diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..61793db
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,6 @@
+#
+# https://help.github.com/articles/dealing-with-line-endings/
+#
+# These are explicitly windows files and should use crlf
+*.bat text eol=crlf
+
diff --git a/.idea/artifacts/AWSSigner_jar.xml b/.idea/artifacts/AWSSigner_jar.xml
deleted file mode 100644
index bffce9e..0000000
--- a/.idea/artifacts/AWSSigner_jar.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
- $PROJECT_DIR$/out/artifacts/AWSSigner_jar
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
deleted file mode 100644
index ddaffea..0000000
--- a/.idea/misc.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index 35eb1dd..0000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/README.md b/README.md
index dabf534..7216030 100644
--- a/README.md
+++ b/README.md
@@ -1,21 +1,23 @@
# AWSSigner
-Burp Extension for AWS Sigv4 Signing
+Burp Extension for AWS SigV4 Signing
-Add your Access Key, Secret Key, Region, and Service to the properties in the extension tab.
+Create a profile in the extension's tab to specify which credentials should be used when signing the request.
-The extension will look for the "X-AMZ-Date" header in all requests being sent by Burp. If it finds a request, it will update the signature in the request. Your request must also have an Authorization header, which should be on all AWS signed requests.
+The extension will check each request passing through Burp. If the request has both the "X-Amz-Date" and "Authorization" header, the request will be re-signed with the specified profile's credentials, and the headers updated.
+
+![AWS Signer](/screenshots/awssigner.png)
## Example Request
-The extenion takes an existing Sigv4 request and updates the Authorization and X-AMZ-Date headers.
+The extension takes an existing SigV4 request and updates the Authorization and X-AMZ-Date headers.
-Here's an example of a Sigv4 request that the extention will update:
+Here's an example of a SigV4 request that the extension will update:
```
GET /?Param1=value1 HTTP/1.1
-Host:example.amazonaws.com
+Host: example.amazonaws.com
Content-Type: application/x-www-form-urlencoded; charset=utf-8
-X-Amz-Date:20150830T123600Z
+X-Amz-Date: 20150830T123600Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20190101/us-west-1/test/request, SignedHeaders=content-type;host;x-amz-date, Signature=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
```
@@ -23,9 +25,96 @@ More information about Sigv4 can be found here:
* https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
+## Extension Tab Interface
+
+The extension's configuration is accessible in Burp Suite under the "AWS Signer" tab. This tab is available in Burp Suite when the extension is added and loaded.
+
+### Global Settings
+
+These settings influence the entire extension's behavior. The settings include:
+* Signing Enabled: If enabled, SigV4 requests will be resigned as they pass through Burp. If disabled, the extension will not modify any requests.
+* Always Sign With: If a profile is selected, all applicable requests will be signed with the specified profile. If unset, requests will be signed using the credentials of the profile with the same "Key Id" value.
+* Log Level: Controls the extension's log verbosity.
+
+![Global Settings](/screenshots/global_settings.png)
+
+### Profile Management
+
+This panel adds/removes profiles. The following buttons are available:
+* Add: Adds a new static credentials, assume role, or command profile. Newly added profiles must have a unique name.
+* Delete: Deletes an existing profile. The extension will check if the profile is referenced by any other existing profiles.
+* Copy: Copies an existing profile. The copy must have a unique name.
+* Import: Imports one or more profiles. See the following section for details.
+* Export: Exports the current profile configurations to a user-selected file.
+
+![Profile Management](/screenshots/profile_management.png)
+
+#### Profile Import
+After clicking the profile import button, a pop-up window allows you to import profiles. Click one of the Source buttons to bring in profiles:
+* Auto: Automatically sources profiles from default credential files (based on the AWS CLI), the clipboard and environment variables
+* File: Allows the user to specify which file to load profiles from. This is useful for importing previously exported profiles.
+* Env: Attempts to import a profile based on the following standardized AWS CLI environment variables:
+ * AWS_ACCESS_KEY_ID
+ * AWS_SECRET_ACCESS_KEY
+ * AWS_SESSION_TOKEN
+* Clipboard: Attempts to automatically recognize and import a profile based on credentials currently copied and held in the user's clipboard.
+
+After sourcing the profiles, use the checkboxes to select which profiles to import into the extension.
+
+![Profile Import](/screenshots/profile_import.png)
+
+### Profile Configuration
+The following settings are available for every profile, regardless of its type:
+* Enabled: When checked, the profile is available for signing requests. Otherwise, it will not be used to modify requests.
+* In-Scope Only: When checked, the profile will only sign requests that are in-scope (as determined by the URL). Otherwise, it will sign any eligible request.
+* Region: When provided, this value replaces the AWS region specified in the request's Authorization header. Otherwise, the request is signed using the same region included in the Authorization header.
+* Service: When provided, this value replaces the AWS service specified in the request's Authorization header. Otherwise, the request is signed using the same service included in the Authorization header.
+* Key Id: When provided, this profile will be used to sign any eligible request whose Authorization header's key id contains the same key id. This can be useful for using one profile to sign certain requests, and have another active profile sign other requests at the same time. This can be any text and does not need to be in the key id format.
+
+#### Test Profile Credentials Button
+This button can be used to test a profile's credentials and ensure they are valid. The credentials are tested by signing a [GetCallerIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html) request and ensuring a successful response. The success or failure is reported in the Status field above.
+
+![Profile Configuration](/screenshots/profile_configuration.png)
+
+### Profile Types
+There are three types of profiles supported by the extension:
+1. Static Credentials: An access key and secret key, with an optional session token.
+2. AssumeRole: The extension will assume a specified role and use the credentials returned. To assume the role, the user must specify another "assumer" profile which will provide credentials required to assume the specified role.
+3. Command: The extension will execute the specified shell command and parse an access key, a secret key and (optionally) a session token.
+
+#### Static Credentials Profile
+The user must provide an access key and a secret key. The session token is optional.
+
+#### AssumeRole Profile
+The user must provide a role ARN which specifies the role to be assumed. The user must also provide credentials to assume this role. These credentials are provided through an "assumer" profile. This allows chaining multiple profiles and roles together when required.
+
+The user may provide the following. See this [API documentation](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) for further details.
+* Session Name: An identifier for the assumed role session.
+* External Id: A unique identifier that might be required when you assume a role in another account.
+* Duration: The lifetime of the session (in seconds). The extension will cache the credentials automatically and re-use them when valid. If the duration is set to 0, the credentials will not be cached and new credentials will be fetched for each request to sign.
+* Session Policy Configuration: An IAM policy in JSON format that you want to use as an inline session policy. This is useful for testing different IAM policies quickly without waiting for the IAM policy to propagate and reach eventual consistency. See [here](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) for further information on session policies.
+
+![AssumeRole Profile Configuration](/screenshots/assume_role_profile.png)
+
+#### Command Profile
+The user must provide a command to be executed which will return AWS credentials in the form of an access key, secret key and (optionally) session token. The command will be executed using either `cmd` (Windows) or `sh` (non-Windows). The extension will attempt to parse the credentials from the command's stdout output. The output does not have a set format, and the credential extraction is based on pattern matching.
+
+The user may provide a Duration. The duration is the lifetime of the credentials (in seconds). The extension will cache the credentials automatically and re-use them when valid. If the duration is set to 0, the credentials will not be cached and the command will be executed for each request that must be signed with the profile.
+
+The extracted credentials show the most recently extracted credentials retrieved by pressing the Test Profile Credentials button. This is intended for debugging purposes.
+
+![Command Profile Configuration](/screenshots/command_profile.png)
+
+## Context Menu
+The extension can be configured by the user while editing a request. Right-click within the request, hover the cusor over Extensions, and then over AWS Signer. The following configuration is available from this location:
+1. Enable/Disable Signing: Signing can be enabled or disabled entirely.
+2. Set Default Signing Profile: The default signing profile can be selected or unset here.
+
+![Context Menu](/screenshots/contextitem.png)
+
## Download
-The most recent jar file can be found in the releases https://github.com/NetSPI/AWSSigner/releases
+The most recent JAR file can be found in the releases https://github.com/NetSPI/AWSSigner/releases
## Build
@@ -34,8 +123,3 @@ The most recent jar file can be found in the releases https://github.com/NetSPI/
3. cd AWSSigner
4. gradle build
5. Jar file will be in the build/libs directory
-
-![Alt text](/screenshots/awssigner.png?raw=true)
-
-![Alt text](/screenshots/contextitem.png?raw=true)
-
diff --git a/build.gradle b/build.gradle
index f96e81d..1616ebe 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,33 +1,48 @@
-group 'com.netspi.awssigner'
-version '1.0-SNAPSHOT'
+group "com.netspi.awssigner"
+version "2.0.0"
-apply plugin: 'java'
+apply plugin: "java"
+
+compileJava {
+ sourceCompatibility = '1.8'
+ targetCompatibility = '1.8'
+}
repositories {
mavenCentral()
}
+def awsSdkVersion = "2.17.116"
+def junitVersion = "5.6.0"
+
dependencies {
- compile 'com.google.guava:guava:23.2-jre'
- compile 'com.intellij:forms_rt:7.0.3'
- compile 'javax.xml.bind:jaxb-api:2.3.0'
- // https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-sts
- compile group: 'com.amazonaws', name: 'aws-java-sdk-sts', version: '1.11.683'
- testCompile group: 'junit', name: 'junit', version: '4.12'
- implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.228')
- implementation 'com.amazonaws:aws-java-sdk-sts'
- testImplementation group: 'junit', name: 'junit', version: '4.11'
+ implementation "com.google.code.gson:gson:2.8.9"
+ implementation "com.google.guava:guava:31.0.1-jre"
+ implementation "net.portswigger.burp.extender:burp-extender-api:2.3"
+ implementation "software.amazon.awssdk:sts:$awsSdkVersion"
+ implementation "software.amazon.awssdk:auth-crt:$awsSdkVersion"
+ testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion"
+ testImplementation "org.junit.jupiter:junit-jupiter-params:$junitVersion"
+ testImplementation "org.junit.jupiter:junit-jupiter-engine:$junitVersion"
}
-def mainClassName = "com.netspi.awssigner.Main"
+test {
+ useJUnitPlatform()
+}
+
+def mainClassName = "com.netspi.awssigner.TestRunner"
jar {
+ dependsOn 'test'
+
manifest {
attributes "Main-Class": "$mainClassName"
}
from {
- configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
+ configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
+
+ duplicatesStrategy "exclude"
}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 87b738c..7454180 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 2e2228b..e750102 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,5 @@
-#Tue Mar 12 11:18:17 CDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip
diff --git a/gradlew b/gradlew
index af6708f..c53aefa 100755
--- a/gradlew
+++ b/gradlew
@@ -1,78 +1,129 @@
-#!/usr/bin/env sh
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
##############################################################################
-##
-## Gradle start up script for UN*X
-##
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
##############################################################################
# Attempt to set APP_HOME
+
# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG=`dirname "$PRG"`"/$link"
- fi
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >/dev/null
-APP_HOME="`pwd -P`"
-cd "$SAVED" >/dev/null
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
+APP_BASE_NAME=${0##*/}
# 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"'
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
+MAX_FD=maximum
warn () {
echo "$*"
-}
+} >&2
die () {
echo
echo "$*"
echo
exit 1
-}
+} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
-case "`uname`" in
- CYGWIN* )
- cygwin=true
- ;;
- Darwin* )
- darwin=true
- ;;
- MINGW* )
- msys=true
- ;;
- NONSTOP* )
- nonstop=true
- ;;
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
+ JAVACMD=$JAVA_HOME/jre/sh/java
else
- JAVACMD="$JAVA_HOME/bin/java"
+ JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -81,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
- JAVACMD="java"
+ 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.
Please set the JAVA_HOME variable in your environment to match the
@@ -89,84 +140,95 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
- MAX_FD_LIMIT=`ulimit -H -n`
- if [ $? -eq 0 ] ; then
- if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
- MAX_FD="$MAX_FD_LIMIT"
- fi
- ulimit -n $MAX_FD
- if [ $? -ne 0 ] ; then
- warn "Could not set maximum file descriptor limit: $MAX_FD"
- fi
- else
- warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
- fi
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
fi
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
- GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
- APP_HOME=`cygpath --path --mixed "$APP_HOME"`
- CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
- JAVACMD=`cygpath --unix "$JAVACMD"`
-
- # We build the pattern for arguments to be converted via cygpath
- ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
- SEP=""
- for dir in $ROOTDIRSRAW ; do
- ROOTDIRS="$ROOTDIRS$SEP$dir"
- SEP="|"
- done
- OURCYGPATTERN="(^($ROOTDIRS))"
- # Add a user-defined pattern to the cygpath arguments
- if [ "$GRADLE_CYGPATTERN" != "" ] ; then
- OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
- fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
- i=0
- for arg in "$@" ; do
- CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
- CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
-
- if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
- eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
- else
- eval `echo args$i`="\"$arg\""
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
fi
- i=$((i+1))
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
done
- case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
- esac
fi
-# Escape application args
-save () {
- for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
- echo " "
-}
-APP_ARGS=$(save "$@")
-
-# Collect all arguments for the java command, following the shell quoting and substitution rules
-eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
-
-# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
-if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
- cd "$(dirname "$0")"
-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.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
index 0f8d593..107acd3 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -1,84 +1,89 @@
-@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=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@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"
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-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 init
-
-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
-
-:init
-@rem Get command-line arguments, handling Windows variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-
-: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 %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="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!
-if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-: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
+
+@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=.
+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%" == "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%"=="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!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/screenshots/assume_role_profile.png b/screenshots/assume_role_profile.png
new file mode 100644
index 0000000..425ef2a
Binary files /dev/null and b/screenshots/assume_role_profile.png differ
diff --git a/screenshots/awssigner.png b/screenshots/awssigner.png
index b1e5565..124d7e0 100644
Binary files a/screenshots/awssigner.png and b/screenshots/awssigner.png differ
diff --git a/screenshots/command_profile.png b/screenshots/command_profile.png
new file mode 100644
index 0000000..443b18d
Binary files /dev/null and b/screenshots/command_profile.png differ
diff --git a/screenshots/contextitem.png b/screenshots/contextitem.png
index 3d2871a..824398f 100644
Binary files a/screenshots/contextitem.png and b/screenshots/contextitem.png differ
diff --git a/screenshots/global_settings.png b/screenshots/global_settings.png
new file mode 100644
index 0000000..ebcbd9e
Binary files /dev/null and b/screenshots/global_settings.png differ
diff --git a/screenshots/profile_configuration.png b/screenshots/profile_configuration.png
new file mode 100644
index 0000000..58c0486
Binary files /dev/null and b/screenshots/profile_configuration.png differ
diff --git a/screenshots/profile_import.png b/screenshots/profile_import.png
new file mode 100644
index 0000000..4037f11
Binary files /dev/null and b/screenshots/profile_import.png differ
diff --git a/screenshots/profile_management.png b/screenshots/profile_management.png
new file mode 100644
index 0000000..929ed37
Binary files /dev/null and b/screenshots/profile_management.png differ
diff --git a/src/main/java/burp/AWSSignerMenuItem.java b/src/main/java/burp/AWSSignerMenuItem.java
deleted file mode 100644
index 90fbc07..0000000
--- a/src/main/java/burp/AWSSignerMenuItem.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package burp;
-
-import javax.swing.*;
-
-public class AWSSignerMenuItem extends JMenuItem {
- private int profileNumber;
- private String itemText;
- private boolean isEnabled;
-
- public AWSSignerMenuItem(String itemText, int profileNumber) {
- this.itemText = itemText;
- this.profileNumber = profileNumber;
-
- // This looks confusing, but "enabled" in terms of the menu item means it looks like you can
- // click on it. We want disabled items to be clickable, because they're the ones you want to change to
- isEnabled = false;
- this.setEnabled(true);
- }
-
- public boolean isProfileEnabled() {
- return isEnabled;
- }
-
- public void enableProfile() {
-
- // See comment in constructor to explain this weirdness
- isEnabled = true;
- this.setEnabled(false);
- }
-
- public void disableProfile() {
-
- // See comment in constructor to explain this weirdness
- isEnabled = false;
- this.setEnabled(true);
- }
-
- public int getProfileNumber() {
- return profileNumber;
- }
-
- public String toString() {
- return itemText;
- }
-
- @Override
- public String getText() {
- return toString();
- }
-}
diff --git a/src/main/java/burp/BurpExtender.java b/src/main/java/burp/BurpExtender.java
index 0ff6504..740ab85 100644
--- a/src/main/java/burp/BurpExtender.java
+++ b/src/main/java/burp/BurpExtender.java
@@ -1,633 +1,212 @@
-package burp;
-
-import com.amazonaws.auth.AWSStaticCredentialsProvider;
-import com.amazonaws.auth.BasicAWSCredentials;
-import com.amazonaws.auth.BasicSessionCredentials;
-import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
-import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
-import com.amazonaws.services.securitytoken.model.*;
-import com.intellij.uiDesigner.core.GridConstraints;
-import com.intellij.uiDesigner.core.GridLayoutManager;
-import com.intellij.uiDesigner.core.Spacer;
-
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.ItemEvent;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.PrintWriter;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Objects;
-import java.util.UUID;
-
-public class BurpExtender implements IBurpExtender, ITab, IHttpListener {
- private IExtensionHelpers helpers;
- private PrintWriter pw;
- private JPanel panel;
- private JTextField accessKey;
- private JTextField secretKey;
- private JTextField token;
- private JTextField region;
- private JTextField service;
- private JTextField roleArn;
- private JCheckBox useToken;
- private JCheckBox dynamicRegionAndService;
- private JComboBox profileComboBox;
- private int numProfiles = 0;
- private JButton saveProfileButton;
- private JButton useProfileButton;
- private JButton deleteProfileButton;
- private JButton assumeRoleButton;
- private boolean justDeleted = false;
- private HashMap profiles;
- private int ACCESS_KEY = 0;
- private int SECRET_KEY = 1;
- private int REGION = 2;
- private int SERVICE = 3;
- private int TOKEN = 4;
- private int USE_TOKEN = 5;
- private int DYNAMIC = 6;
- private int ARN = 7;
-
- @Override
- public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks) {
- helpers = callbacks.getHelpers();
- this.pw = new PrintWriter(callbacks.getStdout(), true);
-
-
- setupTab();
-
- callbacks.setExtensionName("AWS Signer");
-
- callbacks.registerContextMenuFactory(new Menu());
-
- SwingUtilities.invokeLater(() -> {
-
- callbacks.customizeUiComponent(panel);
-
- callbacks.addSuiteTab(BurpExtender.this);
-
- callbacks.registerHttpListener(BurpExtender.this);
- });
-
-
- }
-
- private void createNewProfile() {
-
- // Add another profile to the combo box, or add the add profile button if it's not already there.
- int boxSize = profileComboBox.getItemCount();
- if (boxSize == 0) {
-
- // If there's nothing here, just add our add profile button
- this.profileComboBox.addItem(new AWSSignerMenuItem("Add Profile", 0));
- } else {
-
- // If there is already an add profile button, start creating profiles
- numProfiles++;
- profileComboBox.insertItemAt(new AWSSignerMenuItem("Profile " + numProfiles, numProfiles), boxSize - 1);
- profiles.put(numProfiles, new String[]{"", "", "", "", "", "", "", ""});
- profileComboBox.setSelectedIndex(boxSize - 1);
- clearProfile();
-
- setMenuItems();
- }
- }
-
- private void clearProfile() {
- // Reset text fields
- this.accessKey.setText("");
- this.secretKey.setText("");
- this.token.setText("");
- this.region.setText("");
- this.service.setText("");
- this.roleArn.setText("");
- this.useToken.setSelected(false);
- this.dynamicRegionAndService.setSelected(false);
- this.roleArn.setText("");
- }
-
- private void populateProfile(int profile) {
- this.accessKey.setText(this.profiles.get(profile)[ACCESS_KEY]);
- this.secretKey.setText(this.profiles.get(profile)[SECRET_KEY]);
- this.token.setText(this.profiles.get(profile)[TOKEN]);
- this.region.setText(this.profiles.get(profile)[REGION]);
- this.service.setText(this.profiles.get(profile)[SERVICE]);
- this.useToken.setSelected(Boolean.parseBoolean(this.profiles.get(profile)[USE_TOKEN]));
- this.dynamicRegionAndService.setSelected(Boolean.parseBoolean(this.profiles.get(profile)[DYNAMIC]));
- this.roleArn.setText(this.profiles.get(profile)[ARN]);
-
- }
-
- private void createAndPopulateProfile(String[] details, String name) {
- // Add another profile to the combo box, or add the add profile button if it's not already there.
- int boxSize = profileComboBox.getItemCount();
- // If there's nothing here, just add our add profile button
- if (boxSize == 0) {
- this.profileComboBox.addItem(new AWSSignerMenuItem("Add Profile", 0));
- } else {
- for(int i = 0; i < boxSize; ++i) {
- if(profileComboBox.getItemAt(i).toString().equals(name)) {
- int profileNum = ((AWSSignerMenuItem)profileComboBox.getItemAt(i)).getProfileNumber();
- profiles.replace(profileNum, details);
- profileComboBox.setSelectedIndex(i);
- clearProfile();
- populateProfile(profileNum);
- setMenuItems();
- return;
- }
- }
- // If there is already an add profile button, start creating profiles
- numProfiles++;
- profileComboBox.insertItemAt(new AWSSignerMenuItem(name, numProfiles), boxSize - 1);
- profiles.put(numProfiles, details);
- profileComboBox.setSelectedIndex(boxSize - 1);
- clearProfile();
- populateProfile(numProfiles);
- setMenuItems();
- }
- }
-
- private void createDefaultProfiles() {
- String currentUsersHomeDir = System.getProperty("user.home");
- String[] profileToPut = new String[]{"", "", "", "", "",
- Boolean.toString(false),
- Boolean.toString(true), ""};
- String name = "";
- try {
- File f = new File(currentUsersHomeDir + "/.aws/credentials");
- BufferedReader br = new BufferedReader(new FileReader(f));
- String st;
- while ((st = br.readLine()) != null) {
- if (st.contains("[") && st.contains("]")) {
- if(profileToPut[ACCESS_KEY].isEmpty()) {
- name = st.split("\\[")[1].split("]")[0];
- } else {
- pw.println("Saved profile " + name + " with access key " + profileToPut[ACCESS_KEY]);
- createAndPopulateProfile(profileToPut, name);
- name = st.split("\\[")[1].split("]")[0];
- profileToPut = new String[]{"", "", "", "", "",
- Boolean.toString(false),
- Boolean.toString(true),
- ""};
- }
- } else if (st.startsWith("aws_access_key_id")) {
- profileToPut[ACCESS_KEY] = st.split(" ")[2];
- } else if (st.startsWith("aws_secret_access_key")) {
- profileToPut[SECRET_KEY] = st.split(" ")[2];
- } else if (st.startsWith("aws_security_token")) {
- profileToPut[TOKEN] = st.split(" ")[2];
- profileToPut[USE_TOKEN] = Boolean.toString(true);
- } else {
- pw.println("Invalid line");
- }
- }
- br.close();
- pw.println("Saved profile " + name + " with access key " + profileToPut[ACCESS_KEY]);
- createAndPopulateProfile(profileToPut, name);
- } catch (Exception ex) {
- pw.println("Error reading credentials file: " + ex.getMessage());
- }
- }
-
- private void createEnvironmentVariableProfile() {
- String[] profileToPut = new String[]{"", "", "", "", "",
- Boolean.toString(false),
- Boolean.toString(true), ""};
- String name = "EnvironmentVariables";
- String access = System.getenv("AWS_ACCESS_KEY_ID");
- String secret = System.getenv("AWS_SECRET_ACCESS_KEY");
- if(access != null && secret !=null) {
- profileToPut[ACCESS_KEY] = access;
- profileToPut[SECRET_KEY] = secret;
- } else {
- return;
- }
- String token = System.getenv("AWS_SESSION_TOKEN");
- if(!token.isEmpty()) {
- profileToPut[TOKEN] = token;
- profileToPut[USE_TOKEN] = Boolean.toString(true);
- }
- pw.println("Saved profile " + name + " with access key " + profileToPut[ACCESS_KEY]);
- createAndPopulateProfile(profileToPut, name);
- }
-
- private void setupTab() {
- // Set up profiles combobox
- this.profiles = new HashMap<>();
-
- createNewProfile();
- createDefaultProfiles();
- createEnvironmentVariableProfile();
- createNewProfile();
-
- this.profileComboBox.addItemListener(e -> {
- if (e.getStateChange() == ItemEvent.SELECTED && !justDeleted) {
- int selectedProfile = ((AWSSignerMenuItem) e.getItem()).getProfileNumber();
- if (selectedProfile == 0) {
- pw.println("Creating new profile...");
- createNewProfile();
- } else {
- populateProfile(selectedProfile);
- }
- }
- });
-
- this.saveProfileButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
- int profile = ((AWSSignerMenuItem) Objects.requireNonNull(profileComboBox.getSelectedItem())).getProfileNumber();
- profiles.put(profile,
- new String[]{accessKey.getText(),
- secretKey.getText(),
- region.getText(),
- service.getText(),
- token.getText(),
- String.valueOf(useToken.isSelected()),
- String.valueOf(dynamicRegionAndService.isSelected()),
- roleArn.getText()});
- pw.println("Saved profile " + profile + " with key: " + accessKey.getText());
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
-
- this.deleteProfileButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
- int profile = ((AWSSignerMenuItem) Objects.requireNonNull(profileComboBox.getSelectedItem())).getProfileNumber();
- int index = profileComboBox.getSelectedIndex();
- pw.println("Deleting profile " + profile + "...");
-
- // We need to know this so that when a new item is selected by default by
- // the combobox, we can ignore the action.
- justDeleted = true;
- profileComboBox.removeItemAt(index);
- profiles.remove(profile);
-
- // Determine how we should move our combobox, and what profile we need to populate
- if (profiles.size() > index) {
-
- // There are profiles after this one, move to the newer profile
- profileComboBox.setSelectedIndex(index);
- int newProfile = ((AWSSignerMenuItem) profileComboBox.getSelectedItem()).getProfileNumber();
- populateProfile(newProfile);
- } else if (profiles.size() > 0) {
-
- // No newer profiles, but there are older ones. Move to the older one
- profileComboBox.setSelectedIndex(index - 1);
- int newProfile = ((AWSSignerMenuItem) profileComboBox.getSelectedItem()).getProfileNumber();
- populateProfile(newProfile);
- } else {
-
- // No other profiles exist, create a new one
- createNewProfile();
- }
-
- // If we just deleted our enabled profile, disable the signer
- if (profile == Menu.getEnabledProfile()) {
- Menu.setEnabledProfile(0);
- }
-
- setMenuItems();
-
- justDeleted = false;
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
-
- this.useProfileButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
- int profile = ((AWSSignerMenuItem) Objects.requireNonNull(profileComboBox.getSelectedItem())).getProfileNumber();
- Menu.setEnabledProfile(profile);
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
-
- this.assumeRoleButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
- String[] profile = profiles.get(Menu.getEnabledProfile());
- AWSSecurityTokenService stsClient;
- if(profile[TOKEN].isEmpty()) {
- BasicAWSCredentials awsCreds = new BasicAWSCredentials(profile[ACCESS_KEY], profile[SECRET_KEY]);
- stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
- } else {
- BasicSessionCredentials awsCreds = new BasicSessionCredentials(profile[ACCESS_KEY], profile[SECRET_KEY], profile[TOKEN]);
- stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
- }
- Credentials creds;
- if(roleArn.getText().equals("session-token")) {
- GetSessionTokenRequest session = new GetSessionTokenRequest();
- pw.println("Retrieving session token for " + profile[ACCESS_KEY]);
- creds = stsClient.getSessionToken(session).getCredentials();
- } else {
- String uuid = UUID.randomUUID().toString();
- AssumeRoleRequest assume = new AssumeRoleRequest().withRoleArn(roleArn.getText()).withRoleSessionName(uuid);
- pw.println("Assuming role " + roleArn.getText() + " with role session name " + uuid);
- creds = stsClient.assumeRole(assume).getCredentials();
- }
- String[] details = new String[]{
- creds.getAccessKeyId(), // access key
- creds.getSecretAccessKey(), // secret key
- "", // region
- "", // service
- creds.getSessionToken(), // session token
- Boolean.toString(true), // use token
- Boolean.toString(false), // use default credentials
- ""}; // role ARN
- int profileNum = ((AWSSignerMenuItem) Objects.requireNonNull(profileComboBox.getSelectedItem())).getProfileNumber();
- // Save the profile that holds the role ARN in case user forgets
- String[] save = profiles.get(profileNum);
- save[ARN] = roleArn.getText();
- profiles.replace(profileNum, save);
- // Replace the region and service with the old ones if they're present
- int boxSize = profileComboBox.getItemCount();
- for (int i = 0; i < boxSize; ++i) {
- if (profileComboBox.getItemAt(i).toString().equals(roleArn.getText())) {
- int profileNumOther = ((AWSSignerMenuItem) profileComboBox.getItemAt(i)).getProfileNumber();
- String[] old = profiles.get(profileNumOther);
- details[REGION] = old[REGION];
- details[SERVICE] = old[SERVICE];
- details[DYNAMIC] = old[DYNAMIC];
- }
- }
- createAndPopulateProfile(details, roleArn.getText());
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
- }
-
- // Set the menu items in the context menu
- private void setMenuItems() {
- int itemCount = profileComboBox.getItemCount();
- AWSSignerMenuItem[] menuItems = new AWSSignerMenuItem[itemCount - 1];
-
- // Skip the first item, it's just the add profile button
- for (int i = 0; i < itemCount - 1; i++) {
- menuItems[i] = (AWSSignerMenuItem) profileComboBox.getItemAt(i);
- }
-
- Menu.setMenuItems(menuItems);
- }
-
- @Override
- public String getTabCaption() {
- return "AWS Signer";
- }
-
- @Override
- public Component getUiComponent() {
- return panel;
- }
-
- @Override
- public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) throws Exception {
-
- if(messageIsRequest) {
- if (Menu.getEnabledProfile() > 0) {
- IRequestInfo request = helpers.analyzeRequest(messageInfo.getRequest());
-
- java.util.List headers = request.getHeaders();
-
- if (headers.stream().anyMatch((str -> str.trim().toLowerCase().contains("x-amz-date"))) &&
- headers.stream().anyMatch((str -> str.trim().toLowerCase().contains("authorization")))) {
- String[] profile = this.profiles.get(Menu.getEnabledProfile());
- byte[] signedRequest;
- if (dynamicRegionAndService.isSelected()) {
- String region = "";
- String service = "";
- profile[REGION] = region;
- profile[SERVICE] = service;
- for(String header : headers) {
- if (header.toLowerCase().startsWith("authorization:")){
- String[] splitCredential = header.split("=")[1].split("/");
- region = splitCredential[2];
- service = splitCredential[3];
- }
- }
- pw.println("Signing with profile " + Menu.getEnabledProfile() + " with key: " + profile[ACCESS_KEY]);
- if (Boolean.parseBoolean(profile[USE_TOKEN])) {
- signedRequest = Utility.signRequest(messageInfo,
- helpers,
- service,
- region,
- profile[ACCESS_KEY],
- profile[SECRET_KEY],
- profile[TOKEN],
- pw);
- } else {
- signedRequest = Utility.signRequest(messageInfo,
- helpers,
- service,
- region,
- profile[ACCESS_KEY],
- profile[SECRET_KEY],
- "",
- pw);
- }
- messageInfo.setRequest(signedRequest);
- } else if (!profile[SERVICE].equals("") && !profile[REGION].equals("") &&
- // Removed lower case for service and region since the signature is case-sensitive
- headers.stream().anyMatch((str -> str.trim().contains(profile[SERVICE]))) &&
- headers.stream().anyMatch((str -> str.trim().contains(profile[REGION])))) {
- pw.println("Signing with profile " + Menu.getEnabledProfile() + " with key: " + profile[ACCESS_KEY]);
- if (Boolean.parseBoolean(profile[USE_TOKEN])) {
- signedRequest = Utility.signRequest(messageInfo,
- helpers,
- profile[SERVICE],
- profile[REGION],
- profile[ACCESS_KEY],
- profile[SECRET_KEY],
- profile[TOKEN],
- pw);
- } else {
- signedRequest = Utility.signRequest(messageInfo,
- helpers,
- profile[SERVICE],
- profile[REGION],
- profile[ACCESS_KEY],
- profile[SECRET_KEY],
- "",
- pw);
- }
- messageInfo.setRequest(signedRequest);
- } else {
- messageInfo.setRequest(messageInfo.getRequest());
- pw.println("Request not in defined region and service, not signing");
- }
- }
- }
- }
-
- }
-
- {
-// GUI initializer generated by IntelliJ IDEA GUI Designer
-// >>> IMPORTANT!! <<<
-// DO NOT EDIT OR ADD ANY CODE HERE!
- $$$setupUI$$$();
- }
-
- /**
- * Method generated by IntelliJ IDEA GUI Designer
- * >>> IMPORTANT!! <<<
- * DO NOT edit this method OR call it in your code!
- *
- * @noinspection ALL
- */
- private void $$$setupUI$$$() {
- panel = new JPanel();
- panel.setLayout(new GridLayoutManager(12, 2, new Insets(0, 0, 0, 0), -1, -1));
- final JLabel label1 = new JLabel();
- label1.setText("Access Key: ");
- panel.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- accessKey = new JTextField();
- panel.add(accessKey, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- final JLabel label2 = new JLabel();
- label2.setText("Secret Key:");
- panel.add(label2, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- final JLabel label6 = new JLabel();
- label6.setText("Session Token:");
- panel.add(label6, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- final JLabel label3 = new JLabel();
- label3.setText("Region: ");
- panel.add(label3, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- final JLabel label4 = new JLabel();
- label4.setText("Service: ");
- panel.add(label4, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- secretKey = new JTextField();
- panel.add(secretKey, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- token = new JTextField();
- panel.add(token, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- region = new JTextField();
- panel.add(region, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- service = new JTextField();
- panel.add(service, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- final Spacer spacer1 = new Spacer();
- panel.add(spacer1, new GridConstraints(11, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
- roleArn = new JTextField();
- panel.add(roleArn, new GridConstraints(9, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
- final JLabel label7 = new JLabel();
- label7.setText("Role ARN:");
- panel.add(label7, new GridConstraints(9, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- final JLabel label5 = new JLabel();
- label5.setText("Profile:");
- panel.add(label5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- profileComboBox = new JComboBox();
- final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
- profileComboBox.setModel(defaultComboBoxModel1);
- panel.add(profileComboBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- saveProfileButton = new JButton();
- saveProfileButton.setText("Save Profile");
- useToken = new JCheckBox();
- useToken.setText("Use session token?");
- panel.add(useToken, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- dynamicRegionAndService = new JCheckBox();
- dynamicRegionAndService.setText("Dynamically load region and service from request?");
- panel.add(dynamicRegionAndService, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- panel.add(saveProfileButton, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- final JPanel panel1 = new JPanel();
- panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
- panel.add(panel1, new GridConstraints(11, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
- final JPanel panel2 = new JPanel();
- panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
- panel.add(panel2, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
- deleteProfileButton = new JButton();
- deleteProfileButton.setText("Delete Profile");
- panel2.add(deleteProfileButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, 1, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- useProfileButton = new JButton();
- useProfileButton.setText("Use Profile");
- panel2.add(useProfileButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- assumeRoleButton = new JButton();
- assumeRoleButton.setText("Assume Role");
- panel.add(assumeRoleButton, new GridConstraints(10, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
- }
-
- /**
- * @noinspection ALL
- */
- public JComponent $$$getRootComponent$$$() {
- return panel;
- }
-}
+package burp;
+
+import com.netspi.awssigner.signing.AwsRequestSigner;
+import com.netspi.awssigner.controller.AWSSignerController;
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.AWSSignerConfiguration;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.signing.DelegatingAwsRequestSigner;
+import com.netspi.awssigner.signing.ParsedAuthHeader;
+import com.netspi.awssigner.signing.SigningException;
+import com.netspi.awssigner.view.BurpUIComponentCustomizer;
+import com.netspi.awssigner.view.BurpTabPanel;
+import java.awt.Component;
+import java.util.List;
+import java.util.Optional;
+import javax.swing.JMenuItem;
+import javax.swing.SwingUtilities;
+
+//This is the Burp primary class. It needs to live in this package and have this name
+public class BurpExtender implements IBurpExtender, ITab, IHttpListener, IContextMenuFactory {
+
+ public static final String EXTENSION_NAME = "AWS Signer";
+
+ private BurpTabPanel view;
+ private AWSSignerConfiguration model;
+ private AWSSignerController controller;
+
+ private IBurpExtenderCallbacks callbacks;
+ private IExtensionHelpers helpers;
+
+ @Override
+ public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) {
+
+ //Save callbacks and helpers for later reference
+ this.callbacks = callbacks;
+ helpers = callbacks.getHelpers();
+
+ //Setup styling
+ BurpUIComponentCustomizer.setBurpStyler((Component component) -> {
+ callbacks.customizeUiComponent(component);
+ });
+
+ //Logging
+ LogWriter.configure(callbacks.getStdout(), callbacks.getStderr());
+ LogWriter.logDebug("Logging configured");
+
+ //Create the view
+ view = new BurpTabPanel();
+ //Create the model
+ model = new AWSSignerConfiguration();
+ //Create controller to keep them in sync
+ controller = new AWSSignerController(view, model);
+
+ //register with Burp
+ //set our extension name
+ callbacks.setExtensionName(EXTENSION_NAME);
+
+ //register ourselves with Burp
+ //callbacks.registerContextMenuFactory(new Menu());
+ SwingUtilities.invokeLater(() -> {
+ callbacks.addSuiteTab(BurpExtender.this);
+ callbacks.registerContextMenuFactory(BurpExtender.this);
+ callbacks.registerHttpListener(BurpExtender.this);
+ });
+ }
+
+ @Override
+ public String getTabCaption() {
+ return EXTENSION_NAME;
+ }
+
+ @Override
+ public Component getUiComponent() {
+ //Apply Burp Styling
+ BurpUIComponentCustomizer.applyBurpStyling(view);
+ return view;
+ }
+
+ @Override
+ public List createMenuItems(IContextMenuInvocation invocation) {
+ List menuItems = controller.getMenuItems(invocation);
+ menuItems.forEach(BurpUIComponentCustomizer::applyBurpStyling);
+ return menuItems;
+ }
+
+ @Override
+ public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo) {
+ LogWriter.logDebug("Handling incoming HTTP message.");
+
+ //Check if it's a request. We only sign requests
+ if (!messageIsRequest) {
+ LogWriter.logDebug("Ignoring response.");
+ return;
+ }
+
+ //Is the signer enabled?
+ if (!model.isEnabled) {
+ LogWriter.logDebug("Signing not enabled. Ignoring Message.");
+ return;
+ }
+
+ //Could be a request we want to sign. Let's analyze it
+ IRequestInfo request = helpers.analyzeRequest(messageInfo);
+
+ //Check if this is a SigV4 request
+ if (!isSigV4Request(request)) {
+ LogWriter.logDebug("Message is not a SigV4 request.");
+ return;
+ }
+
+ Optional authHeaderOptional = parseAuthHeader(request);
+ if (authHeaderOptional.isEmpty()) {
+ LogWriter.logError("Unable to parse Authorization header from headers: " + request.getHeaders());
+ return;
+ }
+ ParsedAuthHeader authHeader = authHeaderOptional.get();
+
+ //Try to get the right profile for signing
+ Optional profileOptional = getSigningProfileForRequest(authHeader);
+
+ //Check if we even found a profile
+ if (profileOptional.isEmpty()) {
+ LogWriter.logDebug("Unable to identify correct profile for message.");
+ return;
+ }
+
+ Profile profile = profileOptional.get();
+
+ //Check to see if this profile is even ready for signing
+ //This isn't a guarentee, but a quick assessment if it's NOT ready
+ if (!profile.requiredFieldsAreSet()) {
+ LogWriter.logDebug("Signing profile \"" + profile.getName() + "\" does not have all required fields set. Skipping request.");
+ return;
+ }
+
+ //Check to see if this profile is enabled
+ if (!profile.isEnabled()) {
+ LogWriter.logDebug("Signing profile \"" + profile.getName() + "\" is not enabled. Skipping request.");
+ return;
+ }
+
+ //Check to see if the profile only signs in-scope requests
+ if (profile.isInScopeOnly()) {
+ //Check if our request is in-scope
+ if (!callbacks.isInScope(request.getUrl())) {
+ LogWriter.logDebug("Signing profile \"" + profile.getName() + "\" only signs in-scope requests. "
+ + "The current request is out of scope with URL " + request.getUrl() + " Skipping request");
+ return;
+ }
+ }
+
+ //Looks like we should be good for signing! Let's go
+ //AwsRequestSigner signer = new ClassicAwsRequestSigner(helpers, profile);
+ AwsRequestSigner signer = new DelegatingAwsRequestSigner(helpers, profile);
+ try {
+ byte[] signedRequest = signer.sign(messageInfo, request, authHeader);
+ //Update our message to point to the signed request
+ messageInfo.setRequest(signedRequest);
+ //Add a comment for later identification
+ LogWriter.logInfo("Successfully signed request with profile: " + profile.getName());
+ messageInfo.setComment(String.format("%s signed w/ %s", EXTENSION_NAME, profile.getName()));
+ } catch (SigningException e) {
+ String error = "Unable to sign request with profile "
+ + profile.getName() + " due to exception: " + e.getMessage();
+ LogWriter.logError(error);
+ callbacks.issueAlert(error);//Not sure if this is helpful
+ }
+ }
+
+ private Optional parseAuthHeader(IRequestInfo request) {
+ //Start by dissecting the Authorization header
+ List headers = request.getHeaders();
+ return headers.stream().map(header -> header.trim()) //Trim
+ .map(ParsedAuthHeader::parseFromAuthorizationHeader) //Try to parse if it's the authorization header
+ .filter(Optional::isPresent) //Only keep successfully parsed header
+ .map(Optional::get) //Unwrap optional
+ .findFirst(); //Keep the first match
+ }
+
+ private boolean isSigV4Request(IRequestInfo request) {
+ List headers = request.getHeaders();
+
+ //This is how v1 decided if it should be signed
+ //Looks for both x-amz-date AND authorization
+ return (headers.stream().anyMatch((str -> str.trim().toLowerCase().contains("x-amz-date")))
+ && headers.stream().anyMatch((str -> str.trim().toLowerCase().contains("authorization"))));
+ }
+
+ private Optional getSigningProfileForRequest(ParsedAuthHeader authHeader) {
+ //If we have a default profile set, just use it
+ if (model.alwaysSignWithProfile != null) {
+ return Optional.of(model.alwaysSignWithProfile);
+ }
+
+ String headerAccessKey = authHeader.getAccessKey();
+
+ //Check if any of the profiles are using this access key as their key id
+ Optional accessKeyMatchedProfileOptional = model.profiles.stream().filter(profile -> {
+ return profile.getKeyId().isPresent();
+ }).filter(profile -> {
+ return headerAccessKey.trim().equals(profile.getKeyId().get().trim());
+ }).findFirst();
+
+ if (accessKeyMatchedProfileOptional.isPresent()) {
+ LogWriter.logDebug("Auth header access key \"" + headerAccessKey + "\" matched profile: " + accessKeyMatchedProfileOptional.get().getName());
+ } else {
+ LogWriter.logDebug("Auth header access key \"" + headerAccessKey + "\" did not match a profile.");
+ }
+
+ return accessKeyMatchedProfileOptional;
+ }
+}
diff --git a/src/main/java/burp/IBurpCollaboratorClientContext.java b/src/main/java/burp/IBurpCollaboratorClientContext.java
deleted file mode 100644
index daae9b2..0000000
--- a/src/main/java/burp/IBurpCollaboratorClientContext.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package burp;
-
-/*
- * @(#)IBurpCollaboratorClientContext.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * This interface represents an instance of a Burp Collaborator client context,
- * which can be used to generate Burp Collaborator payloads and poll the
- * Collaborator server for any network interactions that result from using those
- * payloads. Extensions can obtain new instances of this class by calling
- * IBurpExtenderCallbacks.createBurpCollaboratorClientContext()
.
- * Note that each Burp Collaborator client context is tied to the Collaborator
- * server configuration that was in place at the time the context was created.
- */
-public interface IBurpCollaboratorClientContext
-{
-
- /**
- * This method is used to generate new Burp Collaborator payloads.
- *
- * @param includeCollaboratorServerLocation Specifies whether to include the
- * Collaborator server location in the generated payload.
- * @return The payload that was generated.
- */
- String generatePayload(boolean includeCollaboratorServerLocation);
-
- /**
- * This method is used to retrieve all interactions received by the
- * Collaborator server resulting from payloads that were generated for this
- * context.
- *
- * @return The Collaborator interactions that have occurred resulting from
- * payloads that were generated for this context.
- */
- List fetchAllCollaboratorInteractions();
-
- /**
- * This method is used to retrieve interactions received by the Collaborator
- * server resulting from a single payload that was generated for this
- * context.
- *
- * @param payload The payload for which interactions will be retrieved.
- * @return The Collaborator interactions that have occurred resulting from
- * the given payload.
- */
- List fetchCollaboratorInteractionsFor(String payload);
-
- /**
- * This method is used to retrieve all interactions made by Burp Infiltrator
- * instrumentation resulting from payloads that were generated for this
- * context.
- *
- * @return The interactions triggered by the Burp Infiltrator
- * instrumentation that have occurred resulting from payloads that were
- * generated for this context.
- */
- List fetchAllInfiltratorInteractions();
-
- /**
- * This method is used to retrieve interactions made by Burp Infiltrator
- * instrumentation resulting from a single payload that was generated for
- * this context.
- *
- * @param payload The payload for which interactions will be retrieved.
- * @return The interactions triggered by the Burp Infiltrator
- * instrumentation that have occurred resulting from the given payload.
- */
- List fetchInfiltratorInteractionsFor(String payload);
-
- /**
- * This method is used to retrieve the network location of the Collaborator
- * server.
- *
- * @return The hostname or IP address of the Collaborator server.
- */
- String getCollaboratorServerLocation();
-}
diff --git a/src/main/java/burp/IBurpCollaboratorInteraction.java b/src/main/java/burp/IBurpCollaboratorInteraction.java
deleted file mode 100644
index 3af2370..0000000
--- a/src/main/java/burp/IBurpCollaboratorInteraction.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package burp;
-
-/*
- * @(#)IBurpCollaboratorInteraction.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.Map;
-
-/**
- * This interface represents a network interaction that occurred with the Burp
- * Collaborator server.
- */
-public interface IBurpCollaboratorInteraction
-{
-
- /**
- * This method is used to retrieve a property of the interaction. Properties
- * of all interactions are: interaction_id, type, client_ip, and time_stamp.
- * Properties of DNS interactions are: query_type and raw_query. The
- * raw_query value is Base64-encoded. Properties of HTTP interactions are:
- * protocol, request, and response. The request and response values are
- * Base64-encoded.
- *
- * @param name The name of the property to retrieve.
- * @return A string representing the property value, or null if not present.
- */
- String getProperty(String name);
-
- /**
- * This method is used to retrieve a map containing all properties of the
- * interaction.
- *
- * @return A map containing all properties of the interaction.
- */
- Map getProperties();
-}
diff --git a/src/main/java/burp/IBurpExtender.java b/src/main/java/burp/IBurpExtender.java
deleted file mode 100644
index ff6ad12..0000000
--- a/src/main/java/burp/IBurpExtender.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package burp;
-
-/*
- * @(#)IBurpExtender.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * All extensions must implement this interface.
- *
- * Implementations must be called BurpExtender, in the package burp, must be
- * declared public, and must provide a default (public, no-argument)
- * constructor.
- */
-public interface IBurpExtender
-{
- /**
- * This method is invoked when the extension is loaded. It registers an
- * instance of the
- * IBurpExtenderCallbacks
interface, providing methods that may
- * be invoked by the extension to perform various actions.
- *
- * @param callbacks An
- * IBurpExtenderCallbacks
object.
- */
- void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks);
-}
diff --git a/src/main/java/burp/IBurpExtenderCallbacks.java b/src/main/java/burp/IBurpExtenderCallbacks.java
deleted file mode 100644
index a8f6410..0000000
--- a/src/main/java/burp/IBurpExtenderCallbacks.java
+++ /dev/null
@@ -1,1095 +0,0 @@
-package burp;
-
-/*
- * @(#)IBurpExtenderCallbacks.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.Component;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This interface is used by Burp Suite to pass to extensions a set of callback
- * methods that can be used by extensions to perform various actions within
- * Burp.
- *
- * When an extension is loaded, Burp invokes its
- * registerExtenderCallbacks()
method and passes an instance of the
- * IBurpExtenderCallbacks
interface. The extension may then invoke
- * the methods of this interface as required in order to extend Burp's
- * functionality.
- */
-public interface IBurpExtenderCallbacks
-{
-
- /**
- * Flag used to identify Burp Suite as a whole.
- */
- static final int TOOL_SUITE = 0x00000001;
- /**
- * Flag used to identify the Burp Target tool.
- */
- static final int TOOL_TARGET = 0x00000002;
- /**
- * Flag used to identify the Burp Proxy tool.
- */
- static final int TOOL_PROXY = 0x00000004;
- /**
- * Flag used to identify the Burp Spider tool.
- */
- static final int TOOL_SPIDER = 0x00000008;
- /**
- * Flag used to identify the Burp Scanner tool.
- */
- static final int TOOL_SCANNER = 0x00000010;
- /**
- * Flag used to identify the Burp Intruder tool.
- */
- static final int TOOL_INTRUDER = 0x00000020;
- /**
- * Flag used to identify the Burp Repeater tool.
- */
- static final int TOOL_REPEATER = 0x00000040;
- /**
- * Flag used to identify the Burp Sequencer tool.
- */
- static final int TOOL_SEQUENCER = 0x00000080;
- /**
- * Flag used to identify the Burp Decoder tool.
- */
- static final int TOOL_DECODER = 0x00000100;
- /**
- * Flag used to identify the Burp Comparer tool.
- */
- static final int TOOL_COMPARER = 0x00000200;
- /**
- * Flag used to identify the Burp Extender tool.
- */
- static final int TOOL_EXTENDER = 0x00000400;
-
- /**
- * This method is used to set the display name for the current extension,
- * which will be displayed within the user interface for the Extender tool.
- *
- * @param name The extension name.
- */
- void setExtensionName(String name);
-
- /**
- * This method is used to obtain an IExtensionHelpers
object,
- * which can be used by the extension to perform numerous useful tasks.
- *
- * @return An object containing numerous helper methods, for tasks such as
- * building and analyzing HTTP requests.
- */
- IExtensionHelpers getHelpers();
-
- /**
- * This method is used to obtain the current extension's standard output
- * stream. Extensions should write all output to this stream, allowing the
- * Burp user to configure how that output is handled from within the UI.
- *
- * @return The extension's standard output stream.
- */
- OutputStream getStdout();
-
- /**
- * This method is used to obtain the current extension's standard error
- * stream. Extensions should write all error messages to this stream,
- * allowing the Burp user to configure how that output is handled from
- * within the UI.
- *
- * @return The extension's standard error stream.
- */
- OutputStream getStderr();
-
- /**
- * This method prints a line of output to the current extension's standard
- * output stream.
- *
- * @param output The message to print.
- */
- void printOutput(String output);
-
- /**
- * This method prints a line of output to the current extension's standard
- * error stream.
- *
- * @param error The message to print.
- */
- void printError(String error);
-
- /**
- * This method is used to register a listener which will be notified of
- * changes to the extension's state. Note: Any extensions that start
- * background threads or open system resources (such as files or database
- * connections) should register a listener and terminate threads / close
- * resources when the extension is unloaded.
- *
- * @param listener An object created by the extension that implements the
- * IExtensionStateListener
interface.
- */
- void registerExtensionStateListener(IExtensionStateListener listener);
-
- /**
- * This method is used to retrieve the extension state listeners that are
- * registered by the extension.
- *
- * @return A list of extension state listeners that are currently registered
- * by this extension.
- */
- List getExtensionStateListeners();
-
- /**
- * This method is used to remove an extension state listener that has been
- * registered by the extension.
- *
- * @param listener The extension state listener to be removed.
- */
- void removeExtensionStateListener(IExtensionStateListener listener);
-
- /**
- * This method is used to register a listener which will be notified of
- * requests and responses made by any Burp tool. Extensions can perform
- * custom analysis or modification of these messages by registering an HTTP
- * listener.
- *
- * @param listener An object created by the extension that implements the
- * IHttpListener
interface.
- */
- void registerHttpListener(IHttpListener listener);
-
- /**
- * This method is used to retrieve the HTTP listeners that are registered by
- * the extension.
- *
- * @return A list of HTTP listeners that are currently registered by this
- * extension.
- */
- List getHttpListeners();
-
- /**
- * This method is used to remove an HTTP listener that has been registered
- * by the extension.
- *
- * @param listener The HTTP listener to be removed.
- */
- void removeHttpListener(IHttpListener listener);
-
- /**
- * This method is used to register a listener which will be notified of
- * requests and responses being processed by the Proxy tool. Extensions can
- * perform custom analysis or modification of these messages, and control
- * in-UI message interception, by registering a proxy listener.
- *
- * @param listener An object created by the extension that implements the
- * IProxyListener
interface.
- */
- void registerProxyListener(IProxyListener listener);
-
- /**
- * This method is used to retrieve the Proxy listeners that are registered
- * by the extension.
- *
- * @return A list of Proxy listeners that are currently registered by this
- * extension.
- */
- List getProxyListeners();
-
- /**
- * This method is used to remove a Proxy listener that has been registered
- * by the extension.
- *
- * @param listener The Proxy listener to be removed.
- */
- void removeProxyListener(IProxyListener listener);
-
- /**
- * This method is used to register a listener which will be notified of new
- * issues that are reported by the Scanner tool. Extensions can perform
- * custom analysis or logging of Scanner issues by registering a Scanner
- * listener.
- *
- * @param listener An object created by the extension that implements the
- * IScannerListener
interface.
- */
- void registerScannerListener(IScannerListener listener);
-
- /**
- * This method is used to retrieve the Scanner listeners that are registered
- * by the extension.
- *
- * @return A list of Scanner listeners that are currently registered by this
- * extension.
- */
- List getScannerListeners();
-
- /**
- * This method is used to remove a Scanner listener that has been registered
- * by the extension.
- *
- * @param listener The Scanner listener to be removed.
- */
- void removeScannerListener(IScannerListener listener);
-
- /**
- * This method is used to register a listener which will be notified of
- * changes to Burp's suite-wide target scope.
- *
- * @param listener An object created by the extension that implements the
- * IScopeChangeListener
interface.
- */
- void registerScopeChangeListener(IScopeChangeListener listener);
-
- /**
- * This method is used to retrieve the scope change listeners that are
- * registered by the extension.
- *
- * @return A list of scope change listeners that are currently registered by
- * this extension.
- */
- List getScopeChangeListeners();
-
- /**
- * This method is used to remove a scope change listener that has been
- * registered by the extension.
- *
- * @param listener The scope change listener to be removed.
- */
- void removeScopeChangeListener(IScopeChangeListener listener);
-
- /**
- * This method is used to register a factory for custom context menu items.
- * When the user invokes a context menu anywhere within Burp, the factory
- * will be passed details of the invocation event, and asked to provide any
- * custom context menu items that should be shown.
- *
- * @param factory An object created by the extension that implements the
- * IContextMenuFactory
interface.
- */
- void registerContextMenuFactory(IContextMenuFactory factory);
-
- /**
- * This method is used to retrieve the context menu factories that are
- * registered by the extension.
- *
- * @return A list of context menu factories that are currently registered by
- * this extension.
- */
- List getContextMenuFactories();
-
- /**
- * This method is used to remove a context menu factory that has been
- * registered by the extension.
- *
- * @param factory The context menu factory to be removed.
- */
- void removeContextMenuFactory(IContextMenuFactory factory);
-
- /**
- * This method is used to register a factory for custom message editor tabs.
- * For each message editor that already exists, or is subsequently created,
- * within Burp, the factory will be asked to provide a new instance of an
- * IMessageEditorTab
object, which can provide custom rendering
- * or editing of HTTP messages.
- *
- * @param factory An object created by the extension that implements the
- * IMessageEditorTabFactory
interface.
- */
- void registerMessageEditorTabFactory(IMessageEditorTabFactory factory);
-
- /**
- * This method is used to retrieve the message editor tab factories that are
- * registered by the extension.
- *
- * @return A list of message editor tab factories that are currently
- * registered by this extension.
- */
- List getMessageEditorTabFactories();
-
- /**
- * This method is used to remove a message editor tab factory that has been
- * registered by the extension.
- *
- * @param factory The message editor tab factory to be removed.
- */
- void removeMessageEditorTabFactory(IMessageEditorTabFactory factory);
-
- /**
- * This method is used to register a provider of Scanner insertion points.
- * For each base request that is actively scanned, Burp will ask the
- * provider to provide any custom scanner insertion points that are
- * appropriate for the request.
- *
- * @param provider An object created by the extension that implements the
- * IScannerInsertionPointProvider
interface.
- */
- void registerScannerInsertionPointProvider(
- IScannerInsertionPointProvider provider);
-
- /**
- * This method is used to retrieve the Scanner insertion point providers
- * that are registered by the extension.
- *
- * @return A list of Scanner insertion point providers that are currently
- * registered by this extension.
- */
- List getScannerInsertionPointProviders();
-
- /**
- * This method is used to remove a Scanner insertion point provider that has
- * been registered by the extension.
- *
- * @param provider The Scanner insertion point provider to be removed.
- */
- void removeScannerInsertionPointProvider(
- IScannerInsertionPointProvider provider);
-
- /**
- * This method is used to register a custom Scanner check. When performing
- * scanning, Burp will ask the check to perform active or passive scanning
- * on the base request, and report any Scanner issues that are identified.
- *
- * @param check An object created by the extension that implements the
- * IScannerCheck
interface.
- */
- void registerScannerCheck(IScannerCheck check);
-
- /**
- * This method is used to retrieve the Scanner checks that are registered by
- * the extension.
- *
- * @return A list of Scanner checks that are currently registered by this
- * extension.
- */
- List getScannerChecks();
-
- /**
- * This method is used to remove a Scanner check that has been registered by
- * the extension.
- *
- * @param check The Scanner check to be removed.
- */
- void removeScannerCheck(IScannerCheck check);
-
- /**
- * This method is used to register a factory for Intruder payloads. Each
- * registered factory will be available within the Intruder UI for the user
- * to select as the payload source for an attack. When this is selected, the
- * factory will be asked to provide a new instance of an
- * IIntruderPayloadGenerator
object, which will be used to
- * generate payloads for the attack.
- *
- * @param factory An object created by the extension that implements the
- * IIntruderPayloadGeneratorFactory
interface.
- */
- void registerIntruderPayloadGeneratorFactory(
- IIntruderPayloadGeneratorFactory factory);
-
- /**
- * This method is used to retrieve the Intruder payload generator factories
- * that are registered by the extension.
- *
- * @return A list of Intruder payload generator factories that are currently
- * registered by this extension.
- */
- List
- getIntruderPayloadGeneratorFactories();
-
- /**
- * This method is used to remove an Intruder payload generator factory that
- * has been registered by the extension.
- *
- * @param factory The Intruder payload generator factory to be removed.
- */
- void removeIntruderPayloadGeneratorFactory(
- IIntruderPayloadGeneratorFactory factory);
-
- /**
- * This method is used to register a custom Intruder payload processor. Each
- * registered processor will be available within the Intruder UI for the
- * user to select as the action for a payload processing rule.
- *
- * @param processor An object created by the extension that implements the
- * IIntruderPayloadProcessor
interface.
- */
- void registerIntruderPayloadProcessor(IIntruderPayloadProcessor processor);
-
- /**
- * This method is used to retrieve the Intruder payload processors that are
- * registered by the extension.
- *
- * @return A list of Intruder payload processors that are currently
- * registered by this extension.
- */
- List getIntruderPayloadProcessors();
-
- /**
- * This method is used to remove an Intruder payload processor that has been
- * registered by the extension.
- *
- * @param processor The Intruder payload processor to be removed.
- */
- void removeIntruderPayloadProcessor(IIntruderPayloadProcessor processor);
-
- /**
- * This method is used to register a custom session handling action. Each
- * registered action will be available within the session handling rule UI
- * for the user to select as a rule action. Users can choose to invoke an
- * action directly in its own right, or following execution of a macro.
- *
- * @param action An object created by the extension that implements the
- * ISessionHandlingAction
interface.
- */
- void registerSessionHandlingAction(ISessionHandlingAction action);
-
- /**
- * This method is used to retrieve the session handling actions that are
- * registered by the extension.
- *
- * @return A list of session handling actions that are currently registered
- * by this extension.
- */
- List getSessionHandlingActions();
-
- /**
- * This method is used to remove a session handling action that has been
- * registered by the extension.
- *
- * @param action The extension session handling action to be removed.
- */
- void removeSessionHandlingAction(ISessionHandlingAction action);
-
- /**
- * This method is used to unload the extension from Burp Suite.
- */
- void unloadExtension();
-
- /**
- * This method is used to add a custom tab to the main Burp Suite window.
- *
- * @param tab An object created by the extension that implements the
- * ITab
interface.
- */
- void addSuiteTab(ITab tab);
-
- /**
- * This method is used to remove a previously-added tab from the main Burp
- * Suite window.
- *
- * @param tab An object created by the extension that implements the
- * ITab
interface.
- */
- void removeSuiteTab(ITab tab);
-
- /**
- * This method is used to customize UI components in line with Burp's UI
- * style, including font size, colors, table line spacing, etc. The action
- * is performed recursively on any child components of the passed-in
- * component.
- *
- * @param component The UI component to be customized.
- */
- void customizeUiComponent(Component component);
-
- /**
- * This method is used to create a new instance of Burp's HTTP message
- * editor, for the extension to use in its own UI.
- *
- * @param controller An object created by the extension that implements the
- * IMessageEditorController
interface. This parameter is
- * optional and may be null
. If it is provided, then the
- * message editor will query the controller when required to obtain details
- * about the currently displayed message, including the
- * IHttpService
for the message, and the associated request or
- * response message. If a controller is not provided, then the message
- * editor will not support context menu actions, such as sending requests to
- * other Burp tools.
- * @param editable Indicates whether the editor created should be editable,
- * or used only for message viewing.
- * @return An object that implements the IMessageEditor
- * interface, and which the extension can use in its own UI.
- */
- IMessageEditor createMessageEditor(IMessageEditorController controller,
- boolean editable);
-
- /**
- * This method returns the command line arguments that were passed to Burp
- * on startup.
- *
- * @return The command line arguments that were passed to Burp on startup.
- */
- String[] getCommandLineArguments();
-
- /**
- * This method is used to save configuration settings for the extension in a
- * persistent way that survives reloads of the extension and of Burp Suite.
- * Saved settings can be retrieved using the method
- * loadExtensionSetting()
.
- *
- * @param name The name of the setting.
- * @param value The value of the setting. If this value is null
- * then any existing setting with the specified name will be removed.
- */
- void saveExtensionSetting(String name, String value);
-
- /**
- * This method is used to load configuration settings for the extension that
- * were saved using the method saveExtensionSetting()
.
- *
- * @param name The name of the setting.
- * @return The value of the setting, or null
if no value is
- * set.
- */
- String loadExtensionSetting(String name);
-
- /**
- * This method is used to create a new instance of Burp's plain text editor,
- * for the extension to use in its own UI.
- *
- * @return An object that implements the ITextEditor
interface,
- * and which the extension can use in its own UI.
- */
- ITextEditor createTextEditor();
-
- /**
- * This method can be used to send an HTTP request to the Burp Repeater
- * tool. The request will be displayed in the user interface, but will not
- * be issued until the user initiates this action.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @param tabCaption An optional caption which will appear on the Repeater
- * tab containing the request. If this value is null
then a
- * default tab index will be displayed.
- */
- void sendToRepeater(
- String host,
- int port,
- boolean useHttps,
- byte[] request,
- String tabCaption);
-
- /**
- * This method can be used to send an HTTP request to the Burp Intruder
- * tool. The request will be displayed in the user interface, and markers
- * for attack payloads will be placed into default locations within the
- * request.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- */
- void sendToIntruder(
- String host,
- int port,
- boolean useHttps,
- byte[] request);
-
- /**
- * This method can be used to send an HTTP request to the Burp Intruder
- * tool. The request will be displayed in the user interface, and markers
- * for attack payloads will be placed into the specified locations within
- * the request.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @param payloadPositionOffsets A list of index pairs representing the
- * payload positions to be used. Each item in the list must be an int[2]
- * array containing the start and end offsets for the payload position.
- */
- void sendToIntruder(
- String host,
- int port,
- boolean useHttps,
- byte[] request,
- List payloadPositionOffsets);
-
- /**
- * This method can be used to send data to the Comparer tool.
- *
- * @param data The data to be sent to Comparer.
- */
- void sendToComparer(byte[] data);
-
- /**
- * This method can be used to send a seed URL to the Burp Spider tool. If
- * the URL is not within the current Spider scope, the user will be asked if
- * they wish to add the URL to the scope. If the Spider is not currently
- * running, it will be started. The seed URL will be requested, and the
- * Spider will process the application's response in the normal way.
- *
- * @param url The new seed URL to begin spidering from.
- */
- void sendToSpider(
- java.net.URL url);
-
- /**
- * This method can be used to send an HTTP request to the Burp Scanner tool
- * to perform an active vulnerability scan. If the request is not within the
- * current active scanning scope, the user will be asked if they wish to
- * proceed with the scan.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @return The resulting scan queue item.
- */
- IScanQueueItem doActiveScan(
- String host,
- int port,
- boolean useHttps,
- byte[] request);
-
- /**
- * This method can be used to send an HTTP request to the Burp Scanner tool
- * to perform an active vulnerability scan, based on a custom list of
- * insertion points that are to be scanned. If the request is not within the
- * current active scanning scope, the user will be asked if they wish to
- * proceed with the scan.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @param insertionPointOffsets A list of index pairs representing the
- * positions of the insertion points that should be scanned. Each item in
- * the list must be an int[2] array containing the start and end offsets for
- * the insertion point.
- * @return The resulting scan queue item.
- */
- IScanQueueItem doActiveScan(
- String host,
- int port,
- boolean useHttps,
- byte[] request,
- List insertionPointOffsets);
-
- /**
- * This method can be used to send an HTTP request to the Burp Scanner tool
- * to perform a passive vulnerability scan.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @param response The full HTTP response.
- */
- void doPassiveScan(
- String host,
- int port,
- boolean useHttps,
- byte[] request,
- byte[] response);
-
- /**
- * This method can be used to issue HTTP requests and retrieve their
- * responses.
- *
- * @param httpService The HTTP service to which the request should be sent.
- * @param request The full HTTP request.
- * @return An object that implements the IHttpRequestResponse
- * interface, and which the extension can query to obtain the details of the
- * response.
- */
- IHttpRequestResponse makeHttpRequest(IHttpService httpService,
- byte[] request);
-
- /**
- * This method can be used to issue HTTP requests and retrieve their
- * responses.
- *
- * @param host The hostname of the remote HTTP server.
- * @param port The port of the remote HTTP server.
- * @param useHttps Flags whether the protocol is HTTPS or HTTP.
- * @param request The full HTTP request.
- * @return The full response retrieved from the remote server.
- */
- byte[] makeHttpRequest(
- String host,
- int port,
- boolean useHttps,
- byte[] request);
-
- /**
- * This method can be used to query whether a specified URL is within the
- * current Suite-wide scope.
- *
- * @param url The URL to query.
- * @return Returns true
if the URL is within the current
- * Suite-wide scope.
- */
- boolean isInScope(java.net.URL url);
-
- /**
- * This method can be used to include the specified URL in the Suite-wide
- * scope.
- *
- * @param url The URL to include in the Suite-wide scope.
- */
- void includeInScope(java.net.URL url);
-
- /**
- * This method can be used to exclude the specified URL from the Suite-wide
- * scope.
- *
- * @param url The URL to exclude from the Suite-wide scope.
- */
- void excludeFromScope(java.net.URL url);
-
- /**
- * This method can be used to display a specified message in the Burp Suite
- * alerts tab.
- *
- * @param message The alert message to display.
- */
- void issueAlert(String message);
-
- /**
- * This method returns details of all items in the Proxy history.
- *
- * @return The contents of the Proxy history.
- */
- IHttpRequestResponse[] getProxyHistory();
-
- /**
- * This method returns details of items in the site map.
- *
- * @param urlPrefix This parameter can be used to specify a URL prefix, in
- * order to extract a specific subset of the site map. The method performs a
- * simple case-sensitive text match, returning all site map items whose URL
- * begins with the specified prefix. If this parameter is null, the entire
- * site map is returned.
- *
- * @return Details of items in the site map.
- */
- IHttpRequestResponse[] getSiteMap(String urlPrefix);
-
- /**
- * This method returns all of the current scan issues for URLs matching the
- * specified literal prefix.
- *
- * @param urlPrefix This parameter can be used to specify a URL prefix, in
- * order to extract a specific subset of scan issues. The method performs a
- * simple case-sensitive text match, returning all scan issues whose URL
- * begins with the specified prefix. If this parameter is null, all issues
- * are returned.
- * @return Details of the scan issues.
- */
- IScanIssue[] getScanIssues(String urlPrefix);
-
- /**
- * This method is used to generate a report for the specified Scanner
- * issues. The report format can be specified. For all other reporting
- * options, the default settings that appear in the reporting UI wizard are
- * used.
- *
- * @param format The format to be used in the report. Accepted values are
- * HTML and XML.
- * @param issues The Scanner issues to be reported.
- * @param file The file to which the report will be saved.
- */
- void generateScanReport(String format, IScanIssue[] issues,
- java.io.File file);
-
- /**
- * This method is used to retrieve the contents of Burp's session handling
- * cookie jar. Extensions that provide an
- * ISessionHandlingAction
can query and update the cookie jar
- * in order to handle unusual session handling mechanisms.
- *
- * @return A list of ICookie
objects representing the contents
- * of Burp's session handling cookie jar.
- */
- List getCookieJarContents();
-
- /**
- * This method is used to update the contents of Burp's session handling
- * cookie jar. Extensions that provide an
- * ISessionHandlingAction
can query and update the cookie jar
- * in order to handle unusual session handling mechanisms.
- *
- * @param cookie An ICookie
object containing details of the
- * cookie to be updated. If the cookie jar already contains a cookie that
- * matches the specified domain and name, then that cookie will be updated
- * with the new value and expiration, unless the new value is
- * null
, in which case the cookie will be removed. If the
- * cookie jar does not already contain a cookie that matches the specified
- * domain and name, then the cookie will be added.
- */
- void updateCookieJar(ICookie cookie);
-
- /**
- * This method can be used to add an item to Burp's site map with the
- * specified request/response details. This will overwrite the details of
- * any existing matching item in the site map.
- *
- * @param item Details of the item to be added to the site map
- */
- void addToSiteMap(IHttpRequestResponse item);
-
- /**
- * This method can be used to restore Burp's state from a specified saved
- * state file. This method blocks until the restore operation is completed,
- * and must not be called from the event dispatch thread.
- *
- * @param file The file containing Burp's saved state.
- * @deprecated State files have been replaced with Burp project files.
- */
- @Deprecated
- void restoreState(java.io.File file);
-
- /**
- * This method can be used to save Burp's state to a specified file. This
- * method blocks until the save operation is completed, and must not be
- * called from the event dispatch thread.
- *
- * @param file The file to save Burp's state in.
- * @deprecated State files have been replaced with Burp project files.
- */
- @Deprecated
- void saveState(java.io.File file);
-
- /**
- * This method causes Burp to save all of its current configuration as a Map
- * of name/value Strings.
- *
- * @return A Map of name/value Strings reflecting Burp's current
- * configuration.
- * @deprecated Use saveConfigAsJson()
instead.
- */
- @Deprecated
- Map saveConfig();
-
- /**
- * This method causes Burp to load a new configuration from the Map of
- * name/value Strings provided. Any settings not specified in the Map will
- * be restored to their default values. To selectively update only some
- * settings and leave the rest unchanged, you should first call
- * saveConfig()
to obtain Burp's current configuration, modify
- * the relevant items in the Map, and then call loadConfig()
- * with the same Map.
- *
- * @param config A map of name/value Strings to use as Burp's new
- * configuration.
- * @deprecated Use loadConfigFromJson()
instead.
- */
- @Deprecated
- void loadConfig(Map config);
-
- /**
- * This method causes Burp to save its current project-level configuration
- * in JSON format. This is the same format that can be saved and loaded via
- * the Burp user interface. To include only certain sections of the
- * configuration, you can optionally supply the path to each section that
- * should be included, for example: "project_options.connections". If no
- * paths are provided, then the entire configuration will be saved.
- *
- * @param configPaths A list of Strings representing the path to each
- * configuration section that should be included.
- * @return A String representing the current configuration in JSON format.
- */
- String saveConfigAsJson(String... configPaths);
-
- /**
- * This method causes Burp to load a new project-level configuration from
- * the JSON String provided. This is the same format that can be saved and
- * loaded via the Burp user interface. Partial configurations are
- * acceptable, and any settings not specified will be left unmodified.
- *
- * Any user-level configuration options contained in the input will be
- * ignored.
- *
- * @param config A JSON String containing the new configuration.
- */
- void loadConfigFromJson(String config);
-
- /**
- * This method sets the master interception mode for Burp Proxy.
- *
- * @param enabled Indicates whether interception of Proxy messages should be
- * enabled.
- */
- void setProxyInterceptionEnabled(boolean enabled);
-
- /**
- * This method retrieves information about the version of Burp in which the
- * extension is running. It can be used by extensions to dynamically adjust
- * their behavior depending on the functionality and APIs supported by the
- * current version.
- *
- * @return An array of Strings comprised of: the product name (e.g. Burp
- * Suite Professional), the major version (e.g. 1.5), the minor version
- * (e.g. 03)
- */
- String[] getBurpVersion();
-
- /**
- * This method retrieves the absolute path name of the file from which the
- * current extension was loaded.
- *
- * @return The absolute path name of the file from which the current
- * extension was loaded.
- */
- String getExtensionFilename();
-
- /**
- * This method determines whether the current extension was loaded as a BApp
- * (a Burp App from the BApp Store).
- *
- * @return Returns true if the current extension was loaded as a BApp.
- */
- boolean isExtensionBapp();
-
- /**
- * This method can be used to shut down Burp programmatically, with an
- * optional prompt to the user. If the method returns, the user canceled the
- * shutdown prompt.
- *
- * @param promptUser Indicates whether to prompt the user to confirm the
- * shutdown.
- */
- void exitSuite(boolean promptUser);
-
- /**
- * This method is used to create a temporary file on disk containing the
- * provided data. Extensions can use temporary files for long-term storage
- * of runtime data, avoiding the need to retain that data in memory.
- *
- * @param buffer The data to be saved to a temporary file.
- * @return An object that implements the ITempFile
interface.
- */
- ITempFile saveToTempFile(byte[] buffer);
-
- /**
- * This method is used to save the request and response of an
- * IHttpRequestResponse
object to temporary files, so that they
- * are no longer held in memory. Extensions can used this method to convert
- * IHttpRequestResponse
objects into a form suitable for
- * long-term storage.
- *
- * @param httpRequestResponse The IHttpRequestResponse
object
- * whose request and response messages are to be saved to temporary files.
- * @return An object that implements the
- * IHttpRequestResponsePersisted
interface.
- */
- IHttpRequestResponsePersisted saveBuffersToTempFiles(
- IHttpRequestResponse httpRequestResponse);
-
- /**
- * This method is used to apply markers to an HTTP request or response, at
- * offsets into the message that are relevant for some particular purpose.
- * Markers are used in various situations, such as specifying Intruder
- * payload positions, Scanner insertion points, and highlights in Scanner
- * issues.
- *
- * @param httpRequestResponse The IHttpRequestResponse
object
- * to which the markers should be applied.
- * @param requestMarkers A list of index pairs representing the offsets of
- * markers to be applied to the request message. Each item in the list must
- * be an int[2] array containing the start and end offsets for the marker.
- * The markers in the list should be in sequence and not overlapping. This
- * parameter is optional and may be null
if no request markers
- * are required.
- * @param responseMarkers A list of index pairs representing the offsets of
- * markers to be applied to the response message. Each item in the list must
- * be an int[2] array containing the start and end offsets for the marker.
- * The markers in the list should be in sequence and not overlapping. This
- * parameter is optional and may be null
if no response markers
- * are required.
- * @return An object that implements the
- * IHttpRequestResponseWithMarkers
interface.
- */
- IHttpRequestResponseWithMarkers applyMarkers(
- IHttpRequestResponse httpRequestResponse,
- List requestMarkers,
- List responseMarkers);
-
- /**
- * This method is used to obtain the descriptive name for the Burp tool
- * identified by the tool flag provided.
- *
- * @param toolFlag A flag identifying a Burp tool ( TOOL_PROXY
,
- * TOOL_SCANNER
, etc.). Tool flags are defined within this
- * interface.
- * @return The descriptive name for the specified tool.
- */
- String getToolName(int toolFlag);
-
- /**
- * This method is used to register a new Scanner issue. Note:
- * Wherever possible, extensions should implement custom Scanner checks
- * using IScannerCheck
and report issues via those checks, so
- * as to integrate with Burp's user-driven workflow, and ensure proper
- * consolidation of duplicate reported issues. This method is only designed
- * for tasks outside of the normal testing workflow, such as importing
- * results from other scanning tools.
- *
- * @param issue An object created by the extension that implements the
- * IScanIssue
interface.
- */
- void addScanIssue(IScanIssue issue);
-
- /**
- * This method is used to create a new Burp Collaborator client context,
- * which can be used to generate Burp Collaborator payloads and poll the
- * Collaborator server for any network interactions that result from using
- * those payloads.
- *
- * @return A new instance of IBurpCollaboratorClientContext
- * that can be used to generate Collaborator payloads and retrieve
- * interactions.
- */
- IBurpCollaboratorClientContext createBurpCollaboratorClientContext();
-
- /**
- * This method parses the specified request and returns details of each
- * request parameter.
- *
- * @param request The request to be parsed.
- * @return An array of: String[] { name, value, type }
- * containing details of the parameters contained within the request.
- * @deprecated Use IExtensionHelpers.analyzeRequest()
instead.
- */
- @Deprecated
- String[][] getParameters(byte[] request);
-
- /**
- * This method parses the specified request and returns details of each HTTP
- * header.
- *
- * @param message The request to be parsed.
- * @return An array of HTTP headers.
- * @deprecated Use IExtensionHelpers.analyzeRequest()
or
- * IExtensionHelpers.analyzeResponse()
instead.
- */
- @Deprecated
- String[] getHeaders(byte[] message);
-
- /**
- * This method can be used to register a new menu item which will appear on
- * the various context menus that are used throughout Burp Suite to handle
- * user-driven actions.
- *
- * @param menuItemCaption The caption to be displayed on the menu item.
- * @param menuItemHandler The handler to be invoked when the user clicks on
- * the menu item.
- * @deprecated Use registerContextMenuFactory()
instead.
- */
- @Deprecated
- void registerMenuItem(
- String menuItemCaption,
- IMenuItemHandler menuItemHandler);
-}
diff --git a/src/main/java/burp/IContextMenuFactory.java b/src/main/java/burp/IContextMenuFactory.java
deleted file mode 100644
index df316cc..0000000
--- a/src/main/java/burp/IContextMenuFactory.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package burp;
-
-/*
- * @(#)IContextMenuFactory.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-
-import javax.swing.JMenuItem;
-import java.util.List;
-
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerContextMenuFactory()
to register
- * a factory for custom context menu items.
- */
-public interface IContextMenuFactory
-{
- /**
- * This method will be called by Burp when the user invokes a context menu
- * anywhere within Burp. The factory can then provide any custom context
- * menu items that should be displayed in the context menu, based on the
- * details of the menu invocation.
- *
- * @param invocation An object that implements the
- * IContextMenuInvocation
interface, which the extension can
- * query to obtain details of the context menu invocation.
- * @return A list of custom menu items (which may include sub-menus,
- * checkbox menu items, etc.) that should be displayed. Extensions may
- * return
- * null
from this method, to indicate that no menu items are
- * required.
- */
- List createMenuItems(IContextMenuInvocation invocation);
-}
diff --git a/src/main/java/burp/IContextMenuInvocation.java b/src/main/java/burp/IContextMenuInvocation.java
deleted file mode 100644
index 27f8553..0000000
--- a/src/main/java/burp/IContextMenuInvocation.java
+++ /dev/null
@@ -1,156 +0,0 @@
-package burp;
-
-/*
- * @(#)IContextMenuInvocation.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.event.InputEvent;
-
-/**
- * This interface is used when Burp calls into an extension-provided
- * IContextMenuFactory
with details of a context menu invocation.
- * The custom context menu factory can query this interface to obtain details of
- * the invocation event, in order to determine what menu items should be
- * displayed.
- */
-public interface IContextMenuInvocation
-{
- /**
- * Used to indicate that the context menu is being invoked in a request
- * editor.
- */
- static final byte CONTEXT_MESSAGE_EDITOR_REQUEST = 0;
- /**
- * Used to indicate that the context menu is being invoked in a response
- * editor.
- */
- static final byte CONTEXT_MESSAGE_EDITOR_RESPONSE = 1;
- /**
- * Used to indicate that the context menu is being invoked in a non-editable
- * request viewer.
- */
- static final byte CONTEXT_MESSAGE_VIEWER_REQUEST = 2;
- /**
- * Used to indicate that the context menu is being invoked in a non-editable
- * response viewer.
- */
- static final byte CONTEXT_MESSAGE_VIEWER_RESPONSE = 3;
- /**
- * Used to indicate that the context menu is being invoked in the Target
- * site map tree.
- */
- static final byte CONTEXT_TARGET_SITE_MAP_TREE = 4;
- /**
- * Used to indicate that the context menu is being invoked in the Target
- * site map table.
- */
- static final byte CONTEXT_TARGET_SITE_MAP_TABLE = 5;
- /**
- * Used to indicate that the context menu is being invoked in the Proxy
- * history.
- */
- static final byte CONTEXT_PROXY_HISTORY = 6;
- /**
- * Used to indicate that the context menu is being invoked in the Scanner
- * results.
- */
- static final byte CONTEXT_SCANNER_RESULTS = 7;
- /**
- * Used to indicate that the context menu is being invoked in the Intruder
- * payload positions editor.
- */
- static final byte CONTEXT_INTRUDER_PAYLOAD_POSITIONS = 8;
- /**
- * Used to indicate that the context menu is being invoked in an Intruder
- * attack results.
- */
- static final byte CONTEXT_INTRUDER_ATTACK_RESULTS = 9;
- /**
- * Used to indicate that the context menu is being invoked in a search
- * results window.
- */
- static final byte CONTEXT_SEARCH_RESULTS = 10;
-
- /**
- * This method can be used to retrieve the native Java input event that was
- * the trigger for the context menu invocation.
- *
- * @return The InputEvent
that was the trigger for the context
- * menu invocation.
- */
- InputEvent getInputEvent();
-
- /**
- * This method can be used to retrieve the Burp tool within which the
- * context menu was invoked.
- *
- * @return A flag indicating the Burp tool within which the context menu was
- * invoked. Burp tool flags are defined in the
- * IBurpExtenderCallbacks
interface.
- */
- int getToolFlag();
-
- /**
- * This method can be used to retrieve the context within which the menu was
- * invoked.
- *
- * @return An index indicating the context within which the menu was
- * invoked. The indices used are defined within this interface.
- */
- byte getInvocationContext();
-
- /**
- * This method can be used to retrieve the bounds of the user's selection
- * into the current message, if applicable.
- *
- * @return An int[2] array containing the start and end offsets of the
- * user's selection in the current message. If the user has not made any
- * selection in the current message, both offsets indicate the position of
- * the caret within the editor. If the menu is not being invoked from a
- * message editor, the method returns null
.
- */
- int[] getSelectionBounds();
-
- /**
- * This method can be used to retrieve details of the HTTP requests /
- * responses that were shown or selected by the user when the context menu
- * was invoked.
- *
- * Note: For performance reasons, the objects returned from this
- * method are tied to the originating context of the messages within the
- * Burp UI. For example, if a context menu is invoked on the Proxy intercept
- * panel, then the
- * IHttpRequestResponse
returned by this method will reflect
- * the current contents of the interception panel, and this will change when
- * the current message has been forwarded or dropped. If your extension
- * needs to store details of the message for which the context menu has been
- * invoked, then you should query those details from the
- * IHttpRequestResponse
at the time of invocation, or you
- * should use
- * IBurpExtenderCallbacks.saveBuffersToTempFiles()
to create a
- * persistent read-only copy of the
- * IHttpRequestResponse
.
- *
- * @return An array of IHttpRequestResponse
objects
- * representing the items that were shown or selected by the user when the
- * context menu was invoked. This method returns null
if no
- * messages are applicable to the invocation.
- */
- IHttpRequestResponse[] getSelectedMessages();
-
- /**
- * This method can be used to retrieve details of the Scanner issues that
- * were selected by the user when the context menu was invoked.
- *
- * @return An array of IScanIssue
objects representing the
- * issues that were selected by the user when the context menu was invoked.
- * This method returns null
if no Scanner issues are applicable
- * to the invocation.
- */
- IScanIssue[] getSelectedIssues();
-}
diff --git a/src/main/java/burp/ICookie.java b/src/main/java/burp/ICookie.java
deleted file mode 100644
index c44a311..0000000
--- a/src/main/java/burp/ICookie.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package burp;
-
-/*
- * @(#)ICookie.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.Date;
-
-/**
- * This interface is used to hold details about an HTTP cookie.
- */
-public interface ICookie
-{
- /**
- * This method is used to retrieve the domain for which the cookie is in
- * scope.
- *
- * @return The domain for which the cookie is in scope. Note: For
- * cookies that have been analyzed from responses (by calling
- * IExtensionHelpers.analyzeResponse()
and then
- * IResponseInfo.getCookies()
, the domain will be
- * null
if the response did not explicitly set a domain
- * attribute for the cookie.
- */
- String getDomain();
-
- /**
- * This method is used to retrieve the path for which the cookie is in
- * scope.
- *
- * @return The path for which the cookie is in scope or null if none is set.
- */
- String getPath();
-
- /**
- * This method is used to retrieve the expiration time for the cookie.
- *
- * @return The expiration time for the cookie, or
- * null
if none is set (i.e., for non-persistent session
- * cookies).
- */
- Date getExpiration();
-
- /**
- * This method is used to retrieve the name of the cookie.
- *
- * @return The name of the cookie.
- */
- String getName();
-
- /**
- * This method is used to retrieve the value of the cookie.
- * @return The value of the cookie.
- */
- String getValue();
-}
diff --git a/src/main/java/burp/IExtensionHelpers.java b/src/main/java/burp/IExtensionHelpers.java
deleted file mode 100644
index af305e6..0000000
--- a/src/main/java/burp/IExtensionHelpers.java
+++ /dev/null
@@ -1,356 +0,0 @@
-package burp;
-
-/*
- * @(#)IExtensionHelpers.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.net.URL;
-import java.util.List;
-
-/**
- * This interface contains a number of helper methods, which extensions can use
- * to assist with various common tasks that arise for Burp extensions.
- *
- * Extensions can call IBurpExtenderCallbacks.getHelpers
to obtain
- * an instance of this interface.
- */
-public interface IExtensionHelpers
-{
-
- /**
- * This method can be used to analyze an HTTP request, and obtain various
- * key details about it.
- *
- * @param request An IHttpRequestResponse
object containing the
- * request to be analyzed.
- * @return An IRequestInfo
object that can be queried to obtain
- * details about the request.
- */
- IRequestInfo analyzeRequest(IHttpRequestResponse request);
-
- /**
- * This method can be used to analyze an HTTP request, and obtain various
- * key details about it.
- *
- * @param httpService The HTTP service associated with the request. This is
- * optional and may be null
, in which case the resulting
- * IRequestInfo
object will not include the full request URL.
- * @param request The request to be analyzed.
- * @return An IRequestInfo
object that can be queried to obtain
- * details about the request.
- */
- IRequestInfo analyzeRequest(IHttpService httpService, byte[] request);
-
- /**
- * This method can be used to analyze an HTTP request, and obtain various
- * key details about it. The resulting IRequestInfo
object will
- * not include the full request URL. To obtain the full URL, use one of the
- * other overloaded analyzeRequest()
methods.
- *
- * @param request The request to be analyzed.
- * @return An IRequestInfo
object that can be queried to obtain
- * details about the request.
- */
- IRequestInfo analyzeRequest(byte[] request);
-
- /**
- * This method can be used to analyze an HTTP response, and obtain various
- * key details about it.
- *
- * @param response The response to be analyzed.
- * @return An IResponseInfo
object that can be queried to
- * obtain details about the response.
- */
- IResponseInfo analyzeResponse(byte[] response);
-
- /**
- * This method can be used to retrieve details of a specified parameter
- * within an HTTP request. Note: Use analyzeRequest()
to
- * obtain details of all parameters within the request.
- *
- * @param request The request to be inspected for the specified parameter.
- * @param parameterName The name of the parameter to retrieve.
- * @return An IParameter
object that can be queried to obtain
- * details about the parameter, or null
if the parameter was
- * not found.
- */
- IParameter getRequestParameter(byte[] request, String parameterName);
-
- /**
- * This method can be used to URL-decode the specified data.
- *
- * @param data The data to be decoded.
- * @return The decoded data.
- */
- String urlDecode(String data);
-
- /**
- * This method can be used to URL-encode the specified data. Any characters
- * that do not need to be encoded within HTTP requests are not encoded.
- *
- * @param data The data to be encoded.
- * @return The encoded data.
- */
- String urlEncode(String data);
-
- /**
- * This method can be used to URL-decode the specified data.
- *
- * @param data The data to be decoded.
- * @return The decoded data.
- */
- byte[] urlDecode(byte[] data);
-
- /**
- * This method can be used to URL-encode the specified data. Any characters
- * that do not need to be encoded within HTTP requests are not encoded.
- *
- * @param data The data to be encoded.
- * @return The encoded data.
- */
- byte[] urlEncode(byte[] data);
-
- /**
- * This method can be used to Base64-decode the specified data.
- *
- * @param data The data to be decoded.
- * @return The decoded data.
- */
- byte[] base64Decode(String data);
-
- /**
- * This method can be used to Base64-decode the specified data.
- *
- * @param data The data to be decoded.
- * @return The decoded data.
- */
- byte[] base64Decode(byte[] data);
-
- /**
- * This method can be used to Base64-encode the specified data.
- *
- * @param data The data to be encoded.
- * @return The encoded data.
- */
- String base64Encode(String data);
-
- /**
- * This method can be used to Base64-encode the specified data.
- *
- * @param data The data to be encoded.
- * @return The encoded data.
- */
- String base64Encode(byte[] data);
-
- /**
- * This method can be used to convert data from String form into an array of
- * bytes. The conversion does not reflect any particular character set, and
- * a character with the hex representation 0xWXYZ will always be converted
- * into a byte with the representation 0xYZ. It performs the opposite
- * conversion to the method bytesToString()
, and byte-based
- * data that is converted to a String and back again using these two methods
- * is guaranteed to retain its integrity (which may not be the case with
- * conversions that reflect a given character set).
- *
- * @param data The data to be converted.
- * @return The converted data.
- */
- byte[] stringToBytes(String data);
-
- /**
- * This method can be used to convert data from an array of bytes into
- * String form. The conversion does not reflect any particular character
- * set, and a byte with the representation 0xYZ will always be converted
- * into a character with the hex representation 0x00YZ. It performs the
- * opposite conversion to the method stringToBytes()
, and
- * byte-based data that is converted to a String and back again using these
- * two methods is guaranteed to retain its integrity (which may not be the
- * case with conversions that reflect a given character set).
- *
- * @param data The data to be converted.
- * @return The converted data.
- */
- String bytesToString(byte[] data);
-
- /**
- * This method searches a piece of data for the first occurrence of a
- * specified pattern. It works on byte-based data in a way that is similar
- * to the way the native Java method String.indexOf()
works on
- * String-based data.
- *
- * @param data The data to be searched.
- * @param pattern The pattern to be searched for.
- * @param caseSensitive Flags whether or not the search is case-sensitive.
- * @param from The offset within data
where the search should
- * begin.
- * @param to The offset within data
where the search should
- * end.
- * @return The offset of the first occurrence of the pattern within the
- * specified bounds, or -1 if no match is found.
- */
- int indexOf(byte[] data,
- byte[] pattern,
- boolean caseSensitive,
- int from,
- int to);
-
- /**
- * This method builds an HTTP message containing the specified headers and
- * message body. If applicable, the Content-Length header will be added or
- * updated, based on the length of the body.
- *
- * @param headers A list of headers to include in the message.
- * @param body The body of the message, of null
if the message
- * has an empty body.
- * @return The resulting full HTTP message.
- */
- byte[] buildHttpMessage(List headers, byte[] body);
-
- /**
- * This method creates a GET request to the specified URL. The headers used
- * in the request are determined by the Request headers settings as
- * configured in Burp Spider's options.
- *
- * @param url The URL to which the request should be made.
- * @return A request to the specified URL.
- */
- byte[] buildHttpRequest(URL url);
-
- /**
- * This method adds a new parameter to an HTTP request, and if appropriate
- * updates the Content-Length header.
- *
- * @param request The request to which the parameter should be added.
- * @param parameter An IParameter
object containing details of
- * the parameter to be added. Supported parameter types are:
- * PARAM_URL
, PARAM_BODY
and
- * PARAM_COOKIE
.
- * @return A new HTTP request with the new parameter added.
- */
- byte[] addParameter(byte[] request, IParameter parameter);
-
- /**
- * This method removes a parameter from an HTTP request, and if appropriate
- * updates the Content-Length header.
- *
- * @param request The request from which the parameter should be removed.
- * @param parameter An IParameter
object containing details of
- * the parameter to be removed. Supported parameter types are:
- * PARAM_URL
, PARAM_BODY
and
- * PARAM_COOKIE
.
- * @return A new HTTP request with the parameter removed.
- */
- byte[] removeParameter(byte[] request, IParameter parameter);
-
- /**
- * This method updates the value of a parameter within an HTTP request, and
- * if appropriate updates the Content-Length header. Note: This
- * method can only be used to update the value of an existing parameter of a
- * specified type. If you need to change the type of an existing parameter,
- * you should first call removeParameter()
to remove the
- * parameter with the old type, and then call addParameter()
to
- * add a parameter with the new type.
- *
- * @param request The request containing the parameter to be updated.
- * @param parameter An IParameter
object containing details of
- * the parameter to be updated. Supported parameter types are:
- * PARAM_URL
, PARAM_BODY
and
- * PARAM_COOKIE
.
- * @return A new HTTP request with the parameter updated.
- */
- byte[] updateParameter(byte[] request, IParameter parameter);
-
- /**
- * This method can be used to toggle a request's method between GET and
- * POST. Parameters are relocated between the URL query string and message
- * body as required, and the Content-Length header is created or removed as
- * applicable.
- *
- * @param request The HTTP request whose method should be toggled.
- * @return A new HTTP request using the toggled method.
- */
- byte[] toggleRequestMethod(byte[] request);
-
- /**
- * This method constructs an IHttpService
object based on the
- * details provided.
- *
- * @param host The HTTP service host.
- * @param port The HTTP service port.
- * @param protocol The HTTP service protocol.
- * @return An IHttpService
object based on the details
- * provided.
- */
- IHttpService buildHttpService(String host, int port, String protocol);
-
- /**
- * This method constructs an IHttpService
object based on the
- * details provided.
- *
- * @param host The HTTP service host.
- * @param port The HTTP service port.
- * @param useHttps Flags whether the HTTP service protocol is HTTPS or HTTP.
- * @return An IHttpService
object based on the details
- * provided.
- */
- IHttpService buildHttpService(String host, int port, boolean useHttps);
-
- /**
- * This method constructs an IParameter
object based on the
- * details provided.
- *
- * @param name The parameter name.
- * @param value The parameter value.
- * @param type The parameter type, as defined in the IParameter
- * interface.
- * @return An IParameter
object based on the details provided.
- */
- IParameter buildParameter(String name, String value, byte type);
-
- /**
- * This method constructs an IScannerInsertionPoint
object
- * based on the details provided. It can be used to quickly create a simple
- * insertion point based on a fixed payload location within a base request.
- *
- * @param insertionPointName The name of the insertion point.
- * @param baseRequest The request from which to build scan requests.
- * @param from The offset of the start of the payload location.
- * @param to The offset of the end of the payload location.
- * @return An IScannerInsertionPoint
object based on the
- * details provided.
- */
- IScannerInsertionPoint makeScannerInsertionPoint(
- String insertionPointName,
- byte[] baseRequest,
- int from,
- int to);
-
- /**
- * This method analyzes one or more responses to identify variations in a
- * number of attributes and returns an IResponseVariations
- * object that can be queried to obtain details of the variations.
- *
- * @param responses The responses to analyze.
- * @return An IResponseVariations
object representing the
- * variations in the responses.
- */
- IResponseVariations analyzeResponseVariations(byte[]... responses);
-
- /**
- * This method analyzes one or more responses to identify the number of
- * occurrences of the specified keywords and returns an
- * IResponseKeywords
object that can be queried to obtain
- * details of the number of occurrences of each keyword.
- *
- * @param keywords The keywords to look for.
- * @param responses The responses to analyze.
- * @return An IResponseKeywords
object representing the counts
- * of the keywords appearing in the responses.
- */
- IResponseKeywords analyzeResponseKeywords(List keywords, byte[]... responses);
-}
diff --git a/src/main/java/burp/IExtensionStateListener.java b/src/main/java/burp/IExtensionStateListener.java
deleted file mode 100644
index 9b385f7..0000000
--- a/src/main/java/burp/IExtensionStateListener.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package burp;
-
-/*
- * @(#)IExtensionStateListener.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerExtensionStateListener()
to
- * register an extension state listener. The listener will be notified of
- * changes to the extension's state. Note: Any extensions that start
- * background threads or open system resources (such as files or database
- * connections) should register a listener and terminate threads / close
- * resources when the extension is unloaded.
- */
-public interface IExtensionStateListener
-{
- /**
- * This method is called when the extension is unloaded.
- */
- void extensionUnloaded();
-}
diff --git a/src/main/java/burp/IHttpListener.java b/src/main/java/burp/IHttpListener.java
deleted file mode 100644
index e1a5631..0000000
--- a/src/main/java/burp/IHttpListener.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package burp;
-
-/*
- * @(#)IHttpListener.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerHttpListener()
to register an
- * HTTP listener. The listener will be notified of requests and responses made
- * by any Burp tool. Extensions can perform custom analysis or modification of
- * these messages by registering an HTTP listener.
- */
-public interface IHttpListener
-{
- /**
- * This method is invoked when an HTTP request is about to be issued, and
- * when an HTTP response has been received.
- *
- * @param toolFlag A flag indicating the Burp tool that issued the request.
- * Burp tool flags are defined in the
- * IBurpExtenderCallbacks
interface.
- * @param messageIsRequest Flags whether the method is being invoked for a
- * request or response.
- * @param messageInfo Details of the request / response to be processed.
- * Extensions can call the setter methods on this object to update the
- * current message and so modify Burp's behavior.
- */
- void processHttpMessage(int toolFlag,
- boolean messageIsRequest,
- IHttpRequestResponse messageInfo) throws Exception;
-}
diff --git a/src/main/java/burp/IHttpRequestResponse.java b/src/main/java/burp/IHttpRequestResponse.java
deleted file mode 100644
index 1a074b8..0000000
--- a/src/main/java/burp/IHttpRequestResponse.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package burp;
-
-/*
- * @(#)IHttpRequestResponse.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to retrieve and update details about HTTP messages.
- *
- * Note: The setter methods generally can only be used before the message
- * has been processed, and not in read-only contexts. The getter methods
- * relating to response details can only be used after the request has been
- * issued.
- */
-public interface IHttpRequestResponse
-{
- /**
- * This method is used to retrieve the request message.
- *
- * @return The request message.
- */
- byte[] getRequest();
-
- /**
- * This method is used to update the request message.
- *
- * @param message The new request message.
- */
- void setRequest(byte[] message);
-
- /**
- * This method is used to retrieve the response message.
- *
- * @return The response message.
- */
- byte[] getResponse();
-
- /**
- * This method is used to update the response message.
- *
- * @param message The new response message.
- */
- void setResponse(byte[] message);
-
- /**
- * This method is used to retrieve the user-annotated comment for this item,
- * if applicable.
- *
- * @return The user-annotated comment for this item, or null if none is set.
- */
- String getComment();
-
- /**
- * This method is used to update the user-annotated comment for this item.
- *
- * @param comment The comment to be assigned to this item.
- */
- void setComment(String comment);
-
- /**
- * This method is used to retrieve the user-annotated highlight for this
- * item, if applicable.
- *
- * @return The user-annotated highlight for this item, or null if none is
- * set.
- */
- String getHighlight();
-
- /**
- * This method is used to update the user-annotated highlight for this item.
- *
- * @param color The highlight color to be assigned to this item. Accepted
- * values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray,
- * or a null String to clear any existing highlight.
- */
- void setHighlight(String color);
-
- /**
- * This method is used to retrieve the HTTP service for this request /
- * response.
- *
- * @return An
- * IHttpService
object containing details of the HTTP service.
- */
- IHttpService getHttpService();
-
- /**
- * This method is used to update the HTTP service for this request /
- * response.
- *
- * @param httpService An
- * IHttpService
object containing details of the new HTTP
- * service.
- */
- void setHttpService(IHttpService httpService);
-
-}
diff --git a/src/main/java/burp/IHttpRequestResponsePersisted.java b/src/main/java/burp/IHttpRequestResponsePersisted.java
deleted file mode 100644
index bbdb3d3..0000000
--- a/src/main/java/burp/IHttpRequestResponsePersisted.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package burp;
-
-/*
- * @(#)IHttpRequestResponsePersisted.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used for an
- * IHttpRequestResponse
object whose request and response messages
- * have been saved to temporary files using
- * IBurpExtenderCallbacks.saveBuffersToTempFiles()
.
- */
-public interface IHttpRequestResponsePersisted extends IHttpRequestResponse
-{
- /**
- * This method is deprecated and no longer performs any action.
- */
- @Deprecated
- void deleteTempFiles();
-}
diff --git a/src/main/java/burp/IHttpRequestResponseWithMarkers.java b/src/main/java/burp/IHttpRequestResponseWithMarkers.java
deleted file mode 100644
index 5ddc9ae..0000000
--- a/src/main/java/burp/IHttpRequestResponseWithMarkers.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package burp;
-
-/*
- * @(#)IHttpRequestResponseWithMarkers.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * This interface is used for an
- * IHttpRequestResponse
object that has had markers applied.
- * Extensions can create instances of this interface using
- * IBurpExtenderCallbacks.applyMarkers()
, or provide their own
- * implementation. Markers are used in various situations, such as specifying
- * Intruder payload positions, Scanner insertion points, and highlights in
- * Scanner issues.
- */
-public interface IHttpRequestResponseWithMarkers extends IHttpRequestResponse
-{
- /**
- * This method returns the details of the request markers.
- *
- * @return A list of index pairs representing the offsets of markers for the
- * request message. Each item in the list is an int[2] array containing the
- * start and end offsets for the marker. The method may return
- * null
if no request markers are defined.
- */
- List getRequestMarkers();
-
- /**
- * This method returns the details of the response markers.
- *
- * @return A list of index pairs representing the offsets of markers for the
- * response message. Each item in the list is an int[2] array containing the
- * start and end offsets for the marker. The method may return
- * null
if no response markers are defined.
- */
- List getResponseMarkers();
-}
diff --git a/src/main/java/burp/IHttpService.java b/src/main/java/burp/IHttpService.java
deleted file mode 100644
index 9810d80..0000000
--- a/src/main/java/burp/IHttpService.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package burp;
-
-/*
- * @(#)IHttpService.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to provide details about an HTTP service, to which
- * HTTP requests can be sent.
- */
-public interface IHttpService
-{
- /**
- * This method returns the hostname or IP address for the service.
- *
- * @return The hostname or IP address for the service.
- */
- String getHost();
-
- /**
- * This method returns the port number for the service.
- *
- * @return The port number for the service.
- */
- int getPort();
-
- /**
- * This method returns the protocol for the service.
- *
- * @return The protocol for the service. Expected values are "http" or
- * "https".
- */
- String getProtocol();
-}
diff --git a/src/main/java/burp/IInterceptedProxyMessage.java b/src/main/java/burp/IInterceptedProxyMessage.java
deleted file mode 100644
index bf6f47f..0000000
--- a/src/main/java/burp/IInterceptedProxyMessage.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package burp;
-
-/*
- * @(#)IInterceptedProxyMessage.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.net.InetAddress;
-
-/**
- * This interface is used to represent an HTTP message that has been intercepted
- * by Burp Proxy. Extensions can register an
- * IProxyListener
to receive details of proxy messages using this
- * interface. *
- */
-public interface IInterceptedProxyMessage
-{
- /**
- * This action causes Burp Proxy to follow the current interception rules to
- * determine the appropriate action to take for the message.
- */
- static final int ACTION_FOLLOW_RULES = 0;
- /**
- * This action causes Burp Proxy to present the message to the user for
- * manual review or modification.
- */
- static final int ACTION_DO_INTERCEPT = 1;
- /**
- * This action causes Burp Proxy to forward the message to the remote server
- * or client, without presenting it to the user.
- */
- static final int ACTION_DONT_INTERCEPT = 2;
- /**
- * This action causes Burp Proxy to drop the message.
- */
- static final int ACTION_DROP = 3;
- /**
- * This action causes Burp Proxy to follow the current interception rules to
- * determine the appropriate action to take for the message, and then make a
- * second call to processProxyMessage.
- */
- static final int ACTION_FOLLOW_RULES_AND_REHOOK = 0x10;
- /**
- * This action causes Burp Proxy to present the message to the user for
- * manual review or modification, and then make a second call to
- * processProxyMessage.
- */
- static final int ACTION_DO_INTERCEPT_AND_REHOOK = 0x11;
- /**
- * This action causes Burp Proxy to skip user interception, and then make a
- * second call to processProxyMessage.
- */
- static final int ACTION_DONT_INTERCEPT_AND_REHOOK = 0x12;
-
- /**
- * This method retrieves a unique reference number for this
- * request/response.
- *
- * @return An identifier that is unique to a single request/response pair.
- * Extensions can use this to correlate details of requests and responses
- * and perform processing on the response message accordingly.
- */
- int getMessageReference();
-
- /**
- * This method retrieves details of the intercepted message.
- *
- * @return An IHttpRequestResponse
object containing details of
- * the intercepted message.
- */
- IHttpRequestResponse getMessageInfo();
-
- /**
- * This method retrieves the currently defined interception action. The
- * default action is
- * ACTION_FOLLOW_RULES
. If multiple proxy listeners are
- * registered, then other listeners may already have modified the
- * interception action before it reaches the current listener. This method
- * can be used to determine whether this has occurred.
- *
- * @return The currently defined interception action. Possible values are
- * defined within this interface.
- */
- int getInterceptAction();
-
- /**
- * This method is used to update the interception action.
- *
- * @param interceptAction The new interception action. Possible values are
- * defined within this interface.
- */
- void setInterceptAction(int interceptAction);
-
- /**
- * This method retrieves the name of the Burp Proxy listener that is
- * processing the intercepted message.
- *
- * @return The name of the Burp Proxy listener that is processing the
- * intercepted message. The format is the same as that shown in the Proxy
- * Listeners UI - for example, "127.0.0.1:8080".
- */
- String getListenerInterface();
-
- /**
- * This method retrieves the client IP address from which the request for
- * the intercepted message was received.
- *
- * @return The client IP address from which the request for the intercepted
- * message was received.
- */
- InetAddress getClientIpAddress();
-}
diff --git a/src/main/java/burp/IIntruderAttack.java b/src/main/java/burp/IIntruderAttack.java
deleted file mode 100644
index 8305fbb..0000000
--- a/src/main/java/burp/IIntruderAttack.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package burp;
-
-/*
- * @(#)IIntruderAttack.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to hold details about an Intruder attack.
- */
-public interface IIntruderAttack
-{
- /**
- * This method is used to retrieve the HTTP service for the attack.
- *
- * @return The HTTP service for the attack.
- */
- IHttpService getHttpService();
-
- /**
- * This method is used to retrieve the request template for the attack.
- *
- * @return The request template for the attack.
- */
- byte[] getRequestTemplate();
-
-}
diff --git a/src/main/java/burp/IIntruderPayloadGenerator.java b/src/main/java/burp/IIntruderPayloadGenerator.java
deleted file mode 100644
index ba28643..0000000
--- a/src/main/java/burp/IIntruderPayloadGenerator.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package burp;
-
-/*
- * @(#)IIntruderPayloadGenerator.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used for custom Intruder payload generators. Extensions
- * that have registered an
- * IIntruderPayloadGeneratorFactory
must return a new instance of
- * this interface when required as part of a new Intruder attack.
- */
-public interface IIntruderPayloadGenerator
-{
- /**
- * This method is used by Burp to determine whether the payload generator is
- * able to provide any further payloads.
- *
- * @return Extensions should return
- * false
when all the available payloads have been used up,
- * otherwise
- * true
.
- */
- boolean hasMorePayloads();
-
- /**
- * This method is used by Burp to obtain the value of the next payload.
- *
- * @param baseValue The base value of the current payload position. This
- * value may be
- * null
if the concept of a base value is not applicable (e.g.
- * in a battering ram attack).
- * @return The next payload to use in the attack.
- */
- byte[] getNextPayload(byte[] baseValue);
-
- /**
- * This method is used by Burp to reset the state of the payload generator
- * so that the next call to
- * getNextPayload()
returns the first payload again. This
- * method will be invoked when an attack uses the same payload generator for
- * more than one payload position, for example in a sniper attack.
- */
- void reset();
-}
diff --git a/src/main/java/burp/IIntruderPayloadGeneratorFactory.java b/src/main/java/burp/IIntruderPayloadGeneratorFactory.java
deleted file mode 100644
index 2386306..0000000
--- a/src/main/java/burp/IIntruderPayloadGeneratorFactory.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package burp;
-
-/*
- * @(#)IIntruderPayloadGeneratorFactory.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerIntruderPayloadGeneratorFactory()
- * to register a factory for custom Intruder payloads.
- */
-public interface IIntruderPayloadGeneratorFactory
-{
- /**
- * This method is used by Burp to obtain the name of the payload generator.
- * This will be displayed as an option within the Intruder UI when the user
- * selects to use extension-generated payloads.
- *
- * @return The name of the payload generator.
- */
- String getGeneratorName();
-
- /**
- * This method is used by Burp when the user starts an Intruder attack that
- * uses this payload generator.
- *
- * @param attack An
- * IIntruderAttack
object that can be queried to obtain details
- * about the attack in which the payload generator will be used.
- * @return A new instance of
- * IIntruderPayloadGenerator
that will be used to generate
- * payloads for the attack.
- */
- IIntruderPayloadGenerator createNewInstance(IIntruderAttack attack);
-}
diff --git a/src/main/java/burp/IIntruderPayloadProcessor.java b/src/main/java/burp/IIntruderPayloadProcessor.java
deleted file mode 100644
index 56d7fea..0000000
--- a/src/main/java/burp/IIntruderPayloadProcessor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package burp;
-
-/*
- * @(#)IIntruderPayloadProcessor.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerIntruderPayloadProcessor()
to
- * register a custom Intruder payload processor.
- */
-public interface IIntruderPayloadProcessor
-{
- /**
- * This method is used by Burp to obtain the name of the payload processor.
- * This will be displayed as an option within the Intruder UI when the user
- * selects to use an extension-provided payload processor.
- *
- * @return The name of the payload processor.
- */
- String getProcessorName();
-
- /**
- * This method is invoked by Burp each time the processor should be applied
- * to an Intruder payload.
- *
- * @param currentPayload The value of the payload to be processed.
- * @param originalPayload The value of the original payload prior to
- * processing by any already-applied processing rules.
- * @param baseValue The base value of the payload position, which will be
- * replaced with the current payload.
- * @return The value of the processed payload. This may be
- * null
to indicate that the current payload should be skipped,
- * and the attack will move directly to the next payload.
- */
- byte[] processPayload(
- byte[] currentPayload,
- byte[] originalPayload,
- byte[] baseValue);
-}
diff --git a/src/main/java/burp/IMenuItemHandler.java b/src/main/java/burp/IMenuItemHandler.java
deleted file mode 100644
index d769b8c..0000000
--- a/src/main/java/burp/IMenuItemHandler.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package burp;
-
-/*
- * @(#)IMenuItemHandler.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerMenuItem()
to register a custom
- * context menu item.
- *
- * @deprecated Use
- * IContextMenuFactory
instead.
- */
-@Deprecated
-public interface IMenuItemHandler
-{
- /**
- * This method is invoked by Burp Suite when the user clicks on a custom
- * menu item which the extension has registered with Burp.
- *
- * @param menuItemCaption The caption of the menu item which was clicked.
- * This parameter enables extensions to provide a single implementation
- * which handles multiple different menu items.
- * @param messageInfo Details of the HTTP message(s) for which the context
- * menu was displayed.
- */
- void menuItemClicked(
- String menuItemCaption,
- IHttpRequestResponse[] messageInfo);
-}
diff --git a/src/main/java/burp/IMessageEditor.java b/src/main/java/burp/IMessageEditor.java
deleted file mode 100644
index 68fbafb..0000000
--- a/src/main/java/burp/IMessageEditor.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package burp;
-
-/*
- * @(#)IMessageEditor.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.Component;
-
-/**
- * This interface is used to provide extensions with an instance of Burp's HTTP
- * message editor, for the extension to use in its own UI. Extensions should
- * call IBurpExtenderCallbacks.createMessageEditor()
to obtain an
- * instance of this interface.
- */
-public interface IMessageEditor
-{
-
- /**
- * This method returns the UI component of the editor, for extensions to add
- * to their own UI.
- *
- * @return The UI component of the editor.
- */
- Component getComponent();
-
- /**
- * This method is used to display an HTTP message in the editor.
- *
- * @param message The HTTP message to be displayed.
- * @param isRequest Flags whether the message is an HTTP request or
- * response.
- */
- void setMessage(byte[] message, boolean isRequest);
-
- /**
- * This method is used to retrieve the currently displayed message, which
- * may have been modified by the user.
- *
- * @return The currently displayed HTTP message.
- */
- byte[] getMessage();
-
- /**
- * This method is used to determine whether the current message has been
- * modified by the user.
- *
- * @return An indication of whether the current message has been modified by
- * the user since it was first displayed.
- */
- boolean isMessageModified();
-
- /**
- * This method returns the data that is currently selected by the user.
- *
- * @return The data that is currently selected by the user, or
- * null
if no selection is made.
- */
- byte[] getSelectedData();
-
- /**
- * This method can be used to retrieve the bounds of the user's selection
- * into the displayed message, if applicable.
- *
- * @return An int[2] array containing the start and end offsets of the
- * user's selection within the displayed message. If the user has not made
- * any selection in the current message, both offsets indicate the position
- * of the caret within the editor. For some editor views, the concept of
- * selection within the message does not apply, in which case this method
- * returns null.
- */
- int[] getSelectionBounds();
-}
diff --git a/src/main/java/burp/IMessageEditorController.java b/src/main/java/burp/IMessageEditorController.java
deleted file mode 100644
index 99f5851..0000000
--- a/src/main/java/burp/IMessageEditorController.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package burp;
-
-/*
- * @(#)IMessageEditorController.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used by an
- * IMessageEditor
to obtain details about the currently displayed
- * message. Extensions that create instances of Burp's HTTP message editor can
- * optionally provide an implementation of
- * IMessageEditorController
, which the editor will invoke when it
- * requires further information about the current message (for example, to send
- * it to another Burp tool). Extensions that provide custom editor tabs via an
- * IMessageEditorTabFactory
will receive a reference to an
- * IMessageEditorController
object for each tab instance they
- * generate, which the tab can invoke if it requires further information about
- * the current message.
- */
-public interface IMessageEditorController
-{
- /**
- * This method is used to retrieve the HTTP service for the current message.
- *
- * @return The HTTP service for the current message.
- */
- IHttpService getHttpService();
-
- /**
- * This method is used to retrieve the HTTP request associated with the
- * current message (which may itself be a response).
- *
- * @return The HTTP request associated with the current message.
- */
- byte[] getRequest();
-
- /**
- * This method is used to retrieve the HTTP response associated with the
- * current message (which may itself be a request).
- *
- * @return The HTTP response associated with the current message.
- */
- byte[] getResponse();
-}
diff --git a/src/main/java/burp/IMessageEditorTab.java b/src/main/java/burp/IMessageEditorTab.java
deleted file mode 100644
index 39cd0f3..0000000
--- a/src/main/java/burp/IMessageEditorTab.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package burp;
-
-/*
- * @(#)IMessageEditorTab.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.Component;
-
-/**
- * Extensions that register an
- * IMessageEditorTabFactory
must return instances of this
- * interface, which Burp will use to create custom tabs within its HTTP message
- * editors.
- */
-public interface IMessageEditorTab
-{
- /**
- * This method returns the caption that should appear on the custom tab when
- * it is displayed. Note: Burp invokes this method once when the tab
- * is first generated, and the same caption will be used every time the tab
- * is displayed.
- *
- * @return The caption that should appear on the custom tab when it is
- * displayed.
- */
- String getTabCaption();
-
- /**
- * This method returns the component that should be used as the contents of
- * the custom tab when it is displayed. Note: Burp invokes this
- * method once when the tab is first generated, and the same component will
- * be used every time the tab is displayed.
- *
- * @return The component that should be used as the contents of the custom
- * tab when it is displayed.
- */
- Component getUiComponent();
-
- /**
- * The hosting editor will invoke this method before it displays a new HTTP
- * message, so that the custom tab can indicate whether it should be enabled
- * for that message.
- *
- * @param content The message that is about to be displayed, or a zero-length
- * array if the existing message is to be cleared.
- * @param isRequest Indicates whether the message is a request or a
- * response.
- * @return The method should return
- * true
if the custom tab is able to handle the specified
- * message, and so will be displayed within the editor. Otherwise, the tab
- * will be hidden while this message is displayed.
- */
- boolean isEnabled(byte[] content, boolean isRequest);
-
- /**
- * The hosting editor will invoke this method to display a new message or to
- * clear the existing message. This method will only be called with a new
- * message if the tab has already returned
- * true
to a call to
- * isEnabled()
with the same message details.
- *
- * @param content The message that is to be displayed, or
- * null
if the tab should clear its contents and disable any
- * editable controls.
- * @param isRequest Indicates whether the message is a request or a
- * response.
- */
- void setMessage(byte[] content, boolean isRequest);
-
- /**
- * This method returns the currently displayed message.
- *
- * @return The currently displayed message.
- */
- byte[] getMessage();
-
- /**
- * This method is used to determine whether the currently displayed message
- * has been modified by the user. The hosting editor will always call
- * getMessage()
before calling this method, so any pending
- * edits should be completed within
- * getMessage()
.
- *
- * @return The method should return
- * true
if the user has modified the current message since it
- * was first displayed.
- */
- boolean isModified();
-
- /**
- * This method is used to retrieve the data that is currently selected by
- * the user.
- *
- * @return The data that is currently selected by the user. This may be
- * null
if no selection is currently made.
- */
- byte[] getSelectedData();
-}
diff --git a/src/main/java/burp/IMessageEditorTabFactory.java b/src/main/java/burp/IMessageEditorTabFactory.java
deleted file mode 100644
index 821cff0..0000000
--- a/src/main/java/burp/IMessageEditorTabFactory.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package burp;
-
-/*
- * @(#)IMessageEditorTabFactory.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerMessageEditorTabFactory()
to
- * register a factory for custom message editor tabs. This allows extensions to
- * provide custom rendering or editing of HTTP messages, within Burp's own HTTP
- * editor.
- */
-public interface IMessageEditorTabFactory
-{
- /**
- * Burp will call this method once for each HTTP message editor, and the
- * factory should provide a new instance of an
- * IMessageEditorTab
object.
- *
- * @param controller An
- * IMessageEditorController
object, which the new tab can query
- * to retrieve details about the currently displayed message. This may be
- * null
for extension-invoked message editors where the
- * extension has not provided an editor controller.
- * @param editable Indicates whether the hosting editor is editable or
- * read-only.
- * @return A new
- * IMessageEditorTab
object for use within the message editor.
- */
- IMessageEditorTab createNewInstance(IMessageEditorController controller,
- boolean editable);
-}
diff --git a/src/main/java/burp/IParameter.java b/src/main/java/burp/IParameter.java
deleted file mode 100644
index f62d609..0000000
--- a/src/main/java/burp/IParameter.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package burp;
-
-/*
- * @(#)IParameter.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to hold details about an HTTP request parameter.
- */
-public interface IParameter
-{
- /**
- * Used to indicate a parameter within the URL query string.
- */
- static final byte PARAM_URL = 0;
- /**
- * Used to indicate a parameter within the message body.
- */
- static final byte PARAM_BODY = 1;
- /**
- * Used to indicate an HTTP cookie.
- */
- static final byte PARAM_COOKIE = 2;
- /**
- * Used to indicate an item of data within an XML structure.
- */
- static final byte PARAM_XML = 3;
- /**
- * Used to indicate the value of a tag attribute within an XML structure.
- */
- static final byte PARAM_XML_ATTR = 4;
- /**
- * Used to indicate the value of a parameter attribute within a multi-part
- * message body (such as the name of an uploaded file).
- */
- static final byte PARAM_MULTIPART_ATTR = 5;
- /**
- * Used to indicate an item of data within a JSON structure.
- */
- static final byte PARAM_JSON = 6;
-
- /**
- * This method is used to retrieve the parameter type.
- *
- * @return The parameter type. The available types are defined within this
- * interface.
- */
- byte getType();
-
- /**
- * This method is used to retrieve the parameter name.
- *
- * @return The parameter name.
- */
- String getName();
-
- /**
- * This method is used to retrieve the parameter value.
- *
- * @return The parameter value.
- */
- String getValue();
-
- /**
- * This method is used to retrieve the start offset of the parameter name
- * within the HTTP request.
- *
- * @return The start offset of the parameter name within the HTTP request,
- * or -1 if the parameter is not associated with a specific request.
- */
- int getNameStart();
-
- /**
- * This method is used to retrieve the end offset of the parameter name
- * within the HTTP request.
- *
- * @return The end offset of the parameter name within the HTTP request, or
- * -1 if the parameter is not associated with a specific request.
- */
- int getNameEnd();
-
- /**
- * This method is used to retrieve the start offset of the parameter value
- * within the HTTP request.
- *
- * @return The start offset of the parameter value within the HTTP request,
- * or -1 if the parameter is not associated with a specific request.
- */
- int getValueStart();
-
- /**
- * This method is used to retrieve the end offset of the parameter value
- * within the HTTP request.
- *
- * @return The end offset of the parameter value within the HTTP request, or
- * -1 if the parameter is not associated with a specific request.
- */
- int getValueEnd();
-}
diff --git a/src/main/java/burp/IProxyListener.java b/src/main/java/burp/IProxyListener.java
deleted file mode 100644
index e032a9d..0000000
--- a/src/main/java/burp/IProxyListener.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package burp;
-
-/*
- * @(#)IProxyListener.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerProxyListener()
to register a
- * Proxy listener. The listener will be notified of requests and responses being
- * processed by the Proxy tool. Extensions can perform custom analysis or
- * modification of these messages, and control in-UI message interception, by
- * registering a proxy listener.
- */
-public interface IProxyListener
-{
- /**
- * This method is invoked when an HTTP message is being processed by the
- * Proxy.
- *
- * @param messageIsRequest Indicates whether the HTTP message is a request
- * or a response.
- * @param message An
- * IInterceptedProxyMessage
object that extensions can use to
- * query and update details of the message, and control whether the message
- * should be intercepted and displayed to the user for manual review or
- * modification.
- */
- void processProxyMessage(
- boolean messageIsRequest,
- IInterceptedProxyMessage message);
-}
diff --git a/src/main/java/burp/IRequestInfo.java b/src/main/java/burp/IRequestInfo.java
deleted file mode 100644
index 1ae8f9c..0000000
--- a/src/main/java/burp/IRequestInfo.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package burp;
-
-/*
- * @(#)IRequestInfo.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.net.URL;
-import java.util.List;
-
-/**
- * This interface is used to retrieve key details about an HTTP request.
- * Extensions can obtain an
- * IRequestInfo
object for a given request by calling
- * IExtensionHelpers.analyzeRequest()
.
- */
-public interface IRequestInfo
-{
- /**
- * Used to indicate that there is no content.
- */
- static final byte CONTENT_TYPE_NONE = 0;
- /**
- * Used to indicate URL-encoded content.
- */
- static final byte CONTENT_TYPE_URL_ENCODED = 1;
- /**
- * Used to indicate multi-part content.
- */
- static final byte CONTENT_TYPE_MULTIPART = 2;
- /**
- * Used to indicate XML content.
- */
- static final byte CONTENT_TYPE_XML = 3;
- /**
- * Used to indicate JSON content.
- */
- static final byte CONTENT_TYPE_JSON = 4;
- /**
- * Used to indicate AMF content.
- */
- static final byte CONTENT_TYPE_AMF = 5;
- /**
- * Used to indicate unknown content.
- */
- static final byte CONTENT_TYPE_UNKNOWN = -1;
-
- /**
- * This method is used to obtain the HTTP method used in the request.
- *
- * @return The HTTP method used in the request.
- */
- String getMethod();
-
- /**
- * This method is used to obtain the URL in the request.
- *
- * @return The URL in the request.
- */
- URL getUrl();
-
- /**
- * This method is used to obtain the HTTP headers contained in the request.
- *
- * @return The HTTP headers contained in the request.
- */
- List getHeaders();
-
- /**
- * This method is used to obtain the parameters contained in the request.
- *
- * @return The parameters contained in the request.
- */
- List getParameters();
-
- /**
- * This method is used to obtain the offset within the request where the
- * message body begins.
- *
- * @return The offset within the request where the message body begins.
- */
- int getBodyOffset();
-
- /**
- * This method is used to obtain the content type of the message body.
- *
- * @return An indication of the content type of the message body. Available
- * types are defined within this interface.
- */
- byte getContentType();
-}
diff --git a/src/main/java/burp/IResponseInfo.java b/src/main/java/burp/IResponseInfo.java
deleted file mode 100644
index 8435f0a..0000000
--- a/src/main/java/burp/IResponseInfo.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package burp;
-
-/*
- * @(#)IResponseInfo.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * This interface is used to retrieve key details about an HTTP response.
- * Extensions can obtain an
- * IResponseInfo
object for a given response by calling
- * IExtensionHelpers.analyzeResponse()
.
- */
-public interface IResponseInfo
-{
- /**
- * This method is used to obtain the HTTP headers contained in the response.
- *
- * @return The HTTP headers contained in the response.
- */
- List getHeaders();
-
- /**
- * This method is used to obtain the offset within the response where the
- * message body begins.
- *
- * @return The offset within the response where the message body begins.
- */
- int getBodyOffset();
-
- /**
- * This method is used to obtain the HTTP status code contained in the
- * response.
- *
- * @return The HTTP status code contained in the response.
- */
- short getStatusCode();
-
- /**
- * This method is used to obtain details of the HTTP cookies set in the
- * response.
- *
- * @return A list of ICookie
objects representing the cookies
- * set in the response, if any.
- */
- List getCookies();
-
- /**
- * This method is used to obtain the MIME type of the response, as stated in
- * the HTTP headers.
- *
- * @return A textual label for the stated MIME type, or an empty String if
- * this is not known or recognized. The possible labels are the same as
- * those used in the main Burp UI.
- */
- String getStatedMimeType();
-
- /**
- * This method is used to obtain the MIME type of the response, as inferred
- * from the contents of the HTTP message body.
- *
- * @return A textual label for the inferred MIME type, or an empty String if
- * this is not known or recognized. The possible labels are the same as
- * those used in the main Burp UI.
- */
- String getInferredMimeType();
-}
diff --git a/src/main/java/burp/IResponseKeywords.java b/src/main/java/burp/IResponseKeywords.java
deleted file mode 100644
index aecaefa..0000000
--- a/src/main/java/burp/IResponseKeywords.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package burp;
-
-/*
- * @(#)IResponseKeywords.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * This interface is used to represent the counts of keywords appearing in a
- * number of HTTP responses.
- */
-public interface IResponseKeywords
-{
-
- /**
- * This method is used to obtain the list of keywords whose counts vary
- * between the analyzed responses.
- *
- * @return The keywords whose counts vary between the analyzed responses.
- */
- List getVariantKeywords();
-
- /**
- * This method is used to obtain the list of keywords whose counts do not
- * vary between the analyzed responses.
- *
- * @return The keywords whose counts do not vary between the analyzed
- * responses.
- */
- List getInvariantKeywords();
-
- /**
- * This method is used to obtain the number of occurrences of an individual
- * keyword in a response.
- *
- * @param keyword The keyword whose count will be retrieved.
- * @param responseIndex The index of the response. Note responses are
- * indexed from zero in the order they were originally supplied to the
- * IExtensionHelpers.analyzeResponseKeywords()
and
- * IResponseKeywords.updateWith()
methods.
- * @return The number of occurrences of the specified keyword for the
- * specified response.
- */
- int getKeywordCount(String keyword, int responseIndex);
-
- /**
- * This method is used to update the analysis based on additional responses.
- *
- * @param responses The new responses to include in the analysis.
- */
- void updateWith(byte[]... responses);
-}
diff --git a/src/main/java/burp/IResponseVariations.java b/src/main/java/burp/IResponseVariations.java
deleted file mode 100644
index d13f546..0000000
--- a/src/main/java/burp/IResponseVariations.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package burp;
-
-/*
- * @(#)IResponseVariations.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * This interface is used to represent variations between a number HTTP
- * responses, according to various attributes.
- */
-public interface IResponseVariations
-{
-
- /**
- * This method is used to obtain the list of attributes that vary between
- * the analyzed responses.
- *
- * @return The attributes that vary between the analyzed responses.
- */
- List getVariantAttributes();
-
- /**
- * This method is used to obtain the list of attributes that do not vary
- * between the analyzed responses.
- *
- * @return The attributes that do not vary between the analyzed responses.
- */
- List getInvariantAttributes();
-
- /**
- * This method is used to obtain the value of an individual attribute in a
- * response. Note that the values of some attributes are intrinsically
- * meaningful (e.g. a word count) while the values of others are less so
- * (e.g. a checksum of the HTML tag names).
- *
- * @param attributeName The name of the attribute whose value will be
- * retrieved. Extension authors can obtain the list of supported attributes
- * by generating an IResponseVariations
object for a single
- * response and calling
- * IResponseVariations.getInvariantAttributes()
.
- * @param responseIndex The index of the response. Note that responses are
- * indexed from zero in the order they were originally supplied to the
- * IExtensionHelpers.analyzeResponseVariations()
and
- * IResponseVariations.updateWith()
methods.
- * @return The value of the specified attribute for the specified response.
- */
- int getAttributeValue(String attributeName, int responseIndex);
-
- /**
- * This method is used to update the analysis based on additional responses.
- *
- * @param responses The new responses to include in the analysis.
- */
- void updateWith(byte[]... responses);
-}
diff --git a/src/main/java/burp/IScanIssue.java b/src/main/java/burp/IScanIssue.java
deleted file mode 100644
index fe2fdff..0000000
--- a/src/main/java/burp/IScanIssue.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package burp;
-
-/*
- * @(#)IScanIssue.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to retrieve details of Scanner issues. Extensions can
- * obtain details of issues by registering an IScannerListener
or
- * by calling IBurpExtenderCallbacks.getScanIssues()
. Extensions
- * can also add custom Scanner issues by registering an
- * IScannerCheck
or calling
- * IBurpExtenderCallbacks.addScanIssue()
, and providing their own
- * implementations of this interface. Note that issue descriptions and other
- * text generated by extensions are subject to an HTML whitelist that allows
- * only formatting tags and simple hyperlinks.
- */
-public interface IScanIssue
-{
-
- /**
- * This method returns the URL for which the issue was generated.
- *
- * @return The URL for which the issue was generated.
- */
- java.net.URL getUrl();
-
- /**
- * This method returns the name of the issue type.
- *
- * @return The name of the issue type (e.g. "SQL injection").
- */
- String getIssueName();
-
- /**
- * This method returns a numeric identifier of the issue type. See the Burp
- * Scanner help documentation for a listing of all the issue types.
- *
- * @return A numeric identifier of the issue type.
- */
- int getIssueType();
-
- /**
- * This method returns the issue severity level.
- *
- * @return The issue severity level. Expected values are "High", "Medium",
- * "Low", "Information" or "False positive".
- *
- */
- String getSeverity();
-
- /**
- * This method returns the issue confidence level.
- *
- * @return The issue confidence level. Expected values are "Certain", "Firm"
- * or "Tentative".
- */
- String getConfidence();
-
- /**
- * This method returns a background description for this type of issue.
- *
- * @return A background description for this type of issue, or
- * null
if none applies. A limited set of HTML tags may be
- * used.
- */
- String getIssueBackground();
-
- /**
- * This method returns a background description of the remediation for this
- * type of issue.
- *
- * @return A background description of the remediation for this type of
- * issue, or null
if none applies. A limited set of HTML tags
- * may be used.
- */
- String getRemediationBackground();
-
- /**
- * This method returns detailed information about this specific instance of
- * the issue.
- *
- * @return Detailed information about this specific instance of the issue,
- * or null
if none applies. A limited set of HTML tags may be
- * used.
- */
- String getIssueDetail();
-
- /**
- * This method returns detailed information about the remediation for this
- * specific instance of the issue.
- *
- * @return Detailed information about the remediation for this specific
- * instance of the issue, or null
if none applies. A limited
- * set of HTML tags may be used.
- */
- String getRemediationDetail();
-
- /**
- * This method returns the HTTP messages on the basis of which the issue was
- * generated.
- *
- * @return The HTTP messages on the basis of which the issue was generated.
- * Note: The items in this array should be instances of
- * IHttpRequestResponseWithMarkers
if applicable, so that
- * details of the relevant portions of the request and response messages are
- * available.
- */
- IHttpRequestResponse[] getHttpMessages();
-
- /**
- * This method returns the HTTP service for which the issue was generated.
- *
- * @return The HTTP service for which the issue was generated.
- */
- IHttpService getHttpService();
-
-}
diff --git a/src/main/java/burp/IScanQueueItem.java b/src/main/java/burp/IScanQueueItem.java
deleted file mode 100644
index 1716854..0000000
--- a/src/main/java/burp/IScanQueueItem.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package burp;
-
-/*
- * @(#)IScanQueueItem.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to retrieve details of items in the Burp Scanner
- * active scan queue. Extensions can obtain references to scan queue items by
- * calling
- * IBurpExtenderCallbacks.doActiveScan()
.
- */
-public interface IScanQueueItem
-{
- /**
- * This method returns a description of the status of the scan queue item.
- *
- * @return A description of the status of the scan queue item.
- */
- String getStatus();
-
- /**
- * This method returns an indication of the percentage completed for the
- * scan queue item.
- *
- * @return An indication of the percentage completed for the scan queue
- * item.
- */
- byte getPercentageComplete();
-
- /**
- * This method returns the number of requests that have been made for the
- * scan queue item.
- *
- * @return The number of requests that have been made for the scan queue
- * item.
- */
- int getNumRequests();
-
- /**
- * This method returns the number of network errors that have occurred for
- * the scan queue item.
- *
- * @return The number of network errors that have occurred for the scan
- * queue item.
- */
- int getNumErrors();
-
- /**
- * This method returns the number of attack insertion points being used for
- * the scan queue item.
- *
- * @return The number of attack insertion points being used for the scan
- * queue item.
- */
- int getNumInsertionPoints();
-
- /**
- * This method allows the scan queue item to be canceled.
- */
- void cancel();
-
- /**
- * This method returns details of the issues generated for the scan queue
- * item. Note: different items within the scan queue may contain
- * duplicated versions of the same issues - for example, if the same request
- * has been scanned multiple times. Duplicated issues are consolidated in
- * the main view of scan results. Extensions can register an
- * IScannerListener
to get details only of unique, newly
- * discovered Scanner issues post-consolidation.
- *
- * @return Details of the issues generated for the scan queue item.
- */
- IScanIssue[] getIssues();
-}
diff --git a/src/main/java/burp/IScannerCheck.java b/src/main/java/burp/IScannerCheck.java
deleted file mode 100644
index 27ac11c..0000000
--- a/src/main/java/burp/IScannerCheck.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package burp;
-
-/*
- * @(#)IScannerCheck.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerScannerCheck()
to register a
- * custom Scanner check. When performing scanning, Burp will ask the check to
- * perform active or passive scanning on the base request, and report any
- * Scanner issues that are identified.
- */
-public interface IScannerCheck
-{
-
- /**
- * The Scanner invokes this method for each base request / response that is
- * passively scanned. Note: Extensions should only analyze the
- * HTTP messages provided during passive scanning, and should not make any
- * new HTTP requests of their own.
- *
- * @param baseRequestResponse The base HTTP request / response that should
- * be passively scanned.
- * @return A list of IScanIssue
objects, or null
- * if no issues are identified.
- */
- List doPassiveScan(IHttpRequestResponse baseRequestResponse);
-
- /**
- * The Scanner invokes this method for each insertion point that is actively
- * scanned. Extensions may issue HTTP requests as required to carry out
- * active scanning, and should use the
- * IScannerInsertionPoint
object provided to build scan
- * requests for particular payloads.
- * Note:
- * Scan checks should submit raw non-encoded payloads to insertion points,
- * and the insertion point has responsibility for performing any data
- * encoding that is necessary given the nature and location of the insertion
- * point.
- *
- * @param baseRequestResponse The base HTTP request / response that should
- * be actively scanned.
- * @param insertionPoint An IScannerInsertionPoint
object that
- * can be queried to obtain details of the insertion point being tested, and
- * can be used to build scan requests for particular payloads.
- * @return A list of IScanIssue
objects, or null
- * if no issues are identified.
- */
- List doActiveScan(
- IHttpRequestResponse baseRequestResponse,
- IScannerInsertionPoint insertionPoint);
-
- /**
- * The Scanner invokes this method when the custom Scanner check has
- * reported multiple issues for the same URL path. This can arise either
- * because there are multiple distinct vulnerabilities, or because the same
- * (or a similar) request has been scanned more than once. The custom check
- * should determine whether the issues are duplicates. In most cases, where
- * a check uses distinct issue names or descriptions for distinct issues,
- * the consolidation process will simply be a matter of comparing these
- * features for the two issues.
- *
- * @param existingIssue An issue that was previously reported by this
- * Scanner check.
- * @param newIssue An issue at the same URL path that has been newly
- * reported by this Scanner check.
- * @return An indication of which issue(s) should be reported in the main
- * Scanner results. The method should return -1
to report the
- * existing issue only, 0
to report both issues, and
- * 1
to report the new issue only.
- */
- int consolidateDuplicateIssues(
- IScanIssue existingIssue,
- IScanIssue newIssue);
-}
diff --git a/src/main/java/burp/IScannerInsertionPoint.java b/src/main/java/burp/IScannerInsertionPoint.java
deleted file mode 100644
index 404b6d8..0000000
--- a/src/main/java/burp/IScannerInsertionPoint.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package burp;
-
-/*
- * @(#)IScannerInsertionPoint.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to define an insertion point for use by active Scanner
- * checks. Extensions can obtain instances of this interface by registering an
- * IScannerCheck
, or can create instances for use by Burp's own
- * scan checks by registering an
- * IScannerInsertionPointProvider
.
- */
-public interface IScannerInsertionPoint
-{
-
- /**
- * Used to indicate where the payload is inserted into the value of a URL
- * parameter.
- */
- static final byte INS_PARAM_URL = 0x00;
- /**
- * Used to indicate where the payload is inserted into the value of a body
- * parameter.
- */
- static final byte INS_PARAM_BODY = 0x01;
- /**
- * Used to indicate where the payload is inserted into the value of an HTTP
- * cookie.
- */
- static final byte INS_PARAM_COOKIE = 0x02;
- /**
- * Used to indicate where the payload is inserted into the value of an item
- * of data within an XML data structure.
- */
- static final byte INS_PARAM_XML = 0x03;
- /**
- * Used to indicate where the payload is inserted into the value of a tag
- * attribute within an XML structure.
- */
- static final byte INS_PARAM_XML_ATTR = 0x04;
- /**
- * Used to indicate where the payload is inserted into the value of a
- * parameter attribute within a multi-part message body (such as the name of
- * an uploaded file).
- */
- static final byte INS_PARAM_MULTIPART_ATTR = 0x05;
- /**
- * Used to indicate where the payload is inserted into the value of an item
- * of data within a JSON structure.
- */
- static final byte INS_PARAM_JSON = 0x06;
- /**
- * Used to indicate where the payload is inserted into the value of an AMF
- * parameter.
- */
- static final byte INS_PARAM_AMF = 0x07;
- /**
- * Used to indicate where the payload is inserted into the value of an HTTP
- * request header.
- */
- static final byte INS_HEADER = 0x20;
- /**
- * Used to indicate where the payload is inserted into a URL path folder.
- */
- static final byte INS_URL_PATH_FOLDER = 0x21;
- /**
- * Used to indicate where the payload is inserted into a URL path folder.
- * This is now deprecated; use INS_URL_PATH_FOLDER
instead.
- */
- @Deprecated
- static final byte INS_URL_PATH_REST = INS_URL_PATH_FOLDER;
- /**
- * Used to indicate where the payload is inserted into the name of an added
- * URL parameter.
- */
- static final byte INS_PARAM_NAME_URL = 0x22;
- /**
- * Used to indicate where the payload is inserted into the name of an added
- * body parameter.
- */
- static final byte INS_PARAM_NAME_BODY = 0x23;
- /**
- * Used to indicate where the payload is inserted into the body of the HTTP
- * request.
- */
- static final byte INS_ENTIRE_BODY = 0x24;
- /**
- * Used to indicate where the payload is inserted into the URL path
- * filename.
- */
- static final byte INS_URL_PATH_FILENAME = 0x25;
- /**
- * Used to indicate where the payload is inserted at a location manually
- * configured by the user.
- */
- static final byte INS_USER_PROVIDED = 0x40;
- /**
- * Used to indicate where the insertion point is provided by an
- * extension-registered
- * IScannerInsertionPointProvider
.
- */
- static final byte INS_EXTENSION_PROVIDED = 0x41;
- /**
- * Used to indicate where the payload is inserted at an unknown location
- * within the request.
- */
- static final byte INS_UNKNOWN = 0x7f;
-
- /**
- * This method returns the name of the insertion point.
- *
- * @return The name of the insertion point (for example, a description of a
- * particular request parameter).
- */
- String getInsertionPointName();
-
- /**
- * This method returns the base value for this insertion point.
- *
- * @return the base value that appears in this insertion point in the base
- * request being scanned, or null
if there is no value in the
- * base request that corresponds to this insertion point.
- */
- String getBaseValue();
-
- /**
- * This method is used to build a request with the specified payload placed
- * into the insertion point. There is no requirement for extension-provided
- * insertion points to adjust the Content-Length header in requests if the
- * body length has changed, although Burp-provided insertion points will
- * always do this and will return a request with a valid Content-Length
- * header.
- * Note:
- * Scan checks should submit raw non-encoded payloads to insertion points,
- * and the insertion point has responsibility for performing any data
- * encoding that is necessary given the nature and location of the insertion
- * point.
- *
- * @param payload The payload that should be placed into the insertion
- * point.
- * @return The resulting request.
- */
- byte[] buildRequest(byte[] payload);
-
- /**
- * This method is used to determine the offsets of the payload value within
- * the request, when it is placed into the insertion point. Scan checks may
- * invoke this method when reporting issues, so as to highlight the relevant
- * part of the request within the UI.
- *
- * @param payload The payload that should be placed into the insertion
- * point.
- * @return An int[2] array containing the start and end offsets of the
- * payload within the request, or null if this is not applicable (for
- * example, where the insertion point places a payload into a serialized
- * data structure, the raw payload may not literally appear anywhere within
- * the resulting request).
- */
- int[] getPayloadOffsets(byte[] payload);
-
- /**
- * This method returns the type of the insertion point.
- *
- * @return The type of the insertion point. Available types are defined in
- * this interface.
- */
- byte getInsertionPointType();
-}
diff --git a/src/main/java/burp/IScannerInsertionPointProvider.java b/src/main/java/burp/IScannerInsertionPointProvider.java
deleted file mode 100644
index a186530..0000000
--- a/src/main/java/burp/IScannerInsertionPointProvider.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package burp;
-
-/*
- * @(#)IScannerInsertionPointProvider.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.util.List;
-
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerScannerInsertionPointProvider()
- * to register a factory for custom Scanner insertion points.
- */
-public interface IScannerInsertionPointProvider
-{
- /**
- * When a request is actively scanned, the Scanner will invoke this method,
- * and the provider should provide a list of custom insertion points that
- * will be used in the scan. Note: these insertion points are used in
- * addition to those that are derived from Burp Scanner's configuration, and
- * those provided by any other Burp extensions.
- *
- * @param baseRequestResponse The base request that will be actively
- * scanned.
- * @return A list of
- * IScannerInsertionPoint
objects that should be used in the
- * scanning, or
- * null
if no custom insertion points are applicable for this
- * request.
- */
- List getInsertionPoints(
- IHttpRequestResponse baseRequestResponse);
-}
diff --git a/src/main/java/burp/IScannerListener.java b/src/main/java/burp/IScannerListener.java
deleted file mode 100644
index 85e7cbb..0000000
--- a/src/main/java/burp/IScannerListener.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package burp;
-
-/*
- * @(#)IScannerListener.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerScannerListener()
to register a
- * Scanner listener. The listener will be notified of new issues that are
- * reported by the Scanner tool. Extensions can perform custom analysis or
- * logging of Scanner issues by registering a Scanner listener.
- */
-public interface IScannerListener
-{
- /**
- * This method is invoked when a new issue is added to Burp Scanner's
- * results.
- *
- * @param issue An
- * IScanIssue
object that the extension can query to obtain
- * details about the new issue.
- */
- void newScanIssue(IScanIssue issue);
-}
diff --git a/src/main/java/burp/IScopeChangeListener.java b/src/main/java/burp/IScopeChangeListener.java
deleted file mode 100644
index 3ea929a..0000000
--- a/src/main/java/burp/IScopeChangeListener.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package burp;
-
-/*
- * @(#)IScopeChangeListener.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerScopeChangeListener()
to register
- * a scope change listener. The listener will be notified whenever a change
- * occurs to Burp's suite-wide target scope.
- */
-public interface IScopeChangeListener
-{
- /**
- * This method is invoked whenever a change occurs to Burp's suite-wide
- * target scope.
- */
- void scopeChanged();
-}
diff --git a/src/main/java/burp/ISessionHandlingAction.java b/src/main/java/burp/ISessionHandlingAction.java
deleted file mode 100644
index 3915332..0000000
--- a/src/main/java/burp/ISessionHandlingAction.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package burp;
-
-/*
- * @(#)ISessionHandlingAction.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * Extensions can implement this interface and then call
- * IBurpExtenderCallbacks.registerSessionHandlingAction()
to
- * register a custom session handling action. Each registered action will be
- * available within the session handling rule UI for the user to select as a
- * rule action. Users can choose to invoke an action directly in its own right,
- * or following execution of a macro.
- */
-public interface ISessionHandlingAction
-{
- /**
- * This method is used by Burp to obtain the name of the session handling
- * action. This will be displayed as an option within the session handling
- * rule editor when the user selects to execute an extension-provided
- * action.
- *
- * @return The name of the action.
- */
- String getActionName();
-
- /**
- * This method is invoked when the session handling action should be
- * executed. This may happen as an action in its own right, or as a
- * sub-action following execution of a macro.
- *
- * @param currentRequest The base request that is currently being processed.
- * The action can query this object to obtain details about the base
- * request. It can issue additional requests of its own if necessary, and
- * can use the setter methods on this object to update the base request.
- * @param macroItems If the action is invoked following execution of a
- * macro, this parameter contains the result of executing the macro.
- * Otherwise, it is
- * null
. Actions can use the details of the macro items to
- * perform custom analysis of the macro to derive values of non-standard
- * session handling tokens, etc.
- */
- void performAction(
- IHttpRequestResponse currentRequest,
- IHttpRequestResponse[] macroItems);
-}
diff --git a/src/main/java/burp/ITab.java b/src/main/java/burp/ITab.java
deleted file mode 100644
index 5a00017..0000000
--- a/src/main/java/burp/ITab.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package burp;
-
-/*
- * @(#)ITab.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.Component;
-
-/**
- * This interface is used to provide Burp with details of a custom tab that will
- * be added to Burp's UI, using a method such as
- * IBurpExtenderCallbacks.addSuiteTab()
.
- */
-public interface ITab
-{
- /**
- * Burp uses this method to obtain the caption that should appear on the
- * custom tab when it is displayed.
- *
- * @return The caption that should appear on the custom tab when it is
- * displayed.
- */
- String getTabCaption();
-
- /**
- * Burp uses this method to obtain the component that should be used as the
- * contents of the custom tab when it is displayed.
- *
- * @return The component that should be used as the contents of the custom
- * tab when it is displayed.
- */
- Component getUiComponent();
-}
diff --git a/src/main/java/burp/ITempFile.java b/src/main/java/burp/ITempFile.java
deleted file mode 100644
index ea2ee23..0000000
--- a/src/main/java/burp/ITempFile.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package burp;
-
-/*
- * @(#)ITempFile.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-/**
- * This interface is used to hold details of a temporary file that has been
- * created via a call to
- * IBurpExtenderCallbacks.saveToTempFile()
.
- *
- */
-public interface ITempFile
-{
- /**
- * This method is used to retrieve the contents of the buffer that was saved
- * in the temporary file.
- *
- * @return The contents of the buffer that was saved in the temporary file.
- */
- byte[] getBuffer();
-
- /**
- * This method is deprecated and no longer performs any action.
- */
- @Deprecated
- void delete();
-}
diff --git a/src/main/java/burp/ITextEditor.java b/src/main/java/burp/ITextEditor.java
deleted file mode 100644
index 5b23c84..0000000
--- a/src/main/java/burp/ITextEditor.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package burp;
-
-/*
- * @(#)ITextEditor.java
- *
- * Copyright PortSwigger Ltd. All rights reserved.
- *
- * This code may be used to extend the functionality of Burp Suite Free Edition
- * and Burp Suite Professional, provided that this usage does not violate the
- * license terms for those products.
- */
-import java.awt.Component;
-
-/**
- * This interface is used to provide extensions with an instance of Burp's raw
- * text editor, for the extension to use in its own UI. Extensions should call
- * IBurpExtenderCallbacks.createTextEditor()
to obtain an instance
- * of this interface.
- */
-public interface ITextEditor
-{
- /**
- * This method returns the UI component of the editor, for extensions to add
- * to their own UI.
- *
- * @return The UI component of the editor.
- */
- Component getComponent();
-
- /**
- * This method is used to control whether the editor is currently editable.
- * This status can be toggled on and off as required.
- *
- * @param editable Indicates whether the editor should be currently
- * editable.
- */
- void setEditable(boolean editable);
-
- /**
- * This method is used to update the currently displayed text in the editor.
- *
- * @param text The text to be displayed.
- */
- void setText(byte[] text);
-
- /**
- * This method is used to retrieve the currently displayed text.
- *
- * @return The currently displayed text.
- */
- byte[] getText();
-
- /**
- * This method is used to determine whether the user has modified the
- * contents of the editor.
- *
- * @return An indication of whether the user has modified the contents of
- * the editor since the last call to
- * setText()
.
- */
- boolean isTextModified();
-
- /**
- * This method is used to obtain the currently selected text.
- *
- * @return The currently selected text, or
- * null
if the user has not made any selection.
- */
- byte[] getSelectedText();
-
- /**
- * This method can be used to retrieve the bounds of the user's selection
- * into the displayed text, if applicable.
- *
- * @return An int[2] array containing the start and end offsets of the
- * user's selection within the displayed text. If the user has not made any
- * selection in the current message, both offsets indicate the position of
- * the caret within the editor.
- */
- int[] getSelectionBounds();
-
- /**
- * This method is used to update the search expression that is shown in the
- * search bar below the editor. The editor will automatically highlight any
- * regions of the displayed text that match the search expression.
- *
- * @param expression The search expression.
- */
- void setSearchExpression(String expression);
-}
diff --git a/src/main/java/burp/Menu.java b/src/main/java/burp/Menu.java
deleted file mode 100644
index 41aef12..0000000
--- a/src/main/java/burp/Menu.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package burp;
-
-import javax.swing.*;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.util.ArrayList;
-import java.util.List;
-
-public class Menu implements IContextMenuFactory {
- private static JMenu subMenu;
- private static AWSSignerMenuItem enabledMenuItem;
- private static AWSSignerMenuItem[] menuItems = new AWSSignerMenuItem[] {};
-
- @Override
- public List createMenuItems(IContextMenuInvocation invocation) {
- List list;
- list = new ArrayList<>();
-
- // Create menu items
- subMenu = new JMenu("AWSSigner");
-
- // Always create the disable signer item
- JMenuItem disableItem = new JMenuItem("Disable AWSSigner");
- initializeDisableItem(disableItem);
- if (enabledMenuItem == null) {
- disableItem.setEnabled(false);
- } else {
- disableItem.setEnabled(true);
- }
-
- subMenu.add(disableItem);
-
- // Add a menu item for every profile we currently have
- for (AWSSignerMenuItem menuItem : menuItems) {
- initializeMenuItem(menuItem);
- subMenu.add(menuItem);
- }
-
- list.add(subMenu);
- return list;
- }
-
- public static void setMenuItems(AWSSignerMenuItem[] menuItems) {
- Menu.menuItems = menuItems;
- }
-
- private void initializeMenuItem(AWSSignerMenuItem newMenuItem) {
- newMenuItem.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
-
- // Enable the profile, and disable the old profile
- if (enabledMenuItem != null) {
- enabledMenuItem.disableProfile();
- }
- newMenuItem.enableProfile();
- enabledMenuItem = newMenuItem;
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
-
- if (newMenuItem.isProfileEnabled()) {
- if (enabledMenuItem != null) {
- enabledMenuItem.disableProfile();
- }
- newMenuItem.enableProfile();
- enabledMenuItem = newMenuItem;
- }
- }
-
- private static void initializeDisableItem(JMenuItem menuItem) {
- menuItem.addMouseListener(new MouseListener() {
- @Override
- public void mouseClicked(MouseEvent e) {
-
- }
-
- @Override
- public void mousePressed(MouseEvent e) {
-
- }
-
- @Override
- public void mouseReleased(MouseEvent e) {
-
- // To disable the signer, set the enabled item to null
- if (enabledMenuItem != null) {
- enabledMenuItem.disableProfile();
- enabledMenuItem = null;
- }
- }
-
- @Override
- public void mouseEntered(MouseEvent e) {
-
- }
-
- @Override
- public void mouseExited(MouseEvent e) {
-
- }
- });
- }
-
- public static int getEnabledProfile(){
- if (enabledMenuItem == null) {
- return 0;
- }
- return enabledMenuItem.getProfileNumber();
- }
-
- // I expect most of the time, the profile will be enabled through the context menu, but
- // we support enabling profiles through the signer tab too, which is why this needs to be here
- public static void setEnabledProfile(int profile) {
- if (enabledMenuItem != null) {
- enabledMenuItem.disableProfile();
- }
-
- // Also allow the signer tab to disable the signer
- if (profile == 0) {
- enabledMenuItem.disableProfile();
- enabledMenuItem = null;
- } else {
-
- // I don't want to keep a map of all the profiles. Just iterate through them until we find the right one
- for (AWSSignerMenuItem menuItem : menuItems) {
- if (menuItem.getProfileNumber() == profile) {
- menuItem.enableProfile();
- enabledMenuItem = menuItem;
- }
- }
- }
- }
-
-}
diff --git a/src/main/java/burp/TabPanel.form b/src/main/java/burp/TabPanel.form
deleted file mode 100644
index ee734d5..0000000
--- a/src/main/java/burp/TabPanel.form
+++ /dev/null
@@ -1,165 +0,0 @@
-
-
diff --git a/src/main/java/com/netspi/awssigner/controller/AWSSignerController.java b/src/main/java/com/netspi/awssigner/controller/AWSSignerController.java
new file mode 100644
index 0000000..c42015a
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/controller/AWSSignerController.java
@@ -0,0 +1,810 @@
+package com.netspi.awssigner.controller;
+
+import burp.BurpExtender;
+import burp.IContextMenuInvocation;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.netspi.awssigner.credentials.ProfileCredentialTester;
+import com.netspi.awssigner.log.LogLevel;
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import com.netspi.awssigner.model.AWSSignerConfiguration;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.view.AddProfileDialog;
+import com.netspi.awssigner.view.BurpTabPanel;
+import java.awt.CardLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ItemEvent;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.BiConsumer;
+import javax.swing.DefaultListModel;
+import javax.swing.SwingUtilities;
+import javax.swing.event.ListSelectionEvent;
+import static com.netspi.awssigner.log.LogWriter.*;
+import com.netspi.awssigner.model.persistence.ProfileExporter;
+import com.netspi.awssigner.view.BurpUIComponentCustomizer;
+import com.netspi.awssigner.view.CopyProfileDialog;
+import com.netspi.awssigner.view.ImportDialog;
+import java.awt.Component;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.stream.Collectors;
+import javax.swing.ButtonGroup;
+import javax.swing.JFileChooser;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JRadioButtonMenuItem;
+
+/**
+ * The complex class which enforces logic and syncs up the configuration model
+ * and the UI view.
+ */
+public class AWSSignerController {
+
+ private final BurpTabPanel view;
+ private final AWSSignerConfiguration model;
+
+ private final static String INIT_PROFILE_NAME = "Profile 1";
+
+ //Need these because we have to add and remove when setting up / updating combo boxes
+ private ComboBoxProfileSelectionListener alwaysSignWithComboBoxProfileSelectionListener;
+ private ComboBoxProfileSelectionListener assumerProfileComboBoxProfileSelectionListener;
+
+ public AWSSignerController(BurpTabPanel view, AWSSignerConfiguration model) {
+ this.view = view;
+ this.model = model;
+
+ initListeners();
+
+ //Add the initial profile
+ addProfile(new StaticCredentialsProfile(INIT_PROFILE_NAME));
+ }
+
+ private void initListeners() {
+ //Global signing checkbox
+ view.signingEnabledCheckbox.addItemListener((ItemEvent e) -> {
+ logDebug("Global Signing Enabled Checkbox State Change.");
+ model.isEnabled = (e.getStateChange() == ItemEvent.SELECTED);
+ logInfo("Signing Enabled: " + model.isEnabled);
+ });
+
+ //"Always Sign With" profile selection combox box
+ alwaysSignWithComboBoxProfileSelectionListener = new ComboBoxProfileSelectionListener(model, "Always Sign With", (Profile profile) -> {
+ logDebug("Setting \"Always Sign With\" Profile to: " + profile);
+ model.alwaysSignWithProfile = profile;
+ });
+ view.alwaysSignWithProfileComboBox.addItemListener(alwaysSignWithComboBoxProfileSelectionListener);
+
+ //Logging Level combox box
+ view.logLevelComboBox.addItemListener(((event) -> {
+ logDebug("Log Level ComboBox Item Event:" + " StateChange: " + event.getStateChange() + " Item: " + event.getItem());
+ if (event.getStateChange() == ItemEvent.SELECTED) {
+ String selectedLoggingLevel = (String) event.getItem();
+ LogLevel newLoggingLevel = LogLevel.valueOf(selectedLoggingLevel.toUpperCase());
+ logDebug("New logging level set to: " + newLoggingLevel);
+ LogWriter.setLevel(newLoggingLevel);
+ }
+ }));
+
+ //Add button
+ view.addProfileButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Add Profile Button Clicked.");
+ final AddProfileDialog dialog = new AddProfileDialog(null, true, model.getProfileNames());
+ BurpUIComponentCustomizer.applyBurpStyling(dialog);
+ dialog.pack();
+ dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(view));
+ Optional addProfileResult = dialog.showDialog();
+ if (addProfileResult.isPresent()) {
+ Profile newProfile = addProfileResult.get();
+ logInfo("New profile to be added from Add dialog: " + newProfile);
+ addProfile(newProfile);
+ } else {
+ logInfo("No new profile returned from Add dialog.");
+ }
+ }));
+
+ //Delete button
+ view.deleteProfileButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Delete Profile Button Clicked.");
+
+ Optional currentSelectedProfileOptional = getCurrentSelectedProfile();
+ if (currentSelectedProfileOptional.isEmpty()) {
+ logError("There is no current profile selected. Cannot delete.");
+ return;
+ }
+ final Profile selectedProfile = currentSelectedProfileOptional.get();
+ final String selectedProfileName = selectedProfile.getName();
+
+ //Check if selectedProfile is allowed to be deleted.
+ //No other profile must use this one as the assumer
+ List dependentProfileNames = model.profiles.stream().filter(profile -> {
+ return profile instanceof AssumeRoleProfile
+ && ((AssumeRoleProfile) profile).getAssumerProfile().isPresent()
+ && ((AssumeRoleProfile) profile).getAssumerProfile().get().getName().equals(selectedProfileName);
+ }).map(Profile::getName).collect(Collectors.toList());
+ if (!dependentProfileNames.isEmpty()) {
+ JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(view),
+ "Cannot delete profile \"" + selectedProfileName + "\" as it is the assumer profile for the following profile(s): " + dependentProfileNames,
+ "Cannot Delete Profile", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+
+ //Check if the selected profile is currently the default profile
+ if (model.alwaysSignWithProfile != null && model.alwaysSignWithProfile.getName().equals(selectedProfileName)) {
+ JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(view),
+ "Cannot delete profile \"" + selectedProfileName + "\" because it is the current default profile.",
+ "Cannot Delete Profile", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+
+ //Looks good, we should be able to delete.
+ //Show confirmation dialog
+ int result = JOptionPane.showConfirmDialog(SwingUtilities.getWindowAncestor(view),
+ "Are you sure you want to delete profile " + selectedProfileName + "?",
+ "Confirm Profile Delete",
+ JOptionPane.YES_NO_OPTION,
+ JOptionPane.QUESTION_MESSAGE);
+ if (result == JOptionPane.YES_OPTION) {
+ logInfo("Deletion was confirmed");
+ deleteProfile(selectedProfile);
+ } else {
+ logInfo("Deletion was not confirmed");
+ }
+ }));
+
+ //Copy button
+ view.copyProfileButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Copy Profile Button Clicked.");
+ Optional optionalCurrentProfile = getCurrentSelectedProfile();
+ if (optionalCurrentProfile.isEmpty()) {
+
+ } else {
+ Profile currentSelectedProfile = optionalCurrentProfile.get();
+ logInfo("Copying profile: " + currentSelectedProfile.getName());
+ final CopyProfileDialog dialog = new CopyProfileDialog(null, true, model.getProfileNames(), currentSelectedProfile);
+ BurpUIComponentCustomizer.applyBurpStyling(dialog);
+ dialog.pack();
+ dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(view));
+ Optional copyProfileResult = dialog.showDialog();
+ if (copyProfileResult.isPresent()) {
+ Profile newProfile = copyProfileResult.get();
+ logInfo("New profile to be added from Copy dialog: " + newProfile);
+ addProfile(newProfile);
+ } else {
+ logInfo("No new profile returned from Copy dialog.");
+ }
+ }
+ }));
+
+ //Import button
+ view.importProfilesButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Import Profile Button Clicked.");
+ final ImportDialog dialog = new ImportDialog(null, true, model.getProfileNames());
+ BurpUIComponentCustomizer.applyBurpStyling(dialog);
+ dialog.pack();
+ dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(view));
+ Optional> importProfilesResult = dialog.showDialog();
+ if (importProfilesResult.isPresent()) {
+ List importedProfiles = importProfilesResult.get();
+ logInfo("New profiles to be added from import dialog: " + importedProfiles);
+ importedProfiles.stream().forEachOrdered(this::addProfile);
+ } else {
+ logInfo("No new profiles returned from import dialog.");
+ }
+ }));
+
+ //Export button
+ view.exportProfilesButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Export Profile Button Clicked.");
+ JFileChooser fileChooser = new JFileChooser();
+ if (fileChooser.showSaveDialog(SwingUtilities.getWindowAncestor(view)) == JFileChooser.APPROVE_OPTION) {
+ Path exportPath = fileChooser.getSelectedFile().toPath();
+ ProfileExporter exporter = new ProfileExporter(exportPath);
+ try {
+ exporter.exportProfiles(model.profiles);
+ } catch (IOException ex) {
+ logError("Unable to export profiles to file " + exportPath + " due to exception: " + ex);
+ }
+ }
+ }));
+
+ //Selected profile
+ view.profileList.addListSelectionListener((ListSelectionEvent e) -> {
+ boolean valueIsAdjusting = e.getValueIsAdjusting();
+ String selectedProfileName = view.profileList.getSelectedValue();
+ logDebug("Profile List Item Selected."
+ + " ValueIsAdjusting: " + valueIsAdjusting
+ + " FirstIndex: " + e.getFirstIndex()
+ + " LastIndex: " + e.getLastIndex()
+ + " Selected Profile Name: " + selectedProfileName);
+
+ //We only care about the final result
+ if (!valueIsAdjusting && selectedProfileName != null) {
+ logInfo("Profile List Item Selected Value: " + selectedProfileName);
+ Profile selectedProfile = model.getProfileForName(selectedProfileName).get();
+ //Update the display to show the profile's configuration.
+ initializeProfileConfigurationTab(selectedProfile);
+ }
+
+ });
+
+ //Profile enabled checkbox
+ view.profileEnabledCheckbox.addItemListener((ItemEvent e) -> {
+ handleProfileConfigurationCheckboxEvent(e, "Signing Enabled", Profile::setEnabled);
+ });
+
+ //Profile in-scope-only checkbox
+ view.profileInScopeOnlyCheckbox.addItemListener((ItemEvent e) -> {
+ handleProfileConfigurationCheckboxEvent(e, "In-Scope Only Checkbox", Profile::setInScopeOnly);
+ });
+
+ //Profile Region text field
+ view.profileRegionTextField.addFocusListener(new TextComponentFocusListener<>(this, "Region", Profile::setRegion));
+
+ //Profile Service text field
+ view.profileServiceTextField.addFocusListener(new TextComponentFocusListener<>(this, "Service", Profile::setService));
+
+ //Profile Key Id text field
+ view.profileKeyIdTextField.addFocusListener(new TextComponentFocusListener<>(this, "Key Id", Profile::setKeyId));
+
+ //Test credentials button
+ view.testProfileButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Test Credentials Button Clicked.");
+
+ Optional currentProfileOptional = getCurrentSelectedProfile();
+ if (currentProfileOptional.isEmpty()) {
+ logDebug("There is no currently selected profile to test credentials for.");
+ return;
+ }
+
+ Profile profile = currentProfileOptional.get();
+ //Check if we even have enough information to test this profile
+ if (!profile.requiredFieldsAreSet()) {
+ logDebug("Profile " + profile.getName() + " does not have all required fields");
+ updateProfileStatus();
+ return;
+ }
+
+ view.profileStatusTextLabel.setText("Starting profile test");
+
+ //Run in another thread to not block the UI
+ new Thread(() -> {
+ ProfileCredentialTester tester = new ProfileCredentialTester(profile);
+ try {
+ SigningCredentials creds = tester.testProfile();
+
+ logInfo("Successfully obtained credentials with profile: " + profile.getName());
+
+ //Check if we're still showing the same profile
+ Optional newProfileOptional = getCurrentSelectedProfile();
+ if (newProfileOptional.isEmpty()) {
+ logDebug("There is no currently selected profile to test credentials for.");
+ //No profile is currnetly selected
+ }
+ Profile newProfile = newProfileOptional.get();
+ if (profile.getName().equals(newProfile.getName())) {
+ //Showing the same profile. we can update UI fields.
+ view.profileStatusTextLabel.setText("Success");
+ if (profile instanceof CommandProfile) {
+ view.commandExtractedAccessKeyTextField.setText(creds.getAccessKey());
+ view.commandExtractedSecretKeyTextField.setText(creds.getSecretKey());
+ if (creds.getSessionToken().isPresent()) {
+ view.commandExtractedSessionTokenTextField.setText(creds.getSessionToken().get());
+ }
+ }
+ }
+
+ } catch (Exception ex) {
+ logError("Failed to obtain credentials with profile: " + profile.getName());
+
+ //Quick check to see if we need to report the cause at one level deeper
+ Throwable cause = ex.getCause() == null ? ex : ex.getCause();
+ logError("Cause: " + cause.getMessage());
+ view.profileStatusTextLabel.setText("Error testing profile: " + cause.getMessage());
+ }
+ }).start();
+
+ }));
+
+ //Static Credentials Access Key text field
+ view.staticAccessKeyTextField.addFocusListener(new TextComponentFocusListener<>(this, "Static Credentials Access Key", StaticCredentialsProfile::setAccessKey));
+
+ //Static Credentials Secret Key text field
+ view.staticSecretKeyTextField.addFocusListener(new TextComponentFocusListener<>(this, "Static Credentials Secret Key", StaticCredentialsProfile::setSecretKey));
+
+ //Static Credentials Session Token text field
+ view.staticSessionTokenTextField.addFocusListener(new TextComponentFocusListener<>(this, "Static Credentials Secret Key", StaticCredentialsProfile::setSessionToken));
+
+ //AssumeRole assumer profile
+ assumerProfileComboBoxProfileSelectionListener = new ComboBoxProfileSelectionListener(model, "Always Sign With", (Profile profile) -> {
+ //This SHOULD be a safe assumption, but I'm concerned...
+ AssumeRoleProfile currentSelectedProfile = (AssumeRoleProfile) getCurrentSelectedProfile().get();
+ logDebug("Setting \"Assumer Profile\" Profile of " + currentSelectedProfile.getName() + " to: " + profile);
+ currentSelectedProfile.setAssumerProfile(profile);
+ });
+ view.assumeRoleAssumerProfileComboBox.addItemListener(assumerProfileComboBoxProfileSelectionListener);
+
+ //AssumeRole Role ARN text field
+ view.assumeRoleRoleArnTextField.addFocusListener(new TextComponentFocusListener<>(this, "AssumeRole Role ARN", AssumeRoleProfile::setRoleArn));
+
+ //AssumeRole Session Name text field
+ view.assumeRoleSessionNameTextField.addFocusListener(new TextComponentFocusListener<>(this, "AssumeRole Session Name", AssumeRoleProfile::setSessionName));
+
+ //AssumeRole External Id text field
+ view.assumeRoleExternalIdTextField.addFocusListener(new TextComponentFocusListener<>(this, "AssumeRole External Id", AssumeRoleProfile::setExternalId));
+
+ //AssumeRole Duration text field
+ view.assumeRoleDurationTextField.addFocusListener(new TextComponentFocusListener<>(this, "AssumeRole Duration Seconds", AssumeRoleProfile::setDurationSecondsFromText));
+
+ //AssumeRole Session Policy text area
+ view.assumeRoleSessionPolicyTextArea.addFocusListener(new TextComponentFocusListener<>(this, "AssumeRole Session Policy", AssumeRoleProfile::setSessionPolicy));
+
+ //AssumeRole Session Policy Prettify Button
+ view.assumeRoleSessionPolicyPrettifyButton.addActionListener(((ActionEvent e) -> {
+ logDebug("Session Policy Prettify Button Clicked.");
+
+ //This SHOULD be a safe assumption, but I'm concerned...
+ AssumeRoleProfile currentSelectedProfile = (AssumeRoleProfile) getCurrentSelectedProfile().get();
+ Optional sessionPolicyOptional = currentSelectedProfile.getSessionPolicy();
+
+ if (sessionPolicyOptional.isPresent()) {
+ String sessionPolicy = sessionPolicyOptional.get();
+ try {
+ //Parse the session policy text into JSON
+ JsonObject json = JsonParser.parseString(sessionPolicy).getAsJsonObject();
+
+ //Back to a string with pretty-printing
+ String prettyJson = new GsonBuilder().setPrettyPrinting().create().toJson(json);
+
+ //Set both the profile value and the UI field
+ view.assumeRoleSessionPolicyTextArea.setText(prettyJson);
+ currentSelectedProfile.setSessionPolicy(prettyJson);
+ } catch (RuntimeException ex) {
+ logError("Unable to parse session policy into JSON object and pretty print. Current value: " + sessionPolicy);
+ //Quick check to see if we need to report the cause at one level deeper
+ Throwable cause = ex.getCause() == null ? ex : ex.getCause();
+ view.profileStatusTextLabel.setText("Session policy error: " + cause.getMessage());
+ }
+ } else {
+ logDebug("There's no current session policy. Nothing to set.");
+ }
+
+ }));
+
+ //Command Duration text field
+ view.commandCommandTextField.addFocusListener(new TextComponentFocusListener<>(this, "Command Command", CommandProfile::setCommand));
+
+ //Command Duration text field
+ view.commandDurationTextField.addFocusListener(new TextComponentFocusListener<>(this, "Command Duration Seconds", CommandProfile::setDurationSecondsFromText));
+
+ //Add focus handler to various components (panels, etc) to ensure that when the user clicks out of input field, that field loses focus.
+ addFocusGrabber(view.globalSettingsPanel);
+ addFocusGrabber(view.profileListScrollPane);
+ addFocusGrabber(view.rightSideParentPanel);
+ addFocusGrabber(view.profileConfigurationPanel);
+ addFocusGrabber(view.profileConfigurationScrollPane);
+ addFocusGrabber(view.staticCredentialsPanel);
+ addFocusGrabber(view.assumeRolePanel);
+ addFocusGrabber(view.commandPanel);
+ addFocusGrabber(view.commandPanel);
+
+ }
+
+ private void addFocusGrabber(final Component focusable) {
+
+ focusable.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ LogWriter.logDebug("Grabbing focus for containing component.");
+ focusable.requestFocusInWindow();
+ }
+ });
+ }
+
+ private void handleProfileConfigurationCheckboxEvent(ItemEvent e, String propertyLoggingName, BiConsumer updateFunction) {
+ logDebug("Profile " + propertyLoggingName + " State Change:" + e.getStateChange());
+ boolean checkboxEnabled = (e.getStateChange() == ItemEvent.SELECTED);
+ Optional currentProfileOptional = getCurrentSelectedProfile();
+ if (currentProfileOptional.isPresent()) {
+ Profile currentProfile = currentProfileOptional.get();
+ logInfo("Profile " + currentProfile.getName() + " " + propertyLoggingName + " changed to " + (checkboxEnabled ? "enabled" : "disabled"));
+ updateFunction.accept(currentProfile, checkboxEnabled);
+ } else {
+ logDebug("Profile " + propertyLoggingName + " changed, but no profile selected. Ignoring.");
+ }
+ updateProfileStatus();
+ }
+
+ private void addProfile(Profile newProfile) {
+ //Add it to our model for tracking
+ model.profiles.add(newProfile);
+
+ //Setup profile list
+ DefaultListModel listModel = resetProfileList();
+ view.profileList.setSelectedIndex(listModel.indexOf(newProfile.getName()));
+
+ //Reset "Always Sign With" combo box
+ resetAlwaysSignWithProfileComboBox();
+
+ initializeProfileConfigurationTab(newProfile);
+ }
+
+ private void deleteProfile(Profile profile) {
+ //Confirm our model contains the profile. This is just a sanity check
+ if (!model.profiles.contains(profile)) {
+ logError("Attempting to delete profile which doesn't exist. Something is wrong!");
+ return;
+ }
+ logDebug("Removing " + profile.getName());
+
+ //TODO: Need to handle 2 main cases.
+ if (model.profiles.size() == 1) {
+ //1. We're removing the only model, reset to initial view
+ logDebug("Removing only profile. Resetting to initial display");
+ model.profiles.remove(profile);
+ resetProfileList();
+ resetAlwaysSignWithProfileComboBox();
+ resetProfileConfigurationTabToDefault();
+ } else {
+ //2. There is at least one other profile. Select the next one.
+ logDebug("Removing profile and selecting the next in line.");
+
+ //Determine which profile will be shown next.
+ DefaultListModel listModel = resetProfileList();
+ int indexToBeDeleted = listModel.indexOf(profile.getName());
+ //if we're at the bottom, select one up, otherwise select one profile down
+ int nextSelectionIndex;
+ if (indexToBeDeleted == listModel.size() - 1) {
+ nextSelectionIndex = indexToBeDeleted - 1;
+ } else {
+ nextSelectionIndex = indexToBeDeleted + 1;
+ }
+ String nextProfileName = (String) listModel.get(nextSelectionIndex);
+
+ //OK now remove it
+ model.profiles.remove(profile);
+ resetProfileList();
+ resetAlwaysSignWithProfileComboBox();
+
+ //Select and display the next choice.
+ listModel = resetProfileList();
+ Profile selectedProfile = model.getProfileForName(nextProfileName).get();
+ view.profileList.setSelectedIndex(listModel.indexOf(nextProfileName));
+ initializeProfileConfigurationTab(selectedProfile);
+ }
+
+ }
+
+ private void initializeProfileConfigurationTab(Profile currentProfile) {
+ initializeProfileConfigurationCommonFields(currentProfile);
+
+ //Handle type-specific fields
+ if (currentProfile instanceof StaticCredentialsProfile) {
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) currentProfile;
+ initializeStaticCredentialsProfileFields(staticCredentialsProfile);
+ ((CardLayout) view.credentialCardContainerPanel.getLayout()).show(view.credentialCardContainerPanel, "static_credentials_card");
+ } else if (currentProfile instanceof AssumeRoleProfile) {
+ AssumeRoleProfile assumeRoleProfile = (AssumeRoleProfile) currentProfile;
+ initializeAssumeRoleProfileFields(assumeRoleProfile);
+ ((CardLayout) view.credentialCardContainerPanel.getLayout()).show(view.credentialCardContainerPanel, "assume_role_card");
+ } else if (currentProfile instanceof CommandProfile) {
+ CommandProfile commandProfile = (CommandProfile) currentProfile;
+ initializeCommandProfileFields(commandProfile);
+ ((CardLayout) view.credentialCardContainerPanel.getLayout()).show(view.credentialCardContainerPanel, "command_card");
+ } else {
+ throw new IllegalStateException("Profile does not match expected type. Found Type: " + currentProfile.getClass().getName());
+ }
+
+ //Update the profile's status:
+ updateProfileStatus();
+ }
+
+ private void resetProfileConfigurationTabToDefault() {
+ //Reset the "common" fields
+ view.profileNameLabel.setText("[Add A Profile To Begin]");
+ view.profileEnabledCheckbox.setEnabled(false);
+ view.profileEnabledCheckbox.setSelected(false);
+ view.profileInScopeOnlyCheckbox.setEnabled(false);
+ view.profileInScopeOnlyCheckbox.setSelected(false);
+ view.profileRegionTextField.setEnabled(false);
+ view.profileRegionTextField.setText("");
+ view.profileServiceTextField.setEnabled(false);
+ view.profileServiceTextField.setText("");
+ view.profileKeyIdTextField.setEnabled(false);
+ view.profileKeyIdTextField.setText("");
+ view.testProfileButton.setEnabled(false);
+
+ //Default to the static creds card
+ ((CardLayout) view.credentialCardContainerPanel.getLayout()).show(view.credentialCardContainerPanel, "static_credentials_card");
+ view.staticAccessKeyTextField.setEnabled(false);
+ view.staticAccessKeyTextField.setText("");
+ view.staticAccessKeyTextField.getInputVerifier().shouldYieldFocus(view.staticAccessKeyTextField, view.staticAccessKeyTextField);
+ view.staticSecretKeyTextField.setEnabled(false);
+ view.staticSecretKeyTextField.setText("");
+ view.staticSecretKeyTextField.getInputVerifier().shouldYieldFocus(view.staticSecretKeyTextField, view.staticSecretKeyTextField);
+ view.staticSessionTokenTextField.setEnabled(false);
+ view.staticSessionTokenTextField.setText("");
+ view.profileStatusTextLabel.setText("Must add profile to begin editing");
+
+ }
+
+ private void initializeProfileConfigurationCommonFields(Profile currentProfile) {
+ //Update the Profile Configuration Tab common fields
+ view.profileNameLabel.setText(currentProfile.getName());
+ view.profileEnabledCheckbox.setEnabled(true);
+ view.profileEnabledCheckbox.setSelected(currentProfile.isEnabled());
+ view.profileInScopeOnlyCheckbox.setEnabled(true);
+ view.profileInScopeOnlyCheckbox.setSelected(currentProfile.isInScopeOnly());
+ view.profileRegionTextField.setEnabled(true);
+ view.profileRegionTextField.setText(currentProfile.getRegion().orElse(""));
+ view.profileServiceTextField.setEnabled(true);
+ view.profileServiceTextField.setText(currentProfile.getService().orElse(""));
+ view.profileKeyIdTextField.setEnabled(true);
+ view.profileKeyIdTextField.setText(currentProfile.getKeyId().orElse(""));
+ view.testProfileButton.setEnabled(true);
+ }
+
+ private void initializeStaticCredentialsProfileFields(StaticCredentialsProfile staticCredentialsProfile) {
+ String accessKey = staticCredentialsProfile.getAccessKey().orElse("");
+ String secretKey = staticCredentialsProfile.getSecretKey().orElse("");
+ String sessionToken = staticCredentialsProfile.getSessionToken().orElse("");
+
+ view.staticAccessKeyTextField.setEnabled(true);
+ view.staticAccessKeyTextField.setText(accessKey);
+ view.staticAccessKeyTextField.getInputVerifier().shouldYieldFocus(view.staticAccessKeyTextField, view.staticAccessKeyTextField);
+ view.staticSecretKeyTextField.setEnabled(true);
+ view.staticSecretKeyTextField.setText(secretKey);
+ view.staticSecretKeyTextField.getInputVerifier().shouldYieldFocus(view.staticSecretKeyTextField, view.staticSecretKeyTextField);
+ view.staticSessionTokenTextField.setEnabled(true);
+ view.staticSessionTokenTextField.setText(sessionToken);
+
+ //Calculate initial status
+ if ((accessKey == null) && (secretKey == null)) {
+ view.profileStatusTextLabel.setText("Missing Access Key and Secret Key");
+ } else if ((accessKey == null)) {
+ view.profileStatusTextLabel.setText("Missing Access Key");
+ } else if ((secretKey == null)) {
+ view.profileStatusTextLabel.setText("Missing Secret Key");
+ } else {
+ view.profileStatusTextLabel.setText("Ready for testing");
+ }
+ }
+
+ private void initializeAssumeRoleProfileFields(AssumeRoleProfile assumeRoleProfile) {
+
+ //Calculate which profiles may be used as the assumer
+ List profiles = model.profiles;
+ List profileNames = profiles.stream()
+ .filter(profile -> {
+ final String potentialAssumerProfileName = profile.getName();
+ logDebug("Checking if profile should be included in assumer profile choices: " + potentialAssumerProfileName);
+ //Check if the potential profile is the profile being shown.
+ //AssumeRole can't use itself as the assumer
+ if (potentialAssumerProfileName.equals(assumeRoleProfile.getName())) {
+ logDebug("Excluding self from assumer profile choices: " + potentialAssumerProfileName);
+ return false;
+ }
+
+ //This loop prevents a cycle of assume role. Walk up the chain
+ // of assumer profiles and confirm the current profile isn't present
+ // in that chain.
+ Profile potentialAssumer = profile;
+ while (potentialAssumer instanceof AssumeRoleProfile) {
+
+ //This is an assume role profile itself.
+ Optional parentAssumerProfileOptional = ((AssumeRoleProfile) potentialAssumer).getAssumerProfile();
+ //Check if the parent is set.
+ if (parentAssumerProfileOptional.isPresent()) {
+ Profile parentAssumerProfile = parentAssumerProfileOptional.get();
+ //Make sure the parent assumer profile is not the same one being configured. That would be a cycle.
+ if (parentAssumerProfile.getName().equals(assumeRoleProfile.getName())) {
+ logDebug("Excluding "
+ + potentialAssumerProfileName
+ + " from being an assumer profile for "
+ + assumeRoleProfile.getName()
+ + " because it would create a cycle through the "
+ + potentialAssumer.getName() + " profile.");
+ return false;
+ }
+ //Loop again to go up another level
+ potentialAssumer = parentAssumerProfile;
+ } else {
+ //The parent isn't set. Safe to break out and include
+ break;
+ }
+ }
+ //If we made it here, no cycle detected. This profile can be an assumer
+ logDebug("Including profile in assumer profile choices: " + potentialAssumerProfileName);
+ return true;
+ })
+ .map(Profile::getName)
+ .collect(Collectors.toList());
+
+ //Setup the assumer profile combobox
+ view.assumeRoleAssumerProfileComboBox.removeItemListener(assumerProfileComboBoxProfileSelectionListener);
+ view.assumeRoleAssumerProfileComboBox.removeAllItems();
+ view.assumeRoleAssumerProfileComboBox.addItem(""); //Add a blank
+ profileNames.forEach((name) -> {
+ view.assumeRoleAssumerProfileComboBox.addItem(name);
+ });
+
+ if (assumeRoleProfile.getAssumerProfile().isPresent()) {
+ String parentAssumerProfileName = assumeRoleProfile.getAssumerProfile().get().getName();
+ logDebug("Setting selected assumer profile to: " + parentAssumerProfileName);
+ view.assumeRoleAssumerProfileComboBox.setSelectedItem(parentAssumerProfileName);
+ }
+ view.assumeRoleAssumerProfileComboBox.addItemListener(assumerProfileComboBoxProfileSelectionListener);
+
+ view.assumeRoleRoleArnTextField.setText(assumeRoleProfile.getRoleArn().orElse(null));
+ view.assumeRoleRoleArnTextField.getInputVerifier().shouldYieldFocus(view.assumeRoleRoleArnTextField, view.assumeRoleRoleArnTextField);
+ view.assumeRoleSessionNameTextField.setText(assumeRoleProfile.getSessionName().orElse(null));
+ view.assumeRoleExternalIdTextField.setText(assumeRoleProfile.getExternalId().orElse(null));
+ if (assumeRoleProfile.getDurationSeconds().isEmpty()) {
+ view.assumeRoleDurationTextField.setText(null);
+ } else {
+ view.assumeRoleDurationTextField.setText(Integer.toString(assumeRoleProfile.getDurationSeconds().get()));
+ }
+ view.assumeRoleDurationTextField.getInputVerifier().shouldYieldFocus(view.assumeRoleDurationTextField, view.assumeRoleDurationTextField);
+ view.assumeRoleSessionPolicyTextArea.setText(assumeRoleProfile.getSessionPolicy().orElse(null));
+
+ }
+
+ private void initializeCommandProfileFields(CommandProfile commandProfile) {
+ String command = commandProfile.getCommand().orElse("");
+ Optional durationSeconds = commandProfile.getDurationSeconds();
+ view.commandCommandTextField.setText(command);
+ view.commandCommandTextField.getInputVerifier().shouldYieldFocus(view.commandCommandTextField, view.commandCommandTextField);
+ if (durationSeconds.isEmpty()) {
+ view.commandDurationTextField.setText(null);
+ } else {
+ view.commandDurationTextField.setText(Integer.toString(durationSeconds.get()));
+ }
+ view.commandExtractedAccessKeyTextField.setText("");
+ view.commandExtractedSecretKeyTextField.setText("");
+ view.commandExtractedSessionTokenTextField.setText("");
+ }
+
+ void updateProfileStatus() {
+ Optional currentProfileOptional = getCurrentSelectedProfile();
+ String status = "Unknown";
+ if (currentProfileOptional.isPresent()) {
+ Profile currentProfile = currentProfileOptional.get();
+ //Handle type-specific status calculation
+ if (currentProfile instanceof StaticCredentialsProfile) {
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) currentProfile;
+ if (staticCredentialsProfile.getAccessKey().isEmpty() && staticCredentialsProfile.getSecretKey().isEmpty()) {
+ status = "Missing Access Key and Secret Key";
+ } else if (staticCredentialsProfile.getAccessKey().isEmpty()) {
+ status = "Missing Access Key";
+ } else if (staticCredentialsProfile.getSecretKey().isEmpty()) {
+ status = "Missing Secret Key";
+ } else {
+ status = "Ready for testing";
+ }
+ } else if (currentProfile instanceof AssumeRoleProfile) {
+ AssumeRoleProfile assumeRoleProfile = (AssumeRoleProfile) currentProfile;
+ Optional assumerProfile = assumeRoleProfile.getAssumerProfile();
+ Optional roleArn = assumeRoleProfile.getRoleArn();
+ if (assumerProfile.isEmpty() && roleArn.isEmpty()) {
+ status = "Missing Assumer Profile and Role ARN";
+ } else if (assumerProfile.isEmpty()) {
+ status = "Missing Assumer Profile";
+ } else if (roleArn.isEmpty()) {
+ status = "Missing Role ARN";
+ } else {
+ status = "Ready for testing";
+ }
+ } else if (currentProfile instanceof CommandProfile) {
+ CommandProfile commandProfile = (CommandProfile) currentProfile;
+ if (commandProfile.getCommand().isEmpty()) {
+ status = "Missing Command";
+ } else {
+ status = "Ready for testing";
+ }
+ } else {
+ final String errorMessage = "Profile does not match expected type. Found Type: " + currentProfile.getClass().getName();
+ logError(errorMessage);
+ throw new IllegalStateException(errorMessage);
+ }
+ }
+
+ logDebug("Profile status set as: " + status);
+ view.profileStatusTextLabel.setText(status);
+ }
+
+ private DefaultListModel resetProfileList() {
+ //Update our URI to track
+ //Reset the profile list
+ DefaultListModel listModel = new DefaultListModel();
+ List profileNames = model.getProfileNames();
+ listModel.addAll(profileNames);
+ view.profileList.setModel(listModel);
+ return listModel;
+ }
+
+ private void resetAlwaysSignWithProfileComboBox() {
+ view.alwaysSignWithProfileComboBox.removeItemListener(alwaysSignWithComboBoxProfileSelectionListener);
+ List profileNames = model.getProfileNames();
+ view.alwaysSignWithProfileComboBox.removeAllItems();
+ view.alwaysSignWithProfileComboBox.addItem(" "); //Add a blank
+ profileNames.forEach((name) -> {
+ view.alwaysSignWithProfileComboBox.addItem(name);
+ });
+ if (model.alwaysSignWithProfile != null) {
+ view.alwaysSignWithProfileComboBox.setSelectedItem(model.alwaysSignWithProfile.getName());
+ }
+ view.alwaysSignWithProfileComboBox.addItemListener(alwaysSignWithComboBoxProfileSelectionListener);
+ }
+
+ public Optional getCurrentSelectedProfile() {
+ String selectedProfileName = view.profileList.getSelectedValue();
+ return model.getProfileForName(selectedProfileName);
+ }
+
+ public List getMenuItems(IContextMenuInvocation invocation) {
+ JMenu menu = new JMenu(BurpExtender.EXTENSION_NAME);
+
+ //Enable/Disable global signing sub menu
+ JMenu signerEnableSubmenu = new JMenu("Enable/Disable Signing");
+ ButtonGroup signerEnableGroup = new ButtonGroup();
+ JRadioButtonMenuItem enableSigningMenuItem = new JRadioButtonMenuItem("Enable Signing", model.isEnabled);
+ enableSigningMenuItem.addActionListener((event) -> {
+ logDebug("Signing enabled via context menu");
+ model.isEnabled = true;
+ view.signingEnabledCheckbox.setSelected(true);
+ });
+ signerEnableGroup.add(enableSigningMenuItem);
+ signerEnableSubmenu.add(enableSigningMenuItem);
+ JRadioButtonMenuItem disableSigningMenuItem = new JRadioButtonMenuItem("Disable Signing", !model.isEnabled);
+ disableSigningMenuItem.addActionListener((event) -> {
+ logDebug("Signing disabled via context menu");
+ model.isEnabled = false;
+ view.signingEnabledCheckbox.setSelected(false);
+ });
+ signerEnableGroup.add(disableSigningMenuItem);
+ signerEnableSubmenu.add(disableSigningMenuItem);
+ menu.add(signerEnableSubmenu);
+
+ //Set Default Profile
+ JMenu defaultProfileSubmenu = new JMenu("Set \"Always Sign With\" Profile");
+ ButtonGroup defaultProfileGroup = new ButtonGroup();
+
+ //The first profile is special since it represents NOT having a default profile
+ JRadioButtonMenuItem noDefaultProfileItem = new JRadioButtonMenuItem("No Profile", model.alwaysSignWithProfile == null);
+ noDefaultProfileItem.addActionListener((event) -> {
+ logDebug("Always sign with profile unset via context menu");
+ model.alwaysSignWithProfile = null;
+ resetAlwaysSignWithProfileComboBox();
+ });
+ defaultProfileGroup.add(noDefaultProfileItem);
+ defaultProfileSubmenu.add(noDefaultProfileItem);
+
+ List profileList = model.profiles;
+ for (Profile profile : profileList) {
+ JRadioButtonMenuItem profileItem = new JRadioButtonMenuItem(profile.getName(), model.alwaysSignWithProfile != null && model.alwaysSignWithProfile.getName().equals(profile.getName()));
+ profileItem.addActionListener((event) -> {
+ logDebug("Default profile set via context menu. Chosen profile: " + profile.getName());
+ model.alwaysSignWithProfile = profile;
+ resetAlwaysSignWithProfileComboBox();
+ });
+ defaultProfileGroup.add(profileItem);
+ defaultProfileSubmenu.add(profileItem);
+ }
+ menu.add(defaultProfileSubmenu);
+
+ List list = new ArrayList<>();
+ list.add(menu);
+ return list;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/controller/ComboBoxProfileSelectionListener.java b/src/main/java/com/netspi/awssigner/controller/ComboBoxProfileSelectionListener.java
new file mode 100644
index 0000000..773b919
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/controller/ComboBoxProfileSelectionListener.java
@@ -0,0 +1,38 @@
+package com.netspi.awssigner.controller;
+
+import static com.netspi.awssigner.log.LogWriter.*;
+import com.netspi.awssigner.model.AWSSignerConfiguration;
+import com.netspi.awssigner.model.Profile;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.util.function.Consumer;
+
+
+class ComboBoxProfileSelectionListener implements ItemListener {
+
+ private final AWSSignerConfiguration model;
+ private final String comboboxFriendlyName;
+ private final Consumer profileAssignmentFunction;
+
+ public ComboBoxProfileSelectionListener(AWSSignerConfiguration model, String comboboxFriendlyName, Consumer profileAssignmentFunction) {
+ this.model = model;
+ this.comboboxFriendlyName = comboboxFriendlyName;
+ this.profileAssignmentFunction = profileAssignmentFunction;
+ }
+
+ @Override
+ public void itemStateChanged(ItemEvent event) {
+ logDebug("\"" + comboboxFriendlyName + "\" Profile ComboBox Item Event:" + " StateChange: " + event.getStateChange() + " Item: " + event.getItem());
+ if (event.getStateChange() == ItemEvent.SELECTED) {
+ String selectedProfileName = (String) event.getItem();
+ if (selectedProfileName.trim().isEmpty()) {
+ logInfo("\"" + comboboxFriendlyName + "\" Profile unset");
+ profileAssignmentFunction.accept(null);
+ } else {
+ logInfo("New \"" + comboboxFriendlyName + "\" Profile set: " + selectedProfileName);
+ profileAssignmentFunction.accept(model.getProfileForName(selectedProfileName).orElse(null));
+ }
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/controller/TextComponentFocusListener.java b/src/main/java/com/netspi/awssigner/controller/TextComponentFocusListener.java
new file mode 100644
index 0000000..1802b9c
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/controller/TextComponentFocusListener.java
@@ -0,0 +1,66 @@
+package com.netspi.awssigner.controller;
+
+import static com.netspi.awssigner.log.LogWriter.*;
+import com.netspi.awssigner.model.Profile;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.util.Optional;
+import java.util.function.BiConsumer;
+import javax.swing.text.JTextComponent;
+
+class TextComponentFocusListener implements FocusListener {
+
+ private final AWSSignerController controller;
+ private final String propertyLoggingName;
+ private final BiConsumer updateFunction;
+ private Optional currentProfileOptional;
+ private String currentValue = "";
+
+ public TextComponentFocusListener(AWSSignerController controller, String propertyLoggingName, BiConsumer updateFunction) {
+ this.controller = controller;
+ this.propertyLoggingName = propertyLoggingName;
+ this.updateFunction = updateFunction;
+ }
+
+ @Override
+ public void focusGained(FocusEvent e) {
+ /*
+ * Save the current profile being updated.
+ * This is important because we can't just use the SELECTED profile when
+ * focus is lost. This fails if focus is lost by selecting a new profile.
+ * THAT other newly selected profile would be updated instead
+ */
+ currentProfileOptional = controller.getCurrentSelectedProfile();
+
+ //Also note the value when focus was gained. This helps us detected if the value actually changed or not when focus is lost
+ currentValue = ((JTextComponent) e.getComponent()).getText();
+
+ logDebug("Profile " + propertyLoggingName + " Text Field focus gained." + " Cause: " + e.getCause() + " ID:" + e.getID() + " Current value: " + ((JTextComponent) e.getComponent()).getText());
+ }
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ logDebug("Profile " + propertyLoggingName + " Text Field focus lost." + " Cause: " + e.getCause() + " ID:" + e.getID());
+ String currentText = ((JTextComponent) e.getComponent()).getText();
+ if (currentValue.equals(currentText)) {
+ logDebug("Current value has not changed. Not firing update with current value: " + currentValue);
+ } else {
+ currentValue = currentText;
+
+ //The value has changed. Let's check if we have a profile we're intending to update.
+ if (currentProfileOptional.isPresent()) {
+ Profile currentProfile = currentProfileOptional.get();
+ logInfo("Profile " + currentProfile.getName() + " " + propertyLoggingName + " text changed. New Value: " + currentText);
+ if (currentText == null || currentText.isBlank()) {
+ updateFunction.accept((T) currentProfile, null);
+ } else {
+ updateFunction.accept((T) currentProfile, currentText);
+ }
+ controller.updateProfileStatus();
+ } else {
+ logDebug("Profile " + propertyLoggingName + " focus lost, but no profile selected. Ignoring.");
+ }
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/AssumeRoleCredentialFetcher.java b/src/main/java/com/netspi/awssigner/credentials/AssumeRoleCredentialFetcher.java
new file mode 100644
index 0000000..106c815
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/AssumeRoleCredentialFetcher.java
@@ -0,0 +1,110 @@
+package com.netspi.awssigner.credentials;
+
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.Profile;
+import java.util.Optional;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
+import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
+import software.amazon.awssdk.services.sts.model.Credentials;
+
+public class AssumeRoleCredentialFetcher implements CredentialFetcher {
+
+ private final AssumeRoleProfile profile;
+
+ public AssumeRoleCredentialFetcher(AssumeRoleProfile profile) {
+ this.profile = profile;
+ }
+
+ @Override
+ public SigningCredentials getCredentials() throws SignerCredentialException {
+ final Optional roleArnOptional = profile.getRoleArn();
+ final Optional assumerProfileOptional = profile.getAssumerProfile();
+ if (assumerProfileOptional.isEmpty() && roleArnOptional.isEmpty()) {
+ throw new SignerCredentialException("Assumer profile and role ARN are not set for profile: " + profile.getName());
+ } else if (assumerProfileOptional.isEmpty()) {
+ throw new SignerCredentialException("Assumer profile is not set for profile: " + profile.getName());
+ } else if (roleArnOptional.isEmpty()) {
+ throw new SignerCredentialException("Role ARN is not set for profile: " + profile.getName());
+ }
+
+ try {
+ Profile parentProfile = assumerProfileOptional.get();
+ LogWriter.logDebug("Obtaining credentials to use when assuming role from parent assumer: " + parentProfile.getName());
+ SigningCredentials parentCredentials = parentProfile.getCredentials();
+ LogWriter.logDebug("Successfully obtained credentials from parent assumer: " + parentProfile.getName());
+
+ Region region = getRegion();
+ StsClient stsClient = StsClient.builder()
+ .credentialsProvider(new SigningCredentialConverter(parentCredentials))
+ .region(region)
+ .build();
+
+ final String roleARN = roleArnOptional.get();
+
+ AssumeRoleRequest.Builder requestBuilder = AssumeRoleRequest.builder().roleArn(roleARN);
+
+ final Optional durationSecondsOptional = profile.getDurationSeconds();
+ if (durationSecondsOptional.isPresent()) {
+ int duration = durationSecondsOptional.get();
+ //Bounds check
+ if (duration < 900) {
+ duration = 900;
+ } else if (duration > 43200) {
+ duration = 43200;
+ }
+ requestBuilder = requestBuilder.durationSeconds(duration);
+ }
+
+ final Optional externalIdOptional = profile.getExternalId();
+ if (externalIdOptional.isPresent()) {
+ requestBuilder = requestBuilder.externalId(externalIdOptional.get());
+ }
+
+ final Optional sessionNameOptional = profile.getSessionName();
+ if (sessionNameOptional.isPresent()) {
+ requestBuilder = requestBuilder.roleSessionName(sessionNameOptional.get());
+ } else {
+ //Required but not specified. Let's fall back to a default
+ requestBuilder = requestBuilder.roleSessionName("AWSSigner-" + System.currentTimeMillis());
+ }
+
+ final Optional sessionPolicyOptional = profile.getSessionPolicy();
+ if (sessionPolicyOptional.isPresent()) {
+ requestBuilder = requestBuilder.policy(sessionPolicyOptional.get());
+ }
+
+ LogWriter.logDebug("Attempting to assume role: " + roleARN);
+ AssumeRoleResponse assumeRole = stsClient.assumeRole(requestBuilder.build());
+ Credentials awsCredentials = assumeRole.credentials();
+ LogWriter.logInfo("Successfully assumed role: " + roleARN);
+
+ return new SigningCredentials(awsCredentials.accessKeyId(), awsCredentials.secretAccessKey(), awsCredentials.sessionToken());
+
+ } catch (SignerCredentialException ex) {
+ LogWriter.logError("Error while getting credentials for parent profile " + profile.getAssumerProfile().get().getName() + " for assume role: " + roleArnOptional.orElse("") + "\" resulting in error: " + ex.getMessage());
+ throw new SignerCredentialException("Unable to get parent credentials", ex);
+ } catch (RuntimeException ex) {
+ LogWriter.logError("Error while assume role: " + roleArnOptional.orElse("") + "\" resulting in error: " + ex.getMessage());
+ throw new SignerCredentialException("Unable to assume role", ex);
+ }
+
+ }
+
+ private Region getRegion() {
+ //Try to get a region from the profile itself, or default to us-east-1
+ String regionString = profile.getRegion().orElse("us-east-1").toLowerCase();
+
+ //Check if we matched an actual region
+ Region matchedRegion = Region.of(regionString);
+ if (matchedRegion != null) {
+ return matchedRegion;
+ } else {
+ //Didn't match a region. Default to us-east-1
+ return Region.US_EAST_1;
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/CommandCredentialFetcher.java b/src/main/java/com/netspi/awssigner/credentials/CommandCredentialFetcher.java
new file mode 100644
index 0000000..2a1e113
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/CommandCredentialFetcher.java
@@ -0,0 +1,83 @@
+package com.netspi.awssigner.credentials;
+
+import com.netspi.awssigner.log.LogWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import software.amazon.awssdk.utils.IoUtils;
+import software.amazon.awssdk.utils.Platform;
+
+public class CommandCredentialFetcher implements CredentialFetcher {
+
+ private final String profileName;
+ private final List command;
+
+ public CommandCredentialFetcher(String profileName, String command) {
+ List cmd = new ArrayList<>();
+
+ if (Platform.isWindows()) {
+ cmd.add("cmd.exe");
+ cmd.add("/C");
+ } else {
+ cmd.add("sh");
+ cmd.add("-c");
+ }
+
+ String builderCommand = Objects.requireNonNull(command);
+
+ cmd.add(builderCommand);
+
+ this.profileName = profileName;
+ this.command = Collections.unmodifiableList(cmd);
+ }
+
+ /**
+ * Execute the external process to retrieve credentials.
+ */
+ private String executeCommand() throws IOException, InterruptedException {
+ ProcessBuilder processBuilder = new ProcessBuilder(command);
+
+ ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();
+
+ Process process = processBuilder.start();
+ try {
+ IoUtils.copy(process.getInputStream(), commandOutput, 64000); //max 64KB output
+
+ process.waitFor();
+
+ if (process.exitValue() != 0) {
+ throw new IllegalStateException("Command from profile " + profileName + " returned non-zero exit value: " + process.exitValue());
+ }
+
+ return new String(commandOutput.toByteArray(), StandardCharsets.UTF_8);
+ } finally {
+ process.destroy();
+ }
+ }
+
+ @Override
+ public SigningCredentials getCredentials() throws SignerCredentialException {
+ try {
+ LogWriter.logDebug("Starting command execution for profile: " + profileName);
+ String output = executeCommand();
+ LogWriter.logDebug("Completed command execution for profile: " + profileName);
+ Optional parsedCreds = CredentialsParser.parseCredentialsFromText(output);
+ if (parsedCreds.isPresent()) {
+ LogWriter.logInfo("Successfully fetched credentials for profile" + profileName + " using command: " + command);
+ return parsedCreds.get();
+ } else {
+ LogWriter.logDebug("No credentials extracted from the following output: " + output);
+ throw new SignerCredentialException("No credentials extracted from command output");
+ }
+ } catch (InterruptedException | IOException | RuntimeException ex) {
+ LogWriter.logError("Error while executing command for profile: " + profileName + " with command: \"" + command + "\" resulting in error: " + ex.getMessage());
+ throw new SignerCredentialException(ex);
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/CredentialFetcher.java b/src/main/java/com/netspi/awssigner/credentials/CredentialFetcher.java
new file mode 100644
index 0000000..e484637
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/CredentialFetcher.java
@@ -0,0 +1,7 @@
+package com.netspi.awssigner.credentials;
+
+public interface CredentialFetcher {
+
+ SigningCredentials getCredentials() throws SignerCredentialException;
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/CredentialsParser.java b/src/main/java/com/netspi/awssigner/credentials/CredentialsParser.java
new file mode 100644
index 0000000..61b40eb
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/CredentialsParser.java
@@ -0,0 +1,37 @@
+package com.netspi.awssigner.credentials;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class CredentialsParser {
+
+ private static final Pattern ACCESS_KEY_PATTERN = Pattern.compile("(? parseCredentialsFromText(String textToBeParsed) {
+ Matcher accessKeyMatcher = ACCESS_KEY_PATTERN.matcher(textToBeParsed);
+ Matcher secretKeyMatcher = SECRET_KEY_PATTERN.matcher(textToBeParsed);
+ if (accessKeyMatcher.find() && secretKeyMatcher.find()) {
+ String accessKey = accessKeyMatcher.group();
+ String secretKey = secretKeyMatcher.group();
+ String sessionToken = null;
+
+ Matcher sessionTokenMatcher = SESSION_TOKEN_PATTERN.matcher(textToBeParsed);
+ if (sessionTokenMatcher.find()) {
+ sessionToken = sessionTokenMatcher.group();
+ }
+
+ return Optional.of(new SigningCredentials(accessKey, secretKey, sessionToken));
+ }
+ return Optional.empty();
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/ProfileCredentialTester.java b/src/main/java/com/netspi/awssigner/credentials/ProfileCredentialTester.java
new file mode 100644
index 0000000..7898e8b
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/ProfileCredentialTester.java
@@ -0,0 +1,34 @@
+package com.netspi.awssigner.credentials;
+
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.Profile;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.sts.StsClient;
+import software.amazon.awssdk.services.sts.model.GetCallerIdentityResponse;
+
+public class ProfileCredentialTester {
+
+ private final Profile profile;
+
+ public ProfileCredentialTester(Profile profile) {
+ this.profile = profile;
+ }
+
+ public SigningCredentials testProfile() throws SignerCredentialException {
+ if (!profile.requiredFieldsAreSet()) {
+ throw new IllegalStateException("Profile " + profile.getName() + " does not have all required fields set.");
+ }
+
+ //Get the credentials
+ SigningCredentials creds = profile.getCredentials();
+ Region region = Region.US_EAST_1;
+ StsClient stsClient = StsClient.builder()
+ .credentialsProvider(new SigningCredentialConverter(creds))
+ .region(region)
+ .build();
+ GetCallerIdentityResponse response = stsClient.getCallerIdentity();
+ LogWriter.logDebug("Successfully called GetCallerIdentity: " + response.toString());
+ return creds;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/SignerCredentialException.java b/src/main/java/com/netspi/awssigner/credentials/SignerCredentialException.java
new file mode 100644
index 0000000..dde768c
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/SignerCredentialException.java
@@ -0,0 +1,18 @@
+package com.netspi.awssigner.credentials;
+
+public class SignerCredentialException extends Exception {
+
+ public SignerCredentialException(String message) {
+ super(message);
+ }
+
+ public SignerCredentialException(Throwable cause){
+ super(cause);
+ }
+
+ public SignerCredentialException(String message, Throwable cause){
+ super(message, cause);
+ }
+
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/SigningCredentialConverter.java b/src/main/java/com/netspi/awssigner/credentials/SigningCredentialConverter.java
new file mode 100644
index 0000000..aeaefd6
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/SigningCredentialConverter.java
@@ -0,0 +1,30 @@
+package com.netspi.awssigner.credentials;
+
+import java.util.Optional;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
+
+/**
+ * Converts from our SigningCredentials type to SDK's AwsCredentials type
+ */
+public class SigningCredentialConverter implements AwsCredentialsProvider {
+
+ private final SigningCredentials inputCreds;
+
+ public SigningCredentialConverter(SigningCredentials creds) {
+ this.inputCreds = creds;
+ }
+
+ @Override
+ public AwsCredentials resolveCredentials() {
+ final Optional sessionToken = inputCreds.getSessionToken();
+ if(sessionToken.isEmpty()){
+ return AwsBasicCredentials.create(inputCreds.getAccessKey(), inputCreds.getSecretKey());
+ } else {
+ return AwsSessionCredentials.create(inputCreds.getAccessKey(), inputCreds.getSecretKey(), sessionToken.get());
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/credentials/SigningCredentials.java b/src/main/java/com/netspi/awssigner/credentials/SigningCredentials.java
new file mode 100644
index 0000000..8b5c784
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/credentials/SigningCredentials.java
@@ -0,0 +1,44 @@
+
+package com.netspi.awssigner.credentials;
+
+import java.util.Optional;
+
+
+public class SigningCredentials {
+
+ private final String accessKey;
+ private final String secretKey;
+ private final String sessionToken;
+
+ public SigningCredentials(String accessKey, String secretKey, String sessionToken) {
+ if(accessKey == null || accessKey.trim().isEmpty()){
+ throw new IllegalArgumentException("Access Key may not be null or blank");
+ }
+ this.accessKey = accessKey;
+
+ if(secretKey == null || secretKey.trim().isEmpty()){
+ throw new IllegalArgumentException("Secret Key may not be null or blank");
+ }
+ this.secretKey = secretKey;
+
+ this.sessionToken = sessionToken;
+
+ }
+
+ public String getAccessKey() {
+ return accessKey;
+ }
+
+ public String getSecretKey() {
+ return secretKey;
+ }
+
+ public Optional getSessionToken() {
+ if(sessionToken==null|| sessionToken.trim().isEmpty()){
+ return Optional.empty();
+ } else {
+ return Optional.of(sessionToken);
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/log/LogLevel.java b/src/main/java/com/netspi/awssigner/log/LogLevel.java
new file mode 100644
index 0000000..4ad3051
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/log/LogLevel.java
@@ -0,0 +1,15 @@
+package com.netspi.awssigner.log;
+
+public enum LogLevel {
+ ERROR(0), INFO(1), DEBUG(2);
+ private final int severity;
+
+ LogLevel(int severity) {
+ this.severity = severity;
+ }
+
+ public int getSeverity() {
+ return severity;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/log/LogWriter.java b/src/main/java/com/netspi/awssigner/log/LogWriter.java
new file mode 100644
index 0000000..43b670a
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/log/LogWriter.java
@@ -0,0 +1,52 @@
+package com.netspi.awssigner.log;
+
+import burp.BurpExtender;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+/*
+ * This isn't good OOP, but it's good enough for this use case. We don't need to
+ * pass around an instance to each object which gets messy.
+ */
+public class LogWriter {
+
+ private PrintWriter out = new PrintWriter(System.out, true);
+ private PrintWriter err = new PrintWriter(System.err, true);
+ private LogLevel logLevel = LogLevel.ERROR;
+
+ private static final LogWriter logWriter = new LogWriter();
+
+ private LogWriter() {
+ }
+
+ public synchronized static void configure(OutputStream outStream, OutputStream errStream) {
+ logWriter.out = new PrintWriter(outStream, true);
+ logWriter.out.println(BurpExtender.EXTENSION_NAME + " Logging Initialized");
+ logWriter.err = new PrintWriter(errStream, true);
+ }
+
+ public synchronized static void setLevel(LogLevel level) {
+ logWriter.logLevel = level;
+ }
+
+ public static LogLevel getLevel() {
+ return logWriter.logLevel;
+ }
+
+ public static void logDebug(final String message) {
+ if (logWriter.logLevel.getSeverity() >= LogLevel.DEBUG.getSeverity()) {
+ logWriter.out.println("[DEBUG] " + message);
+ }
+ }
+
+ public static void logInfo(final String message) {
+ if (logWriter.logLevel.getSeverity() >= LogLevel.INFO.getSeverity()) {
+ logWriter.out.println("[INFO] " + message);
+ }
+ }
+
+ public static void logError(final String message) {
+ logWriter.err.println("[ERROR] " + message);
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/main/TestRunner.java b/src/main/java/com/netspi/awssigner/main/TestRunner.java
new file mode 100644
index 0000000..d0248da
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/main/TestRunner.java
@@ -0,0 +1,37 @@
+package com.netspi.awssigner.main;
+
+import com.netspi.awssigner.controller.AWSSignerController;
+import com.netspi.awssigner.log.LogLevel;
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.AWSSignerConfiguration;
+import com.netspi.awssigner.view.BurpTabPanel;
+import java.awt.BorderLayout;
+import javax.swing.*;
+
+/*
+* This has no meaningful functionality, and it only displays the UI elements
+* without the elements actually working. For display purposes only.
+ */
+class TestRunner {
+
+ public static void main(String[] args) {
+
+ //Configure logging
+ LogWriter.setLevel(LogLevel.DEBUG);
+ //Create the view
+ BurpTabPanel view = new BurpTabPanel();
+ //Create the model
+ AWSSignerConfiguration model = new AWSSignerConfiguration();
+ //Create controller to keep them in sync
+ AWSSignerController controller = new AWSSignerController(view, model);
+
+ final JFrame frame = new JFrame();
+
+ frame.setLayout(new BorderLayout());
+
+ frame.add(view);
+ frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+ frame.setVisible(true);
+ frame.pack();
+ }
+}
diff --git a/src/main/java/com/netspi/awssigner/model/AWSSignerConfiguration.java b/src/main/java/com/netspi/awssigner/model/AWSSignerConfiguration.java
new file mode 100644
index 0000000..1bc036d
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/AWSSignerConfiguration.java
@@ -0,0 +1,29 @@
+package com.netspi.awssigner.model;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class AWSSignerConfiguration {
+ public volatile boolean isEnabled = true;
+ public volatile List profiles = new ArrayList<>();
+ public volatile Profile alwaysSignWithProfile;
+
+ public List getProfileNames() {
+ return profiles.stream().map(Profile::getName).collect(Collectors.toList());
+ }
+
+ /**
+ * Gets the profile, if it exists.
+ * @param name The name of the profile to get
+ * @return The profile, if it exists
+ */
+ public Optional getProfileForName(String name){
+ if(name == null || name.isEmpty()){
+ return Optional.empty();
+ }
+ return profiles.stream().filter(profile -> profile.getName().equals(name)).findFirst();
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/AbstractCachingProfile.java b/src/main/java/com/netspi/awssigner/model/AbstractCachingProfile.java
new file mode 100644
index 0000000..698de20
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/AbstractCachingProfile.java
@@ -0,0 +1,128 @@
+package com.netspi.awssigner.model;
+
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import com.netspi.awssigner.log.LogWriter;
+import java.util.Optional;
+
+public abstract class AbstractCachingProfile extends Profile {
+
+ /**
+ * Default lifetime of cached creds Using default value for assume role
+ * command
+ * https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html
+ */
+ private final static int DEFAULT_DURATION_SECONDS = 3600;
+
+ /**
+ * How long the cached credentials should be considered valid. A negative
+ * value indicates that the duration seconds value has not been set for this
+ * profile. If the value has not been set, the default value should be used
+ * for determining the lifetime of the cached creds If the value has been
+ * set, the value of durationSeconds should be used.
+ */
+ private volatile int durationSeconds = -1;
+
+ /*
+ * -1 means no creds have been cached and should be refetched
+ */
+ private volatile long expirationSeconds = -1;
+ private volatile SigningCredentials cachedCreds;
+
+ public AbstractCachingProfile(String name) {
+ super(name);
+ }
+
+ /**
+ * Empty Optional if no value has been set for the profile, otherwise the
+ * set value.
+ *
+ * @return Empty Optional if no value has been set for the profile,
+ * otherwise the set value.
+ */
+ public Optional getDurationSeconds() {
+ if (durationSeconds >= 0) {
+ return Optional.of(durationSeconds);
+ } else {
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Sets the duration (in seconds) for how long the cached credentials will
+ * be considered valid. A null or negative input value unsets the value for
+ * this profile and the default caching duration will be used. A non-null,
+ * non-negative value sets the new duration.
+ *
+ * @param durationSeconds null/negative if the value should be unset (and
+ * the default cache lifetime will be used will be used) or the value to be
+ * used.
+ */
+ public void setDurationSeconds(Integer durationSeconds) {
+ //Check for null/negative value
+ if (durationSeconds == null || durationSeconds < 0) {
+ this.durationSeconds = -1;
+ } else {
+ this.durationSeconds = durationSeconds;
+ }
+ clearCache();
+ }
+
+ /**
+ * Sets the duration (in seconds) for how long the cached credentials will
+ * be considered valid. A null or negative input value unsets the value for
+ * this profile and the default caching duration will be used. A non-null,
+ * non-negative value sets the new duration.
+ *
+ * @param durationSeconds null/negative if the value should be unset (and
+ * the default cache lifetime will be used will be used) or the value to be
+ * used.
+ */
+ public void setDurationSecondsFromText(String durationSeconds) {
+ if (durationSeconds == null) {
+ setDurationSeconds(null);
+ }
+ try {
+ int duration = Integer.parseInt(durationSeconds);
+ setDurationSeconds(duration);
+ } catch (NumberFormatException e) {
+ LogWriter.logDebug("Invalid input string provided for Profile Duration: " + durationSeconds + " using default of " + DEFAULT_DURATION_SECONDS + " seconds instead.");
+ setDurationSeconds(null);
+ }
+ }
+
+ @Override
+ public SigningCredentials getCredentials() throws SignerCredentialException {
+ if(durationSeconds==0){
+ LogWriter.logDebug("Duration set to zero. Fetching new credentials and not caching.");
+ return getCredentialsNoCache();
+ }
+
+ long seconds = expirationSeconds;
+ long now = System.currentTimeMillis() / 1000;
+ if (seconds == -1 || now - seconds >= 0) {
+ synchronized (this) {
+ if (seconds == expirationSeconds) { // recheck for lost race
+ LogWriter.logDebug("Cache expired. Fetching new creds");
+ cachedCreds = getCredentialsNoCache();
+ if (durationSeconds >= 0) {
+ seconds = now + durationSeconds;
+ } else {
+ seconds = now + DEFAULT_DURATION_SECONDS;
+ }
+ expirationSeconds = seconds;
+ }
+ }
+ }
+ LogWriter.logDebug("Returning previously cached creds.");
+ return cachedCreds;
+ }
+
+ protected void clearCache(){
+ LogWriter.logDebug("Clearing the cache.");
+ expirationSeconds = -1;
+ }
+
+ abstract protected SigningCredentials getCredentialsNoCache() throws SignerCredentialException ;
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/AssumeRoleProfile.java b/src/main/java/com/netspi/awssigner/model/AssumeRoleProfile.java
new file mode 100644
index 0000000..3d3e639
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/AssumeRoleProfile.java
@@ -0,0 +1,125 @@
+package com.netspi.awssigner.model;
+
+import com.netspi.awssigner.credentials.AssumeRoleCredentialFetcher;
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import java.util.Optional;
+
+public class AssumeRoleProfile extends AbstractCachingProfile {
+
+ private Profile assumerProfile;
+ private String roleArn;
+ private String sessionName;
+ private String externalId;
+ private String sessionPolicy;
+
+ public AssumeRoleProfile(String name) {
+ super(name);
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null Profile.
+ */
+ public Optional getAssumerProfile() {
+ return Optional.ofNullable(assumerProfile);
+ }
+
+ public void setAssumerProfile(Profile assumerProfile) {
+ this.assumerProfile = assumerProfile;
+ clearCache();
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getRoleArn() {
+ return Optional.ofNullable(roleArn);
+ }
+
+ public void setRoleArn(String roleArn) {
+ if (roleArn != null && roleArn.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.roleArn = null;
+ } else {
+ this.roleArn = roleArn;
+ }
+ clearCache();
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getSessionName() {
+ return Optional.ofNullable(sessionName);
+ }
+
+ public void setSessionName(String sessionName) {
+ if (sessionName != null && sessionName.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.sessionName = null;
+ } else {
+ this.sessionName = sessionName;
+ }
+ clearCache();
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getExternalId() {
+ return Optional.ofNullable(externalId);
+ }
+
+ public void setExternalId(String externalId) {
+ if (externalId != null && externalId.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.externalId = null;
+ } else {
+ this.externalId = externalId;
+ }
+ clearCache();
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getSessionPolicy() {
+ return Optional.ofNullable(sessionPolicy);
+ }
+
+ public void setSessionPolicy(String sessionPolicy) {
+ if (sessionPolicy != null && sessionPolicy.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.sessionPolicy = null;
+ } else {
+ this.sessionPolicy = sessionPolicy;
+ }
+ clearCache();
+ }
+
+ @Override
+ public boolean requiredFieldsAreSet() {
+ return roleArn != null && assumerProfile != null && !assumerProfile.getName().isEmpty();
+ }
+
+ @Override
+ protected SigningCredentials getCredentialsNoCache() throws SignerCredentialException {
+ if (assumerProfile == null && roleArn == null) {
+ throw new SignerCredentialException("Assumer profile and role ARN are not set for profile: " + getName());
+ } else if (assumerProfile == null) {
+ throw new SignerCredentialException("Assumer profile is not set for profile: " + getName());
+ } else if (roleArn == null) {
+ throw new SignerCredentialException("Role ARN is not set for profile: " + getName());
+ }
+ AssumeRoleCredentialFetcher fetcher = new AssumeRoleCredentialFetcher(this);
+ return fetcher.getCredentials();
+ }
+
+
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/CommandProfile.java b/src/main/java/com/netspi/awssigner/model/CommandProfile.java
new file mode 100644
index 0000000..f74f325
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/CommandProfile.java
@@ -0,0 +1,48 @@
+package com.netspi.awssigner.model;
+
+import com.netspi.awssigner.credentials.CommandCredentialFetcher;
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import java.util.Optional;
+
+public class CommandProfile extends AbstractCachingProfile {
+
+ private String command;
+
+ public CommandProfile(String name) {
+ super(name);
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getCommand() {
+ return Optional.ofNullable(command);
+ }
+
+ public void setCommand(String command) {
+ if (command != null && command.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.command = null;
+ } else {
+ this.command = command;
+ }
+ clearCache();
+ }
+
+ @Override
+ public boolean requiredFieldsAreSet() {
+ return command != null;
+ }
+
+ @Override
+ protected SigningCredentials getCredentialsNoCache() throws SignerCredentialException {
+ if (command == null) {
+ throw new SignerCredentialException("Command is not set for profile: " + getName());
+ }
+
+ return new CommandCredentialFetcher(name, command).getCredentials();
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/Profile.java b/src/main/java/com/netspi/awssigner/model/Profile.java
new file mode 100644
index 0000000..2e4a0a7
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/Profile.java
@@ -0,0 +1,143 @@
+package com.netspi.awssigner.model;
+
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import java.util.Objects;
+import java.util.Optional;
+
+public abstract class Profile {
+
+ protected String name;
+ protected boolean isEnabled = true;
+ protected boolean inScopeOnly = false;
+ protected String region = null;
+ protected String service = null;
+ protected String keyId = null;
+
+ public Profile(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new IllegalArgumentException("The Profile name may not be null or blank.");
+ }
+ this.name = name;
+ }
+
+ /**
+ * Must be set, will not be null or blank.
+ */
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ if (name == null || name.trim().isEmpty()) {
+ throw new IllegalArgumentException("The Profile name may not be null or blank.");
+ }
+ this.name = name;
+ }
+
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ public void setEnabled(boolean isEnabled) {
+ this.isEnabled = isEnabled;
+ }
+
+ public boolean isInScopeOnly() {
+ return inScopeOnly;
+ }
+
+ public void setInScopeOnly(boolean inScopeOnly) {
+ this.inScopeOnly = inScopeOnly;
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getRegion() {
+ return Optional.ofNullable(region);
+ }
+
+ public void setRegion(String region) {
+ if (region != null && region.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.region = null;
+ } else {
+ this.region = region;
+ }
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getService() {
+ return Optional.ofNullable(service);
+ }
+
+ public void setService(String service) {
+ if (service != null && service.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.service = null;
+ } else {
+ this.service = service;
+ }
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getKeyId() {
+ return Optional.ofNullable(keyId);
+ }
+
+ public void setKeyId(String keyId) {
+ if (keyId != null && keyId.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.keyId = null;
+ } else {
+ this.keyId = keyId;
+ }
+ }
+
+ /**
+ * Returns true if the required fields for the profile are set but does not
+ * confirm if those set values are themselves valid.
+ *
+ * @return true if the profile's required fields are set, false otherwise.
+ */
+ public abstract boolean requiredFieldsAreSet();
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(this.name);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final Profile other = (Profile) obj;
+ if (!Objects.equals(this.name, other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return this.getClass().getSimpleName() + "{" + "name=" + name + ", isEnabled=" + isEnabled + ", inScopeOnly=" + inScopeOnly + ", region=" + region + ", service=" + service + ", keyId=" + keyId + '}';
+ }
+
+ public abstract SigningCredentials getCredentials() throws SignerCredentialException;
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/StaticCredentialsProfile.java b/src/main/java/com/netspi/awssigner/model/StaticCredentialsProfile.java
new file mode 100644
index 0000000..77634c6
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/StaticCredentialsProfile.java
@@ -0,0 +1,86 @@
+package com.netspi.awssigner.model;
+
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import java.util.Optional;
+
+public class StaticCredentialsProfile extends Profile {
+
+ private String accessKey = null;
+ private String secretKey = null;
+ private String sessionToken = null;
+
+ public StaticCredentialsProfile(String name) {
+ super(name);
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getAccessKey() {
+ return Optional.ofNullable(accessKey);
+ }
+
+ public void setAccessKey(String accessKey) {
+ if (accessKey != null && accessKey.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.accessKey = null;
+ } else {
+ this.accessKey = accessKey;
+ }
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getSecretKey() {
+ return Optional.ofNullable(secretKey);
+ }
+
+ public void setSecretKey(String secretKey) {
+ if (secretKey != null && secretKey.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.secretKey = null;
+ } else {
+ this.secretKey = secretKey;
+ }
+ }
+
+ /**
+ * If unset, this will return an empty optional, but it should never be an
+ * empty/null string.
+ */
+ public Optional getSessionToken() {
+ return Optional.ofNullable(sessionToken);
+ }
+
+ public void setSessionToken(String sessionToken) {
+ if (sessionToken != null && sessionToken.trim().isEmpty()) {
+ //Treat a blank input as null to indicate it's unset.
+ this.sessionToken = null;
+ } else {
+ this.sessionToken = sessionToken;
+ }
+ }
+
+ @Override
+ public boolean requiredFieldsAreSet() {
+ return accessKey != null && secretKey != null;
+ }
+
+ @Override
+ public SigningCredentials getCredentials() throws SignerCredentialException {
+ if (accessKey == null && secretKey == null) {
+ throw new SignerCredentialException("Access key and secret key are not set for profile: " + getName());
+ } else if (accessKey == null) {
+ throw new SignerCredentialException("Access key is not set for profile: " + getName());
+ } else if (secretKey == null) {
+ throw new SignerCredentialException("Secret key is not set for profile: " + getName());
+ }
+
+ return new SigningCredentials(accessKey, secretKey, sessionToken);
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/AutoProfileImporter.java b/src/main/java/com/netspi/awssigner/model/persistence/AutoProfileImporter.java
new file mode 100644
index 0000000..1343aaf
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/AutoProfileImporter.java
@@ -0,0 +1,80 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.model.Profile;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+public class AutoProfileImporter implements ProfileImporter{
+
+
+ //Profiles could be defined in many default locations. Check each and keep those that exist.
+ private List getDefaultProfilePaths() {
+ List profileFilePaths = new ArrayList<>();
+
+ //AWS_CONFIG_FILE environment variable
+ String envConfigFile = System.getenv("AWS_SHARED_CREDENTIALS_FILE");
+ if (envConfigFile != null) {
+ Path envPath = Paths.get(envConfigFile);
+ if (Files.exists(envPath)) {
+ profileFilePaths.add(envPath);
+ }
+ }
+
+ //~/.aws/config
+ Path configPath = Paths.get(System.getProperty("user.home"), ".aws", "config");
+ if (Files.exists(configPath)) {
+ profileFilePaths.add(configPath);
+ }
+
+ //AWS_SHARED_CREDENTIALS_FILE environment variable
+ String envCredsFile = System.getenv("AWS_SHARED_CREDENTIALS_FILE");
+ if (envCredsFile != null) {
+ Path envPath = Paths.get(envCredsFile);
+ if (Files.exists(envPath)) {
+ profileFilePaths.add(envPath);
+ }
+ }
+
+ //~/.aws/credentials
+ Path credsPath = Paths.get(System.getProperty("user.home"), ".aws", "credentials");
+ if (Files.exists(credsPath)) {
+ profileFilePaths.add(credsPath);
+ }
+
+ return profileFilePaths;
+ }
+
+ public List importProfiles() {
+ //This basically steals logic from the different importer types
+
+ //Import from default files
+ List defaultPaths = getDefaultProfilePaths();
+ List filePersistentProfiles = new ArrayList<>();
+ for (Path path : defaultPaths) {
+ FileProfileImporter fileProfileImporter = new FileProfileImporter(path);
+ List parseProfilesFromPath = fileProfileImporter.parseProfilesFromPath(path);
+ for (PersistedProfile persistedProfile : parseProfilesFromPath) {
+ fileProfileImporter.mergePersistedProfile(filePersistentProfiles, persistedProfile.name, persistedProfile.keyValuePairs);
+ }
+ }
+ List profiles = FileProfileImporter.parseAndConvertProfiles(filePersistentProfiles);
+
+ EnvironmentVariableProfileImporter envProfileImporter = new EnvironmentVariableProfileImporter();
+ List envProfiles = envProfileImporter.importProfiles();
+ profiles.addAll(envProfiles);
+
+ ClipboardProfileImporter clipboardProfileImporter = new ClipboardProfileImporter();
+ List clipboard = clipboardProfileImporter.importProfiles();
+ profiles.addAll(clipboard);
+ return profiles;
+ }
+
+
+
+
+}
+
+
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/ClipboardProfileImporter.java b/src/main/java/com/netspi/awssigner/model/persistence/ClipboardProfileImporter.java
new file mode 100644
index 0000000..2179a43
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/ClipboardProfileImporter.java
@@ -0,0 +1,51 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.credentials.CredentialsParser;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.awt.Toolkit;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public class ClipboardProfileImporter implements ProfileImporter {
+
+ @Override
+ public List importProfiles() {
+ String clipboardText = "";
+ try {
+ //Gets the current clipboard text as a string
+ clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
+ //This shouldn't happen, but a safeguard just in case.
+ if (clipboardText == null) {
+ clipboardText = "";
+ }
+ } catch (UnsupportedFlavorException | IOException ex) {
+ LogWriter.logError("Unable to obtain clipboard text. Exception: " + ex.toString());
+ }
+
+ List profiles = new ArrayList<>(1);
+
+ //Parse the clipboard text
+ Optional results = CredentialsParser.parseCredentialsFromText(clipboardText);
+
+ //Did it work?
+ if (results.isPresent()) {
+ //Build a profile
+ SigningCredentials creds = results.get();
+ StaticCredentialsProfile profile = new StaticCredentialsProfile("clipboard");
+ profile.setAccessKey(creds.getAccessKey());
+ profile.setSecretKey(creds.getSecretKey());
+ profile.setSessionToken(creds.getSessionToken().orElse(null));
+ profiles.add(profile);
+ }
+
+ return profiles;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/EnvironmentVariableProfileImporter.java b/src/main/java/com/netspi/awssigner/model/persistence/EnvironmentVariableProfileImporter.java
new file mode 100644
index 0000000..80c0d1f
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/EnvironmentVariableProfileImporter.java
@@ -0,0 +1,41 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+public class EnvironmentVariableProfileImporter implements ProfileImporter {
+
+ @Override
+ public List importProfiles() {
+ List profiles = new ArrayList<>(1);
+
+ //ignore case for keys
+ Map env = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ //Add all the current environment variables
+ env.putAll(System.getenv());
+
+ //Pull out environment variables
+ String accessKey = env.get("AWS_ACCESS_KEY_ID");
+ String secretKey = env.get("AWS_SECRET_ACCESS_KEY");
+ String sessionToken = env.get("AWS_SESSION_TOKEN");
+
+ //Check if we have the required 2
+ if (accessKey != null && !accessKey.isEmpty() && secretKey != null && !secretKey.isEmpty()) {
+ StaticCredentialsProfile profile = new StaticCredentialsProfile("environment_variables");
+ profile.setAccessKey(accessKey);
+ profile.setSecretKey(secretKey);
+ //Check if we have a session token too
+ if (sessionToken != null && !sessionToken.isEmpty()) {
+ profile.setSessionToken(sessionToken);
+ }
+ profiles.add(profile);
+ }
+
+ return profiles;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/FileProfileImporter.java b/src/main/java/com/netspi/awssigner/model/persistence/FileProfileImporter.java
new file mode 100644
index 0000000..a3bc97e
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/FileProfileImporter.java
@@ -0,0 +1,229 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import static com.netspi.awssigner.model.persistence.ProfileFileKeyConstants.*;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+import java.util.stream.Collectors;
+
+public class FileProfileImporter implements ProfileImporter {
+
+ private static final Pattern awsProfileStartPattern = Pattern.compile("\\s*\\[(?:profile\\s)?(\\S+)\\]\\s*", Pattern.CASE_INSENSITIVE);
+ private static final int PROFILE_NAME_GROUP = 1;
+ private static final Pattern awsProfileKVPattern = Pattern.compile("\\s*([\\S\\=]+)\\s*=\\s*(.+)\\s*", Pattern.CASE_INSENSITIVE);
+ private static final int KEY_GROUP = 1;
+ private static final int VALUE_GROUP = 2;
+ private final Path inputPath;
+
+ public FileProfileImporter(Path inputPath) {
+ this.inputPath = inputPath;
+ }
+
+ @Override
+ public List importProfiles() {
+ //Read all the profiles available in the input file. These are basically raw KV pairs.
+ List parsedProfiles = parseProfilesFromPath(inputPath);
+ return parseAndConvertProfiles(parsedProfiles);
+
+ }
+
+ static List parseAndConvertProfiles(List parsedProfiles) {
+ List profiles = new ArrayList<>();
+ //The following section needs to convert the parsed profiles into real Profiles.
+ //For StaticCreds and Command profiles, this is easy one-to-one mapping.
+ //For AssumeRole profile, we need to reference the previously imported source profile which really makes this more complex
+ //Let's start by importing all the simple ones (Static and Command)
+ for (Iterator iterator = parsedProfiles.iterator(); iterator.hasNext();) {
+ PersistedProfile parsedProfile = iterator.next();
+ final Map keyValuePairs = parsedProfile.keyValuePairs;
+
+ //Need to identify which type of profile we have.
+ if (keyValuePairs.containsKey(STATIC_CREDS_ACCESS_KEY_KEY) && keyValuePairs.containsKey(STATIC_CREDS_SECRET_KEY_KEY)) {
+ //We have minimum requirements for StaticCreds profile
+ StaticCredentialsProfile staticCredsProfile = new StaticCredentialsProfile(parsedProfile.name);
+ String accessKey = keyValuePairs.get(STATIC_CREDS_ACCESS_KEY_KEY);
+ staticCredsProfile.setAccessKey(accessKey);
+
+ String secretKey = keyValuePairs.get(STATIC_CREDS_SECRET_KEY_KEY);
+ staticCredsProfile.setSecretKey(secretKey);
+
+ String sessionToken = keyValuePairs.get(STATIC_CREDS_SESSION_TOKEN_KEY);
+ staticCredsProfile.setSessionToken(sessionToken);
+
+ addGenericProfileVales(staticCredsProfile, keyValuePairs);
+
+ //add to profiles list and remove from parsed profiles
+ profiles.add(staticCredsProfile);
+ iterator.remove();
+
+ } else if (keyValuePairs.containsKey(COMMAND_COMMAND_KEY)) {
+ //We have minimum requirements for Command profile
+ CommandProfile commandProfile = new CommandProfile(parsedProfile.name);
+ String command = keyValuePairs.get(COMMAND_COMMAND_KEY);
+ commandProfile.setCommand(command);
+
+ String durationString = keyValuePairs.get(DURATION_SECONDS_KEY);
+ commandProfile.setDurationSecondsFromText(durationString);
+
+ addGenericProfileVales(commandProfile, keyValuePairs);
+
+ //add to profiles list and remove from parsed profiles
+ profiles.add(commandProfile);
+ iterator.remove();
+ }
+ //if it didn't meet those, ignore and loop
+ }
+
+ //Now that we have the simple ones, the ones remaining are either AssumeRole profiles (or a profile we can't properly import)
+ //We need to keep attempting to parse assume role profiles until we stop making progress.
+ int processedProfiles;
+ do {
+ processedProfiles = 0;
+ for (Iterator iterator = parsedProfiles.iterator(); iterator.hasNext();) {
+ PersistedProfile parsedProfile = iterator.next();
+ final Map keyValuePairs = parsedProfile.keyValuePairs;
+ if (keyValuePairs.containsKey(ASSUME_ROLE_ROLE_ARN_KEY) && keyValuePairs.containsKey(ASSUME_ROLE_ASSUMER_PROFILE_NAME_KEY)) {
+ //We have minimum requirements for AssumeRole profile
+
+ //Check if we've already parsed its source profile
+ String sourceProfileName = keyValuePairs.get(ASSUME_ROLE_ASSUMER_PROFILE_NAME_KEY);
+ Optional sourceProfileOptional = profiles.stream().filter(profile -> {
+ return profile.getName().equals(sourceProfileName);
+ }).findAny();
+ if (sourceProfileOptional.isEmpty()) {
+ //We haven't found the source yet. Ignore this parsed profile and continue
+ continue;
+ }
+
+ AssumeRoleProfile assumeRoleProfile = new AssumeRoleProfile(parsedProfile.name);
+ assumeRoleProfile.setAssumerProfile(sourceProfileOptional.get());
+
+ String roleARN = keyValuePairs.get(ASSUME_ROLE_ROLE_ARN_KEY);
+ assumeRoleProfile.setRoleArn(roleARN);
+
+ String durationString = keyValuePairs.get(DURATION_SECONDS_KEY);
+ assumeRoleProfile.setDurationSecondsFromText(durationString);
+
+ String externalId = keyValuePairs.get(ASSUME_ROLE_EXTERNAL_ID_KEY);
+ assumeRoleProfile.setExternalId(externalId);
+
+ String roleSessionName = keyValuePairs.get(ASSUME_ROLE_SESSION_NAME_KEY);
+ assumeRoleProfile.setSessionName(roleSessionName);
+
+ String roleSessionPolicy = keyValuePairs.get(ASSUME_ROLE_SESSION_POLICY_KEY);
+ assumeRoleProfile.setSessionPolicy(roleSessionPolicy);
+
+ addGenericProfileVales(assumeRoleProfile, keyValuePairs);
+
+ //add to profiles list and remove from parsed profiles
+ profiles.add(assumeRoleProfile);
+ iterator.remove();
+ processedProfiles++;
+ }
+ }
+ } while (!parsedProfiles.isEmpty() && processedProfiles > 0);
+
+ //We're all done. Let's output a warning if there's any remaining.
+ if (!parsedProfiles.isEmpty()) {
+ //Get a list of profile names we couldn't parse
+ List unparsableNames = parsedProfiles.stream().map(profile -> profile.name).collect(Collectors.toList());
+ LogWriter.logError("Unable to parse the following profiles: " + unparsableNames);
+ }
+
+ return profiles;
+ }
+
+ //We're collecting all ParsedProfiles from the given input file
+ //The input file is assumed to be in the AWS config/creds file format
+ List parseProfilesFromPath(Path inputPath) {
+ List profiles = new ArrayList<>();
+
+ //This is goofy, this should be cleaned up.
+ try ( Stream lineStream = Files.lines(inputPath)) {
+ String profileName = null;
+ HashMap keyValuePairs = new HashMap<>();
+
+ for (Iterator iterator = lineStream.iterator(); iterator.hasNext();) {
+ String line = iterator.next();
+ //Check if it's the start of a profile definition
+ Matcher profileStartMatcher = awsProfileStartPattern.matcher(line);
+ if (profileStartMatcher.matches()) {
+ //This is the start of a new profile
+
+ //Check if we've already found a profile name
+ if (profileName != null) {
+ //This must be the start of another profile.
+ mergePersistedProfile(profiles, profileName, keyValuePairs);
+ }
+ //Capture the profile name
+ profileName = profileStartMatcher.group(PROFILE_NAME_GROUP);
+ //clear previous key values
+ keyValuePairs = new HashMap<>();
+ }
+
+ //Didn't match a profile start. Is it a key-value pair?
+ Matcher kvMatcher = awsProfileKVPattern.matcher(line);
+ if (kvMatcher.matches()) {
+ //Add it to our map of key-value pairs
+ keyValuePairs.put(kvMatcher.group(KEY_GROUP), kvMatcher.group(VALUE_GROUP));
+ }
+ }
+
+ //This should be the end of the file. Save any profile that was in being parsed
+ if (profileName != null) {
+ //This must be the start of another profile.
+ mergePersistedProfile(profiles, profileName, keyValuePairs);
+ }
+ } catch (IOException err) {
+ LogWriter.logError("Unable to load profiles from path: " + inputPath.toString() + " . Error: " + err.toString());
+ }
+ return profiles;
+ }
+
+ void mergePersistedProfile(List profiles, String profileName, Map keyValuePairs) {
+ //Check our growing list of parsed profiles to see if we have already found one with the same name.
+ Optional existingProfileOptional = profiles.stream().filter(profile -> {
+ return profile.name.equals(profileName);
+ }).findAny();
+
+ if (existingProfileOptional.isPresent()) {
+ //Since we have previously found a profile with the same name. Merge these
+ PersistedProfile existingProfile = existingProfileOptional.get();
+ existingProfile.keyValuePairs.putAll(keyValuePairs);
+ } else {
+ //Build and save the previous profile.
+ profiles.add(new PersistedProfile(profileName, keyValuePairs));
+ }
+ }
+
+ private static void addGenericProfileVales(Profile profile, Map keyValuePairs) {
+ //special handling for the boolean values (if present)
+ if(keyValuePairs.containsKey(PROFILE_ENABLED_KEY)){
+ String enabledStringValue = keyValuePairs.get(PROFILE_ENABLED_KEY);
+ profile.setEnabled(Boolean.parseBoolean(enabledStringValue));
+ }
+ if(keyValuePairs.containsKey(PROFILE_IN_SCOPE_ONLY_KEY)){
+ String inScopeOnlyStringValue = keyValuePairs.get(PROFILE_IN_SCOPE_ONLY_KEY);
+ profile.setInScopeOnly(Boolean.parseBoolean(inScopeOnlyStringValue));
+ }
+
+ profile.setService(keyValuePairs.get(PROFILE_SERVICE_KEY));
+ profile.setRegion(keyValuePairs.get(PROFILE_REGION_KEY));
+ profile.setKeyId(keyValuePairs.get(PROFILE_KEY_ID_KEY));
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/PersistedProfile.java b/src/main/java/com/netspi/awssigner/model/persistence/PersistedProfile.java
new file mode 100644
index 0000000..c64e4f6
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/PersistedProfile.java
@@ -0,0 +1,20 @@
+package com.netspi.awssigner.model.persistence;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+class PersistedProfile {
+
+ String name;
+ Map keyValuePairs;
+
+ PersistedProfile(String name, Map keyValuePairs) {
+ this.name = name;
+
+ //ignore case for keys
+ this.keyValuePairs = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ this.keyValuePairs.putAll(keyValuePairs);
+ }
+
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/ProfileExporter.java b/src/main/java/com/netspi/awssigner/model/persistence/ProfileExporter.java
new file mode 100644
index 0000000..eee2766
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/ProfileExporter.java
@@ -0,0 +1,149 @@
+package com.netspi.awssigner.model.persistence;
+
+import static com.netspi.awssigner.log.LogWriter.logError;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import static com.netspi.awssigner.model.persistence.ProfileFileKeyConstants.*;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class ProfileExporter {
+
+
+ private final Path exportPath;
+
+ public ProfileExporter(Path exportPath) {
+ this.exportPath = exportPath;
+ }
+
+ public void exportProfiles(List profiles) throws IOException {
+ List iniProfiles = profiles.stream()
+ .map(this::toINI)
+ .filter(iniString -> {
+ return iniString != null && !iniString.trim().isEmpty();
+ })
+ .collect(Collectors.toList());
+
+ Files.write(exportPath, iniProfiles, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
+ }
+
+ private String toINI(Profile profile) {
+ if (profile == null || !profile.requiredFieldsAreSet()) {
+ return "";
+ }
+
+ String profileFields = getProfileFields(profile);
+
+ //Handle type-specific status transformation
+ if (profile instanceof StaticCredentialsProfile) {
+ return profileFields+getStaticCredsFields((StaticCredentialsProfile) profile);
+ } else if (profile instanceof AssumeRoleProfile) {
+ return profileFields+getAssumeRoleFields((AssumeRoleProfile) profile);
+ } else if (profile instanceof CommandProfile) {
+ return profileFields+getCommandFields((CommandProfile) profile);
+ } else {
+ final String errorMessage = "Profile does not match expected type. Found Type: " + profile.getClass().getName();
+ logError(errorMessage);
+ return "";
+ }
+ }
+
+ private String getProfileFields(Profile profile) {
+ //Start the profile output
+ String result = "[profile " + profile.getName() + "]" + System.lineSeparator();
+
+ //Output required fields
+ result += requiredKeyValueBoolean(PROFILE_ENABLED_KEY, profile.isEnabled());
+ result += requiredKeyValueBoolean(PROFILE_IN_SCOPE_ONLY_KEY, profile.isInScopeOnly());
+
+
+ //Output optional generic Profile fields
+ result += optionalKeyValueString(PROFILE_KEY_ID_KEY, profile.getKeyId());
+ result += optionalKeyValueString(PROFILE_REGION_KEY, profile.getRegion());
+ result += optionalKeyValueString(PROFILE_SERVICE_KEY, profile.getService());
+ return result;
+ }
+
+
+ private String getStaticCredsFields(StaticCredentialsProfile profile) {
+ String result = "";
+
+ //Check if we have the minimum requirements
+ if (profile.requiredFieldsAreSet()) {
+ //Output type-specific required fields
+ result += requiredKeyValueString(STATIC_CREDS_ACCESS_KEY_KEY, profile.getAccessKey());
+ result += requiredKeyValueString(STATIC_CREDS_SECRET_KEY_KEY, profile.getSecretKey());
+
+ //Output type-specific optional fields
+ result += optionalKeyValueString(STATIC_CREDS_SESSION_TOKEN_KEY, profile.getSessionToken());
+ }
+
+ return result;
+ }
+
+
+ private String getAssumeRoleFields(AssumeRoleProfile profile) {
+ String result = "";
+
+ //Check if we have the minimum requirements
+ if (profile.requiredFieldsAreSet()) {
+ //Output type-specific required fields
+ result += requiredKeyValueString(ASSUME_ROLE_ROLE_ARN_KEY, profile.getRoleArn());
+ result += requiredKeyValueString(ASSUME_ROLE_ASSUMER_PROFILE_NAME_KEY, Optional.of(profile.getAssumerProfile().get().getName()));
+
+ //Output type-specific optional fields
+ result += optionalKeyValueString(DURATION_SECONDS_KEY, profile.getDurationSeconds());
+ result += optionalKeyValueString(ASSUME_ROLE_EXTERNAL_ID_KEY, profile.getExternalId());
+ result += optionalKeyValueString(ASSUME_ROLE_SESSION_NAME_KEY, profile.getSessionName());
+ if(profile.getSessionPolicy().isPresent()){
+ String sessionPolicy = profile.getSessionPolicy().get();
+ //output must be a single line. Strip line breaks
+ sessionPolicy = sessionPolicy.replace("\n", "").replace("\r", "").trim();
+ result += optionalKeyValueString(ASSUME_ROLE_SESSION_POLICY_KEY, Optional.of(sessionPolicy));
+ }
+ }
+
+ return result;
+ }
+
+
+ private String getCommandFields(CommandProfile profile) {
+ String result = "";
+
+ //Check if we have the minimum requirements
+ if (profile.requiredFieldsAreSet()) {
+ //Output type-specific required fields
+ result += requiredKeyValueString(COMMAND_COMMAND_KEY, profile.getCommand());
+
+ //Output type-specific optional fields
+ result += optionalKeyValueString(DURATION_SECONDS_KEY, profile.getDurationSeconds());
+ }
+
+ return result;
+ }
+
+
+ private String requiredKeyValueBoolean(String key, boolean value) {
+ return key + "=" + Boolean.toString(value) + System.lineSeparator();
+ }
+
+ private String requiredKeyValueString(String key, Optional value) {
+ return key + "=" + value.get().toString() + System.lineSeparator();
+ }
+
+ private String optionalKeyValueString(String key, Optional value) {
+ if (value.isPresent()) {
+ return key + "=" + value.get().toString() + System.lineSeparator();
+ } else {
+ return "";
+ }
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/ProfileFileKeyConstants.java b/src/main/java/com/netspi/awssigner/model/persistence/ProfileFileKeyConstants.java
new file mode 100644
index 0000000..68f6dd5
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/ProfileFileKeyConstants.java
@@ -0,0 +1,43 @@
+package com.netspi.awssigner.model.persistence;
+
+class ProfileFileKeyConstants {
+
+ /*
+ * Keys with this prefix are not standard AWS CLI keys
+ */
+ static final String CUSTOM_KEY_PREFIX = "signer_";
+
+ //profile required keys
+ static final String PROFILE_ENABLED_KEY = CUSTOM_KEY_PREFIX + "enabled";
+ static final String PROFILE_IN_SCOPE_ONLY_KEY = CUSTOM_KEY_PREFIX + "in_scope_only";
+
+ //profile optional keys
+ static final String PROFILE_SERVICE_KEY = CUSTOM_KEY_PREFIX + "service";
+ /*
+ * Note: we intentionally have a custom value for region rather than the default
+ * AWS "region" key. The "region" key is nice on the CLI for specifying a default
+ * region. But in the Signer it is really annoying to import a profile with
+ * default region "us-west-2" and then try to send a request to a "us-east-1"
+ * endpoint but it fails because it was signed with "us-west-2"
+ */
+ static final String PROFILE_REGION_KEY = CUSTOM_KEY_PREFIX + "region";
+ static final String PROFILE_KEY_ID_KEY = CUSTOM_KEY_PREFIX + "key_id";
+
+ //static creds keys
+ static final String STATIC_CREDS_ACCESS_KEY_KEY = "aws_access_key_id";
+ static final String STATIC_CREDS_SECRET_KEY_KEY = "aws_secret_access_key";
+ static final String STATIC_CREDS_SESSION_TOKEN_KEY = "aws_session_token";
+
+ //Shared duration key
+ static final String DURATION_SECONDS_KEY = "duration_seconds";
+
+ //assume role keys
+ static final String ASSUME_ROLE_ROLE_ARN_KEY = "role_arn";
+ static final String ASSUME_ROLE_ASSUMER_PROFILE_NAME_KEY = "source_profile";
+ static final String ASSUME_ROLE_EXTERNAL_ID_KEY = "external_id";
+ static final String ASSUME_ROLE_SESSION_NAME_KEY = "role_session_name";
+ static final String ASSUME_ROLE_SESSION_POLICY_KEY = CUSTOM_KEY_PREFIX + "session_policy";
+
+ //command keys
+ static final String COMMAND_COMMAND_KEY = "credential_process";
+}
diff --git a/src/main/java/com/netspi/awssigner/model/persistence/ProfileImporter.java b/src/main/java/com/netspi/awssigner/model/persistence/ProfileImporter.java
new file mode 100644
index 0000000..bed8d50
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/model/persistence/ProfileImporter.java
@@ -0,0 +1,8 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.model.Profile;
+import java.util.List;
+
+public interface ProfileImporter {
+ public List importProfiles();
+}
diff --git a/src/main/java/com/netspi/awssigner/signing/AwsRequestSigner.java b/src/main/java/com/netspi/awssigner/signing/AwsRequestSigner.java
new file mode 100644
index 0000000..f67153e
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/signing/AwsRequestSigner.java
@@ -0,0 +1,10 @@
+package com.netspi.awssigner.signing;
+
+import burp.IHttpRequestResponse;
+import burp.IRequestInfo;
+
+public interface AwsRequestSigner {
+
+ public byte[] sign(IHttpRequestResponse messageInfo, IRequestInfo request, ParsedAuthHeader authHeader) throws SigningException;
+
+}
diff --git a/src/main/java/burp/Utility.java b/src/main/java/com/netspi/awssigner/signing/ClassicAwsRequestSigner.java
similarity index 70%
rename from src/main/java/burp/Utility.java
rename to src/main/java/com/netspi/awssigner/signing/ClassicAwsRequestSigner.java
index 0e5730a..95ba434 100644
--- a/src/main/java/burp/Utility.java
+++ b/src/main/java/com/netspi/awssigner/signing/ClassicAwsRequestSigner.java
@@ -1,299 +1,348 @@
-package burp;
-
-import com.google.common.base.Strings;
-import com.google.common.hash.Hashing;
-
-import javax.crypto.Mac;
-import javax.crypto.spec.SecretKeySpec;
-import javax.xml.bind.DatatypeConverter;
-import java.io.PrintWriter;
-import java.net.URI;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.Pattern;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import java.util.regex.Matcher;
-
-class Utility {
-
- static byte[] signRequest(IHttpRequestResponse messageInfo,
- IExtensionHelpers helpers,
- String service,
- String region,
- String accessKey,
- String secretKey,
- String token,
- PrintWriter pw) throws Exception {
- IRequestInfo requestInfo = helpers.analyzeRequest(messageInfo);
- List headers = requestInfo.getHeaders();
- if (!token.isEmpty()) {
- boolean tokenExists = false;
- int i = 0;
- for (String header : headers) {
- if (header.toLowerCase().startsWith("x-amz-security-token")) {
- headers.set(i, "X-Amz-Security-Token: " + token);
- tokenExists = true;
- }
- i++;
- }
- if (!tokenExists)
- headers.add("X-Amz-Security-Token: " + token);
- }
- List newHeaders = new ArrayList<>(headers);
- headers.remove(0);
-
- Map headerMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
-
- String authHeader = "";
- String amzDate = "";
-
- for (String header : headers) {
- if (header.toLowerCase().startsWith("authorization:")){
- authHeader = header;
- }
- if (header.toLowerCase().startsWith("x-amz-date:")){
- amzDate = header;
- }
-
- String[] headerPair = header.split(":",2);
- headerMap.put(headerPair[0].trim(),headerPair[1].trim());
- }
-
- headers.remove(authHeader);
- headers.remove(amzDate);
- newHeaders.remove(authHeader);
- newHeaders.remove(amzDate);
-
- SimpleDateFormat amz = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
- amz.setTimeZone(TimeZone.getTimeZone("UTC"));
- String amzdate = amz.format(new Date());
-
- SimpleDateFormat dateStamp = new SimpleDateFormat("yyyyMMdd");
- dateStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
- String dateStampString = dateStamp.format(new Date());
-
- headerMap.put("x-amz-date",amzdate);
-
- String signedHeaders = getSignedHeaders(headerMap.get("authorization"));
- if (!token.isEmpty() && !signedHeaders.contains("x-amz-security-token")) {
- signedHeaders = signedHeaders + ";x-amz-security-token";
- }
-
- String[] signedHeaderArray = signedHeaders.split(";");
-
- List signedHeaderList = Arrays.asList(signedHeaderArray);
-
- Collections.sort(signedHeaderList);
-
- StringBuilder canonicalHeaders = new StringBuilder();
-
- for (String signedHeader : signedHeaderList) {
- if (headerMap.containsKey(signedHeader)) {
- canonicalHeaders.append(signedHeader.toLowerCase()).append(':').append(headerMap.get(signedHeader)).append('\n');
- } else {
- pw.println("Warning: SignedHeader '" + signedHeader + "' does not exist in request headers.");
- }
- }
- String signedHeadersSorted = String.join(";", signedHeaderList);
- //pw.println(canonicalHeaders.toString());
- byte[] request = messageInfo.getRequest();
- String body = "";
- String notUnicode = "[^\\u0000-\\u007F]+";
- String payloadHash;
-
- if (!requestInfo.getMethod().equals("GET") || requestInfo.getBodyOffset() > 0){
-
- int bodyOffset = requestInfo.getBodyOffset();
- body = hexToString(bytesToHex(Arrays.copyOfRange(request, bodyOffset, request.length)));
- if(!body.matches(notUnicode)) {
- char[] chars = body.toCharArray();
- String sanitize = "";
- for (char aChar : chars) {
- String test = Character.toString(aChar);
- if (Pattern.matches(notUnicode, test)) {
- sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
- } else {
- sanitize = sanitize.concat(test);
- }
- }
- body = sanitize;
- }
- pw.println(Base64.getEncoder().encodeToString(body.getBytes("utf-8")));
- payloadHash = Hashing.sha256().hashString(body, StandardCharsets.UTF_8).toString().toLowerCase();
-
- } else {
- payloadHash = Hashing.sha256().hashString("", StandardCharsets.UTF_8).toString().toLowerCase();
- }
-
- String canonicalUri = requestInfo.getUrl().getPath();
- if(!canonicalUri.matches(notUnicode)) {
- char[] chars = canonicalUri.toCharArray();
- String sanitize = "";
- for (char aChar : chars) {
- String test = Character.toString(aChar);
- if (Pattern.matches(notUnicode, test)) {
- sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
- } else {
- sanitize = sanitize.concat(test);
- }
- }
- canonicalUri = sanitize;
- }
- //pw.println(canonicalUri);
- URI uri = new URI(canonicalUri);
- uri = uri.normalize();
- String path = uri.getPath();
- if(canonicalUri.contains("%")) {
- path = uri.getRawPath();
- }
- String[] segments = path.split("/");
- String[] encodedSegments = new String[segments.length];
- for (int i=0; i 1) {
- sorted[i] = String.join("=", param);
- } else if (param.length == 1 && !param[0].isEmpty()){
- sorted[i] = param[0] + "=";
- }
- }
- canonicalQueryString = String.join("&", sorted);
-
- String[] cleanup = canonicalQueryString.split("");
- for (int i = 0; i < cleanup.length; ++i) {
- if (cleanup[i].equals("%")) {
- cleanup[i+1] = cleanup[i+1].toUpperCase();
- cleanup[i+2] = cleanup[i+2].toUpperCase();
- }
- }
- canonicalQueryString = String.join("", cleanup);
- //pw.println(canonicalQueryString);
- //canonicalQueryString = canonicalQueryString.replace(":","%3A").replace("/","%2F").replace(" ", "%20");
-
- String canonicalRequest = requestInfo.getMethod() + '\n' + encodedCanonicalUri + '\n' + canonicalQueryString + '\n' +
- canonicalHeaders +'\n' + signedHeadersSorted + '\n' + payloadHash;
- String credScope = dateStampString + '/' + region + '/' + service + '/' + "aws4_request";
- String algorithm = "AWS4-HMAC-SHA256";
-
- String stringToSign = algorithm + '\n' + amzdate + '\n' + credScope + '\n' + Hashing.sha256().hashString(canonicalRequest, StandardCharsets.UTF_8).toString().toLowerCase();
- //pw.println(canonicalRequest);
- //pw.println(stringToSign);
- byte[] signingKey = getSignatureKey(secretKey, dateStampString, region, service);
-
- String signature = DatatypeConverter.printHexBinary(HmacSHA256(stringToSign, signingKey));
-
- newHeaders.add("Authorization: " + algorithm + ' ' + "Credential=" + accessKey + '/' + credScope + ", " + "SignedHeaders=" +
- signedHeadersSorted + ", " + "Signature=" + signature.toLowerCase());
- newHeaders.add("X-Amz-Date: " + amzdate);
- if(!newHeaders.get(0).matches(notUnicode)) {
- char[] chars = newHeaders.get(0).toCharArray();
- String sanitize = "";
- for (char aChar : chars) {
- String test = Character.toString(aChar);
- if (Pattern.matches(notUnicode, test)) {
- sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
- } else {
- sanitize = sanitize.concat(test);
- }
- }
- newHeaders.set(0, sanitize);
- }
-
- return helpers.buildHttpMessage(newHeaders, body.getBytes());
- }
-
- private static byte[] HmacSHA256(String data, byte[] key) throws Exception {
- String algorithm="HmacSHA256";
- Mac mac = Mac.getInstance(algorithm);
- mac.init(new SecretKeySpec(key, algorithm));
- return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
- }
-
- private static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
- byte[] kSecret = ("AWS4" + key).getBytes(StandardCharsets.UTF_8);
- byte[] kDate = HmacSHA256(dateStamp, kSecret);
- byte[] kRegion = HmacSHA256(regionName, kDate);
- byte[] kService = HmacSHA256(serviceName, kRegion);
- return HmacSHA256("aws4_request", kService);
- }
-
- private static String getSignedHeaders(String authHeader){
-
- String signedHeaders = "";
-
- Pattern pattern = Pattern.compile("SignedHeaders=(.*?)[,\\s]");
-
- Matcher matcher = pattern.matcher(authHeader);
- if (matcher.find()){
- signedHeaders = matcher.group(1);
- }
-
- return signedHeaders;
-
- }
- private static String bytesToHex(byte[] bytes) {
- char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
- char[] hexChars = new char[bytes.length * 2];
- for (int j = 0; j < bytes.length; j++) {
- int v = bytes[j] & 0xFF;
- hexChars[j * 2] = HEX_ARRAY[v >>> 4];
- hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
- }
- return new String(hexChars);
- }
- private static String hexToString(String hex){
- StringBuilder sb = new StringBuilder();
- for( int i=0; i new SigningException("Region missing from Authorization header. Is this a SigV4a request? Can't sign with classic signer")));
+
+ try {
+ return callV1Signing(messageInfo, helpers, service, region, accessKey, secretKey, token);
+ } catch (Exception ex) {
+ final String errorMessage = "Unable to sign request with profile " + profile + " using V1 signing algorithm. Error: " + ex.getMessage();
+ LogWriter.logError(errorMessage);
+ throw new SigningException(errorMessage, ex);
+ }
+ }
+
+ //As much as possible, copy-pasting from V1
+ private byte[] callV1Signing(IHttpRequestResponse messageInfo,
+ IExtensionHelpers helpers,
+ String service,
+ String region,
+ String accessKey,
+ String secretKey,
+ String token) throws Exception {
+ IRequestInfo requestInfo = helpers.analyzeRequest(messageInfo);
+ List headers = requestInfo.getHeaders();
+ if (!token.isEmpty()) {
+ boolean tokenExists = false;
+ int i = 0;
+ for (String header : headers) {
+ if (header.toLowerCase().startsWith("x-amz-security-token")) {
+ headers.set(i, "X-Amz-Security-Token: " + token);
+ tokenExists = true;
+ }
+ i++;
+ }
+ if (!tokenExists)
+ headers.add("X-Amz-Security-Token: " + token);
+ }
+ List newHeaders = new ArrayList<>(headers);
+ headers.remove(0);
+
+ Map headerMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+
+ String authHeader = "";
+ String amzDate = "";
+
+ for (String header : headers) {
+ if (header.toLowerCase().startsWith("authorization:")){
+ authHeader = header;
+ }
+ if (header.toLowerCase().startsWith("x-amz-date:")){
+ amzDate = header;
+ }
+
+ String[] headerPair = header.split(":",2);
+ headerMap.put(headerPair[0].trim(),headerPair[1].trim());
+ }
+
+ headers.remove(authHeader);
+ headers.remove(amzDate);
+ newHeaders.remove(authHeader);
+ newHeaders.remove(amzDate);
+
+ SimpleDateFormat amz = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
+ amz.setTimeZone(TimeZone.getTimeZone("UTC"));
+ String amzdate = amz.format(new Date());
+
+ SimpleDateFormat dateStamp = new SimpleDateFormat("yyyyMMdd");
+ dateStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
+ String dateStampString = dateStamp.format(new Date());
+
+ headerMap.put("x-amz-date",amzdate);
+
+ String signedHeaders = getSignedHeaders(headerMap.get("authorization"));
+ if (!token.isEmpty() && !signedHeaders.contains("x-amz-security-token")) {
+ signedHeaders = signedHeaders + ";x-amz-security-token";
+ }
+
+ String[] signedHeaderArray = signedHeaders.split(";");
+
+ List signedHeaderList = Arrays.asList(signedHeaderArray);
+
+ Collections.sort(signedHeaderList);
+
+ StringBuilder canonicalHeaders = new StringBuilder();
+
+ for (String signedHeader : signedHeaderList) {
+ if (headerMap.containsKey(signedHeader)) {
+ canonicalHeaders.append(signedHeader.toLowerCase()).append(':').append(headerMap.get(signedHeader)).append('\n');
+ } else {
+ LogWriter.logInfo("Warning: SignedHeader '" + signedHeader + "' does not exist in request headers.");
+ }
+ }
+ String signedHeadersSorted = String.join(";", signedHeaderList);
+ LogWriter.logDebug(canonicalHeaders.toString());
+ byte[] request = messageInfo.getRequest();
+ String body = "";
+ String notUnicode = "[^\\u0000-\\u007F]+";
+ String payloadHash;
+
+ if (!requestInfo.getMethod().equals("GET") || requestInfo.getBodyOffset() > 0){
+
+ int bodyOffset = requestInfo.getBodyOffset();
+ body = hexToString(bytesToHex(Arrays.copyOfRange(request, bodyOffset, request.length)));
+ if(!body.matches(notUnicode)) {
+ char[] chars = body.toCharArray();
+ String sanitize = "";
+ for (char aChar : chars) {
+ String test = Character.toString(aChar);
+ if (Pattern.matches(notUnicode, test)) {
+ sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
+ } else {
+ sanitize = sanitize.concat(test);
+ }
+ }
+ body = sanitize;
+ }
+ LogWriter.logDebug(Base64.getEncoder().encodeToString(body.getBytes("utf-8")));
+ payloadHash = Hashing.sha256().hashString(body, StandardCharsets.UTF_8).toString().toLowerCase();
+
+ } else {
+ payloadHash = Hashing.sha256().hashString("", StandardCharsets.UTF_8).toString().toLowerCase();
+ }
+
+ String canonicalUri = requestInfo.getUrl().getPath();
+ if(!canonicalUri.matches(notUnicode)) {
+ char[] chars = canonicalUri.toCharArray();
+ String sanitize = "";
+ for (char aChar : chars) {
+ String test = Character.toString(aChar);
+ if (Pattern.matches(notUnicode, test)) {
+ sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
+ } else {
+ sanitize = sanitize.concat(test);
+ }
+ }
+ canonicalUri = sanitize;
+ }
+ LogWriter.logDebug(canonicalUri);
+ URI uri = new URI(canonicalUri);
+ uri = uri.normalize();
+ String path = uri.getPath();
+ if(canonicalUri.contains("%")) {
+ path = uri.getRawPath();
+ }
+ String[] segments = path.split("/");
+ String[] encodedSegments = new String[segments.length];
+ for (int i=0; i 1) {
+ sorted[i] = String.join("=", param);
+ } else if (param.length == 1 && !param[0].isEmpty()){
+ sorted[i] = param[0] + "=";
+ }
+ }
+ canonicalQueryString = String.join("&", sorted);
+
+ String[] cleanup = canonicalQueryString.split("");
+ for (int i = 0; i < cleanup.length; ++i) {
+ if (cleanup[i].equals("%")) {
+ cleanup[i+1] = cleanup[i+1].toUpperCase();
+ cleanup[i+2] = cleanup[i+2].toUpperCase();
+ }
+ }
+ canonicalQueryString = String.join("", cleanup);
+ LogWriter.logDebug(canonicalQueryString);
+ //canonicalQueryString = canonicalQueryString.replace(":","%3A").replace("/","%2F").replace(" ", "%20");
+
+ String canonicalRequest = requestInfo.getMethod() + '\n' + encodedCanonicalUri + '\n' + canonicalQueryString + '\n' +
+ canonicalHeaders +'\n' + signedHeadersSorted + '\n' + payloadHash;
+ String credScope = dateStampString + '/' + region + '/' + service + '/' + "aws4_request";
+ String algorithm = "AWS4-HMAC-SHA256";
+
+ String stringToSign = algorithm + '\n' + amzdate + '\n' + credScope + '\n' + Hashing.sha256().hashString(canonicalRequest, StandardCharsets.UTF_8).toString().toLowerCase();
+ LogWriter.logDebug(canonicalRequest);
+ LogWriter.logDebug(stringToSign);
+ byte[] signingKey = getSignatureKey(secretKey, dateStampString, region, service);
+
+ String signature = bytesToHex(HmacSHA256(stringToSign, signingKey));
+
+ newHeaders.add("Authorization: " + algorithm + ' ' + "Credential=" + accessKey + '/' + credScope + ", " + "SignedHeaders=" +
+ signedHeadersSorted + ", " + "Signature=" + signature.toLowerCase());
+ newHeaders.add("X-Amz-Date: " + amzdate);
+ if(!newHeaders.get(0).matches(notUnicode)) {
+ char[] chars = newHeaders.get(0).toCharArray();
+ String sanitize = "";
+ for (char aChar : chars) {
+ String test = Character.toString(aChar);
+ if (Pattern.matches(notUnicode, test)) {
+ sanitize = sanitize.concat(URLEncoder.encode(test, StandardCharsets.UTF_8.toString()));
+ } else {
+ sanitize = sanitize.concat(test);
+ }
+ }
+ newHeaders.set(0, sanitize);
+ }
+
+ return helpers.buildHttpMessage(newHeaders, body.getBytes());
+ }
+
+ private byte[] HmacSHA256(String data, byte[] key) throws Exception {
+ String algorithm = "HmacSHA256";
+ Mac mac = Mac.getInstance(algorithm);
+ mac.init(new SecretKeySpec(key, algorithm));
+ return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
+ byte[] kSecret = ("AWS4" + key).getBytes(StandardCharsets.UTF_8);
+ byte[] kDate = HmacSHA256(dateStamp, kSecret);
+ byte[] kRegion = HmacSHA256(regionName, kDate);
+ byte[] kService = HmacSHA256(serviceName, kRegion);
+ return HmacSHA256("aws4_request", kService);
+ }
+
+ private String getSignedHeaders(String authHeader) {
+
+ String signedHeaders = "";
+
+ Pattern pattern = Pattern.compile("SignedHeaders=(.*?)[,\\s]");
+
+ Matcher matcher = pattern.matcher(authHeader);
+ if (matcher.find()) {
+ signedHeaders = matcher.group(1);
+ }
+
+ return signedHeaders;
+
+ }
+
+ private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
+ private String bytesToHex(byte[] data) {
+ StringBuilder r = new StringBuilder(data.length * 2);
+ for (byte b : data) {
+ r.append(hexCode[(b >> 4) & 0xF]);
+ r.append(hexCode[(b & 0xF)]);
+ }
+ return r.toString();
+ }
+
+ private String hexToString(String hex) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < hex.length() - 1; i += 2) {
+ String output = hex.substring(i, (i + 2));
+ int decimal = Integer.parseInt(output, 16);
+ sb.append((char) decimal);
+ }
+ return sb.toString();
+ }
+
+
+}
diff --git a/src/main/java/com/netspi/awssigner/signing/DelegatingAwsRequestSigner.java b/src/main/java/com/netspi/awssigner/signing/DelegatingAwsRequestSigner.java
new file mode 100644
index 0000000..41ae7f0
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/signing/DelegatingAwsRequestSigner.java
@@ -0,0 +1,280 @@
+package com.netspi.awssigner.signing;
+
+import burp.IExtensionHelpers;
+import burp.IHttpRequestResponse;
+import burp.IRequestInfo;
+import com.netspi.awssigner.credentials.SignerCredentialException;
+import com.netspi.awssigner.credentials.SigningCredentialConverter;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.Profile;
+import java.io.ByteArrayInputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.signer.Aws4Signer;
+import software.amazon.awssdk.auth.signer.AwsS3V4Signer;
+import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
+import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
+import software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner;
+import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
+import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
+import software.amazon.awssdk.core.signer.Signer;
+import software.amazon.awssdk.http.SdkHttpFullRequest;
+import software.amazon.awssdk.http.SdkHttpMethod;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.regions.internal.util.RegionScope;
+
+/**
+ * Passes off request signing responsibility to the AWS SDK.
+ */
+public class DelegatingAwsRequestSigner implements AwsRequestSigner {
+
+ private final IExtensionHelpers helpers;
+ private final Profile profile;
+
+ public DelegatingAwsRequestSigner(IExtensionHelpers helpers, Profile profile) {
+ this.helpers = helpers;
+ this.profile = profile;
+ }
+
+ @Override
+ public byte[] sign(IHttpRequestResponse messageInfo, IRequestInfo request, ParsedAuthHeader authHeader) throws SigningException {
+ //Get the credentials for signing
+ SigningCredentials credentials;
+ try {
+ credentials = profile.getCredentials();
+ } catch (SignerCredentialException ex) {
+ final String errorMessage = "Unable to fetch credentials for profile " + profile + " when attempting to sign. Error: " + ex.getMessage();
+ LogWriter.logError(errorMessage);
+ throw new SigningException(errorMessage, ex);
+ }
+
+ //May be set in profile, fall back to parsed auth header
+ String service = profile.getService().orElse(authHeader.getService());
+
+ //Get the fulll request as bytes
+ byte[] originalRequestBytes = messageInfo.getRequest();
+
+ //Pull out the bytes of the body
+ final byte[] body = Arrays.copyOfRange(originalRequestBytes, request.getBodyOffset(), originalRequestBytes.length);
+
+ //Get all the headers
+ List allHeaders = request.getHeaders();
+ LogWriter.logDebug("All headers in request: " + allHeaders);
+ //First line is HTTP request line (GET / ...). Take it out
+ final String originalRequestLine = allHeaders.remove(0);
+
+ //Split the signed headers in the auth header into individual headers.
+ String signedHeadersString = authHeader.getSignedHeaders();
+ LogWriter.logDebug("Signed Headers extracted from Authorization header: " + signedHeadersString);
+ Set originalSignedHeaderSet = Arrays.stream(signedHeadersString.split(";"))
+ .map(String::toLowerCase)
+ .collect(Collectors.toSet());
+ LogWriter.logDebug("Signed Headers extracted from Authorization header, after splitting: " + originalSignedHeaderSet);
+
+ //For each signed header, we need get the corresponding value(s) in our request.
+ Map> signedHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ for (final String signedHeader : originalSignedHeaderSet) {
+ List headerValues = allHeaders.stream().filter(header -> {
+ //Check if this line matches the signed header
+ return header.toLowerCase().startsWith(signedHeader + ":");
+ }).map(header -> {
+ //Only keep the header's value.
+ //We know from the filter that there is a colon character, so this is safe.
+ return header.split(":", 2)[1];
+ }).collect(Collectors.toList());
+ LogWriter.logDebug("For header \"" + signedHeader + "\" found the following values: " + headerValues);
+ signedHeaderMap.put(signedHeader, headerValues);
+ }
+ LogWriter.logDebug("signedHeaderMap: " + signedHeaderMap);
+
+ // build request object for signing
+ URI uri;
+ try {
+ uri = request.getUrl().toURI();
+ } catch (URISyntaxException ex) {
+ final String errorMessage = "Bad Request URL. Not valid syntax. Error: " + ex.getMessage();
+ LogWriter.logError(errorMessage);
+ throw new SigningException(errorMessage, ex);
+ }
+
+ // Need to remove these headers for the SDK
+ signedHeaderMap.remove("x-amz-security-token");
+ signedHeaderMap.remove("x-amz-date");
+ signedHeaderMap.remove("host");
+ //Check if this is an S3 request.
+ if (service.equalsIgnoreCase("s3")) {
+ //Also remove this header
+ signedHeaderMap.remove("x-amz-content-sha256");
+ }
+ LogWriter.logDebug("signedHeaderMap after removals for SDK: " + signedHeaderMap);
+
+ SdkHttpFullRequest signedRequest;
+ try {
+ final SdkHttpFullRequest awsRequest = SdkHttpFullRequest.builder()
+ .headers(signedHeaderMap)
+ .uri(uri)
+ .method(SdkHttpMethod.fromValue(request.getMethod()))
+ .contentStreamProvider(() -> new ByteArrayInputStream(body)).build();
+
+ //Convert signing creds to AWS type
+ AwsCredentials awsCredentials = new SigningCredentialConverter(credentials).resolveCredentials();
+
+ //Check if the headers include a "X-Amz-Region-Set" header value
+ Optional xAmzRegionSetHeaderValue = allHeaders.stream().filter(headerLine -> {
+ return headerLine.toLowerCase().startsWith("x-amz-region-set:");
+ })
+ .map(header -> {
+ //Only keep the header's value.
+ //We know from the filter that there is a colon character, so this is safe.
+ return header.split(":", 2)[1];
+ }).findFirst();
+
+ //We want to find the right region for our request
+ //May be set in the profile, fall back to parsed auth header, then fall back to X-Amz-Region-Set header.
+ //If it's not set any of those places... don't know what to do.
+ String region = profile.getRegion().orElse(authHeader.getRegion().orElse(xAmzRegionSetHeaderValue.orElse(null)));
+
+ //Get the metadata for signing
+ ExecutionAttributes executionAttributes = new ExecutionAttributes();
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, awsCredentials);
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, service);
+ LogWriter.logDebug("Adding service (" + AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME + ") attribute: " + service);
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of(region));
+ LogWriter.logDebug("Adding region (" + AwsSignerExecutionAttribute.SIGNING_REGION + ") attribute: " + Region.of(region));
+
+ //We'll now create the appropriate signer
+ Signer signer;
+
+ //Check if this is an S3 request. They get special handling
+ if (service.equalsIgnoreCase("s3")) {
+ LogWriter.logDebug("Handling S3-specific signature.");
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, false);
+ executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
+ if (authHeader.getAlgorithm() == SigningAlgorithm.SIGV4A) {
+ LogWriter.logDebug("Handling S3-specific SigV4a signature.");
+ if (region.equals("*")) {
+ LogWriter.logDebug("Handling region * with SigV4A");
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, RegionScope.GLOBAL);
+ LogWriter.logDebug("Adding region scope (" + AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE + ") attribute: " + RegionScope.GLOBAL);
+ }
+ signer = AwsCrtS3V4aSigner.create();
+ } else {
+ LogWriter.logDebug("Handling S3-specific SigV4 signature.");
+ signer = AwsS3V4Signer.create();
+ }
+
+ } else {
+ LogWriter.logDebug("Handling non-S3 signature.");
+ executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, true);
+ if (authHeader.getAlgorithm() == SigningAlgorithm.SIGV4A) {
+ LogWriter.logDebug("Handling non-S3 SigV4a signature.");
+ signer = AwsCrtV4aSigner.create();
+ } else {
+ LogWriter.logDebug("Handling non-S3 SigV4 signature.");
+ signer = Aws4Signer.create();
+ }
+ }
+ LogWriter.logDebug("Execution attributes: " + executionAttributes.getAttributes());
+ signedRequest = signer.sign(awsRequest, executionAttributes);
+
+ } catch (RuntimeException ex) {
+ final String errorMessage = "Unable to sign request with AWS SDK. Error: " + ex.getMessage();
+ LogWriter.logError(errorMessage);
+ throw new SigningException(errorMessage, ex);
+ }
+ LogWriter.logDebug("Successfully signed request with AWS signer.");
+
+ //Rebuild the final headers
+ List finalHeaders = new ArrayList<>(allHeaders);
+ final Map> postSignedHeaders = signedRequest.headers();
+ LogWriter.logDebug("Signed headers after signing: " + postSignedHeaders);
+
+ //Merge back in the signed headers with updated values
+ for (final String signedHeader : postSignedHeaders.keySet()) {
+ List signedValues = postSignedHeaders.get(signedHeader);
+ //Iterate through the list of headers, searching for a match for the signed header.
+ //Track the value in case there are multiple values so we know which to pick.
+ for (int i = 0, valueCount = 0; i < finalHeaders.size(); i++) {
+ String finalHeaderLine = finalHeaders.get(i);
+ if (finalHeaderLine.toLowerCase().startsWith(signedHeader.toLowerCase() + ":")) {
+ String[] parts = finalHeaderLine.split(":", 2);
+ finalHeaders.set(i, parts[0] + ": " + signedValues.get(valueCount));
+ valueCount++;
+ }
+ }
+ }
+ LogWriter.logDebug("All request headers after merging in signed headers: " + finalHeaders);
+
+ //Special handling for Content-MD5
+ for (int i = 0; i < finalHeaders.size(); i++) {
+ String finalHeader = finalHeaders.get(i);
+ if (finalHeader.toLowerCase().startsWith("Content-MD5".toLowerCase() + ":")) {
+ //Found Content-MD5 header. Update it.
+ try {
+ final byte[] bodyMD5 = MessageDigest.getInstance("MD5").digest(body);
+ final String updatedContentMD5 = helpers.base64Encode(bodyMD5);
+ finalHeaders.set(i, "Content-MD5: " + updatedContentMD5);
+ LogWriter.logDebug("Updated Content-MD5 header");
+ } catch (NoSuchAlgorithmException e) {
+ LogWriter.logError("Platform does not support MD5. Cannot update Content-MD5 header");
+ }
+ }
+ }
+
+ //Check if the credentials have a session token
+ if (credentials.getSessionToken().isPresent()) {
+ boolean foundHeader = false;
+ for (int i = 0; i < finalHeaders.size(); i++) {
+ String header = finalHeaders.get(i);
+ //Check if this header is already the session token header
+ if (header.toLowerCase().startsWith("x-amz-security-token:")) {
+ finalHeaders.set(i, "X-Amz-Security-Token: " + credentials.getSessionToken().get());
+ foundHeader = true;
+ LogWriter.logDebug("Replaced " + header + " in request with profile's session token.");
+ }
+ }
+ if(!foundHeader){
+ finalHeaders.add("X-Amz-Security-Token: " + credentials.getSessionToken().get());
+ LogWriter.logDebug("Added X-Amz-Security-Token to request with profile's session token.");
+ }
+ } else {
+ for (Iterator iterator = finalHeaders.iterator(); iterator.hasNext();) {
+ String header = iterator.next();
+ if (header.toLowerCase().startsWith("x-amz-security-token:")) {
+ iterator.remove();
+ LogWriter.logDebug("Removed " + header + " from request because it was signed with credentials which have a session token.");
+ }
+ }
+ }
+
+
+ LogWriter.logDebug("Final Headers: " + finalHeaders);
+
+ //Handle the first request line
+ //We actually want to rebuild this from the signed request because it would have handled URL encoding for us if necessary.
+ String methodString = signedRequest.method().toString();
+ URI signedUri = signedRequest.getUri();
+ String signedPath = signedUri.getRawPath();
+ String signedQuery = signedUri.getRawQuery() == null ? "" : "?" + signedUri.getRawQuery();
+ String httpProtocolPart = originalRequestLine.substring(originalRequestLine.lastIndexOf(" ") + 1);
+ String newRequestLine = methodString + " " + signedPath + signedQuery + " " + httpProtocolPart;
+ finalHeaders.add(0, newRequestLine);
+
+ //Build it and send it back
+ return helpers.buildHttpMessage(finalHeaders, body);
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/signing/ParsedAuthHeader.java b/src/main/java/com/netspi/awssigner/signing/ParsedAuthHeader.java
new file mode 100644
index 0000000..c313ceb
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/signing/ParsedAuthHeader.java
@@ -0,0 +1,151 @@
+package com.netspi.awssigner.signing;
+
+import com.netspi.awssigner.log.LogWriter;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ParsedAuthHeader {
+
+ private static final String AUTH_HEADER_PATTERN_ALGORITHM_GROUP = "algorithm";
+ private static final String AUTH_HEADER_PATTERN_ACCESS_KEY_GROUP = "accessKeyId";
+ private static final String AUTH_HEADER_PATTERN_DATE_GROUP = "date";
+ private static final String AUTH_HEADER_PATTERN_REGION_GROUP = "region";
+ private static final String AUTH_HEADER_PATTERN_SERVICE_GROUP = "service";
+ private static final String AUTH_HEADER_PATTERN_SIGNED_HEADERS_GROUP = "signedheaders";
+ private static final String AUTH_HEADER_PATTERN_SIGNATURE_GROUP = "signature";
+ private static final Pattern AUTH_HEADER_PATTERN = Pattern.compile("Authorization:\\s*(?<" + AUTH_HEADER_PATTERN_ALGORITHM_GROUP + ">AWS4-(?:HMAC|ECDSA-P256)-SHA256)\\s*Credential=(?<" + AUTH_HEADER_PATTERN_ACCESS_KEY_GROUP + ">[\\w-]{1,128})\\/(?<" + AUTH_HEADER_PATTERN_DATE_GROUP + ">\\d{8})\\/(?:(?<" + AUTH_HEADER_PATTERN_REGION_GROUP + ">[\\w-]{0,64})\\/)?(?<" + AUTH_HEADER_PATTERN_SERVICE_GROUP + ">\\S{0,128})\\/aws4_request,?\\s+SignedHeaders=(?<" + AUTH_HEADER_PATTERN_SIGNED_HEADERS_GROUP + ">\\S+),\\s+Signature=(?<" + AUTH_HEADER_PATTERN_SIGNATURE_GROUP + ">[a-fA-F\\d]{1,256})", Pattern.CASE_INSENSITIVE);
+
+ private final SigningAlgorithm algorithm;
+ private final String accessKey;
+ private final String date;
+ private final Optional region;
+ private final String service;
+ private final String signedheaders;
+ private final String signature;
+
+ public ParsedAuthHeader(SigningAlgorithm algorithm, String accessKey, String date, String region, String service, String signedheaders, String signature) {
+ this.algorithm = algorithm;
+ this.accessKey = accessKey;
+ this.date = date;
+ this.region = Optional.ofNullable(region);
+ this.service = service;
+ this.signedheaders = signedheaders;
+ this.signature = signature;
+
+ }
+
+ public SigningAlgorithm getAlgorithm() {
+ return algorithm;
+ }
+
+ public String getAccessKey() {
+ return accessKey;
+ }
+
+ public String getDate() {
+ return date;
+ }
+
+ public Optional getRegion() {
+ return region;
+ }
+
+ public String getService() {
+ return service;
+ }
+
+ public String getSignedHeaders() {
+ return signedheaders;
+ }
+
+ public String getSignature() {
+ return signature;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ hash = 37 * hash + Objects.hashCode(this.algorithm);
+ hash = 37 * hash + Objects.hashCode(this.accessKey);
+ hash = 37 * hash + Objects.hashCode(this.date);
+ hash = 37 * hash + Objects.hashCode(this.region);
+ hash = 37 * hash + Objects.hashCode(this.service);
+ hash = 37 * hash + Objects.hashCode(this.signedheaders);
+ hash = 37 * hash + Objects.hashCode(this.signature);
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final ParsedAuthHeader other = (ParsedAuthHeader) obj;
+ if (!Objects.equals(this.algorithm, other.algorithm)) {
+ return false;
+ }
+ if (!Objects.equals(this.accessKey, other.accessKey)) {
+ return false;
+ }
+ if (!Objects.equals(this.date, other.date)) {
+ return false;
+ }
+ if (!Objects.equals(this.region, other.region)) {
+ return false;
+ }
+ if (!Objects.equals(this.service, other.service)) {
+ return false;
+ }
+ if (!Objects.equals(this.signedheaders, other.signedheaders)) {
+ return false;
+ }
+ if (!Objects.equals(this.signature, other.signature)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "ParsedAuthHeader{" + "algorithm=" + algorithm + ", accessKey=" + accessKey + ", date=" + date + ", region=" + region + ", service=" + service + ", signedheaders=" + signedheaders + ", signature=" + signature + '}';
+ }
+
+ public static Optional parseFromAuthorizationHeader(String authHeader) {
+ //Get the parts from the Authorization header
+ Matcher authorizationMatcher = AUTH_HEADER_PATTERN.matcher(authHeader);
+
+ if (!authorizationMatcher.matches()) {
+ //Something is wrong. Why didn't this match now... when it already matched?
+ LogWriter.logDebug("Unable to parse authorization headers. Input header: " + authHeader);
+ return Optional.empty();
+ }
+
+ //Pull apart the string into components we want
+ String algorithmString = authorizationMatcher.group(AUTH_HEADER_PATTERN_ALGORITHM_GROUP);
+ Optional algorithmOptional = SigningAlgorithm.fromAuthorizationHeaderString(algorithmString);
+ if (algorithmOptional.isEmpty()) {
+ LogWriter.logError("Unable to detect AWS signature type. Input header: " + authHeader + " Parsed algorithm: " + algorithmString);
+ return Optional.empty();
+ }
+ String accessKey = authorizationMatcher.group(AUTH_HEADER_PATTERN_ACCESS_KEY_GROUP);
+ String date = authorizationMatcher.group(AUTH_HEADER_PATTERN_DATE_GROUP);
+ String region = authorizationMatcher.group(AUTH_HEADER_PATTERN_REGION_GROUP);
+ String service = authorizationMatcher.group(AUTH_HEADER_PATTERN_SERVICE_GROUP);
+ String signedheaders = authorizationMatcher.group(AUTH_HEADER_PATTERN_SIGNED_HEADERS_GROUP);
+ String signature = authorizationMatcher.group(AUTH_HEADER_PATTERN_SIGNATURE_GROUP);
+
+ //make return object and be done
+ ParsedAuthHeader parsed = new ParsedAuthHeader(algorithmOptional.get(), accessKey, date, region, service, signedheaders, signature);
+ LogWriter.logInfo("Successfully parsed Authorization header: " + parsed);
+ return Optional.of(parsed);
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/signing/SigningAlgorithm.java b/src/main/java/com/netspi/awssigner/signing/SigningAlgorithm.java
new file mode 100644
index 0000000..26f54c3
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/signing/SigningAlgorithm.java
@@ -0,0 +1,16 @@
+package com.netspi.awssigner.signing;
+
+import java.util.Optional;
+
+public enum SigningAlgorithm {
+ SIGV4, SIGV4A;
+ public static Optional fromAuthorizationHeaderString(String authHeaderPartString){
+ if(authHeaderPartString.equalsIgnoreCase("AWS4-HMAC-SHA256")){
+ return Optional.of(SIGV4);
+ } else if(authHeaderPartString.equalsIgnoreCase("AWS4-ECDSA-P256-SHA256")){
+ return Optional.of(SIGV4A);
+ } else {
+ return Optional.empty();
+ }
+ }
+}
diff --git a/src/main/java/com/netspi/awssigner/signing/SigningException.java b/src/main/java/com/netspi/awssigner/signing/SigningException.java
new file mode 100644
index 0000000..b95b76f
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/signing/SigningException.java
@@ -0,0 +1,17 @@
+package com.netspi.awssigner.signing;
+
+public class SigningException extends Exception {
+
+ public SigningException(String message) {
+ super(message);
+ }
+
+ public SigningException(Throwable cause) {
+ super(cause);
+ }
+
+ public SigningException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/view/AddProfileDialog.form b/src/main/java/com/netspi/awssigner/view/AddProfileDialog.form
new file mode 100644
index 0000000..6cd2fcf
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/AddProfileDialog.form
@@ -0,0 +1,231 @@
+
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/AddProfileDialog.java b/src/main/java/com/netspi/awssigner/view/AddProfileDialog.java
new file mode 100644
index 0000000..de4dfb6
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/AddProfileDialog.java
@@ -0,0 +1,262 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package com.netspi.awssigner.view;
+
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ *
+ * @author jkarnes
+ */
+public class AddProfileDialog extends javax.swing.JDialog {
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is always
+ * regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ profileTypeButtonGroup = new javax.swing.ButtonGroup();
+ AddProfileTitleLabel = new javax.swing.JLabel();
+ profileNameLabel = new javax.swing.JLabel();
+ profileNameTextField = new FormattedHintTextField(true);
+ profileNameDescriptionLabel = new javax.swing.JLabel();
+ profileTypeLabel = new javax.swing.JLabel();
+ staticCredentialsRadioButton = new javax.swing.JRadioButton();
+ assumeRoleRadioButton = new javax.swing.JRadioButton();
+ commandRadioButton = new javax.swing.JRadioButton();
+ okButton = new javax.swing.JButton();
+ cancelButton = new javax.swing.JButton();
+ errorTextLabel = new javax.swing.JLabel();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Add Signing Profile");
+
+ AddProfileTitleLabel.setFont(AddProfileTitleLabel.getFont().deriveFont(AddProfileTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ AddProfileTitleLabel.setForeground(new java.awt.Color(255, 102, 51));
+ AddProfileTitleLabel.setText("Add Profile");
+
+ profileNameLabel.setFont(profileNameLabel.getFont().deriveFont(profileNameLabel.getFont().getStyle() | java.awt.Font.BOLD, profileNameLabel.getFont().getSize()+1));
+ profileNameLabel.setLabelFor(profileNameTextField);
+ profileNameLabel.setText("Profile Name:");
+ profileNameLabel.setToolTipText("The name of the new profile.");
+
+ profileNameTextField.setToolTipText("The name of the new profile.");
+
+ profileNameDescriptionLabel.setText("The profile name must be unique.");
+
+ profileTypeLabel.setFont(profileTypeLabel.getFont().deriveFont(profileTypeLabel.getFont().getStyle() | java.awt.Font.BOLD, profileTypeLabel.getFont().getSize()+1));
+ profileTypeLabel.setText("Profile Type:");
+ profileTypeLabel.setToolTipText("The command to be executed to fetch credentials.");
+
+ profileTypeButtonGroup.add(staticCredentialsRadioButton);
+ staticCredentialsRadioButton.setFont(staticCredentialsRadioButton.getFont());
+ staticCredentialsRadioButton.setText("Static Credentials");
+
+ profileTypeButtonGroup.add(assumeRoleRadioButton);
+ assumeRoleRadioButton.setFont(assumeRoleRadioButton.getFont());
+ assumeRoleRadioButton.setText("AssumeRole");
+
+ profileTypeButtonGroup.add(commandRadioButton);
+ commandRadioButton.setFont(commandRadioButton.getFont());
+ commandRadioButton.setText("Command");
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ cancelButton.setText("Cancel");
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ errorTextLabel.setFont(errorTextLabel.getFont().deriveFont(errorTextLabel.getFont().getStyle() | java.awt.Font.BOLD));
+ errorTextLabel.setForeground(new java.awt.Color(255, 0, 0));
+ errorTextLabel.setText("The profile name already exists");
+ errorTextLabel.setVisible(false);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(AddProfileTitleLabel)
+ .addGap(0, 0, Short.MAX_VALUE))
+ .addGroup(layout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(profileNameLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(profileNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE))
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileTypeLabel)
+ .addGroup(layout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleRadioButton)
+ .addComponent(staticCredentialsRadioButton)
+ .addComponent(commandRadioButton)
+ .addComponent(profileNameDescriptionLabel)))
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(okButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(cancelButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(errorTextLabel)))
+ .addGap(0, 0, Short.MAX_VALUE)))))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(AddProfileTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileNameLabel)
+ .addComponent(profileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(profileNameDescriptionLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(profileTypeLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(staticCredentialsRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(assumeRoleRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(commandRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(okButton)
+ .addComponent(cancelButton)
+ .addComponent(errorTextLabel))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+ //Get the user's choice of name
+ String profileName = profileNameTextField.getText();
+
+ //Check if profile name was provided
+ if (profileName == null || profileName.isEmpty()) {
+ errorTextLabel.setText("The profile name is required");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Check if we already have a profile with this name. If so, bail out.
+ if (existingProfileNames.contains(profileName)) {
+ errorTextLabel.setText("The profile name already exists");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Get the type and create response object
+ if (staticCredentialsRadioButton.isSelected()) {
+ this.result = new StaticCredentialsProfile(profileName);
+ } else if (assumeRoleRadioButton.isSelected()) {
+ this.result = new AssumeRoleProfile(profileName);
+ } else if (commandRadioButton.isSelected()) {
+ this.result = new CommandProfile(profileName);
+ } else {
+ //No button selected
+ errorTextLabel.setText("The profile type is required");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Close the dialog
+ setVisible(false);
+ dispose();
+
+ }//GEN-LAST:event_okButtonActionPerformed
+
+ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ //Close the dialog
+ setVisible(false);
+ dispose();
+ }//GEN-LAST:event_cancelButtonActionPerformed
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ /* Create and display the dialog */
+ java.awt.EventQueue.invokeLater(() -> {
+ AddProfileDialog dialog = new AddProfileDialog(new javax.swing.JFrame(), true, new ArrayList<>());
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ @Override
+ public void windowClosing(java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ });
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel AddProfileTitleLabel;
+ private javax.swing.JRadioButton assumeRoleRadioButton;
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JRadioButton commandRadioButton;
+ private javax.swing.JLabel errorTextLabel;
+ private javax.swing.JButton okButton;
+ private javax.swing.JLabel profileNameDescriptionLabel;
+ private javax.swing.JLabel profileNameLabel;
+ public javax.swing.JTextField profileNameTextField;
+ private javax.swing.ButtonGroup profileTypeButtonGroup;
+ private javax.swing.JLabel profileTypeLabel;
+ private javax.swing.JRadioButton staticCredentialsRadioButton;
+ // End of variables declaration//GEN-END:variables
+ //START CUSTOM (NON-GENERATED) CODE
+
+ private Profile result = null;
+ private final List existingProfileNames;
+
+ /**
+ * Creates new form AddProfileDialog
+ */
+ public AddProfileDialog(java.awt.Frame parent, boolean modal, List existingProfileNames) {
+ super(parent, modal);
+ this.existingProfileNames = existingProfileNames;
+ initComponents();
+ BurpUIComponentCustomizer.applyBurpStyling(this);
+ }
+
+ /**
+ * Shows the dialog and gets the user's choice
+ *
+ * @return The result object or null if the dialog was closed/cancelled
+ */
+ public Optional showDialog() {
+ setVisible(true);
+ return Optional.ofNullable(result);
+ }
+}
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/BurpTabPanel.form b/src/main/java/com/netspi/awssigner/view/BurpTabPanel.form
new file mode 100644
index 0000000..8fe8443
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/BurpTabPanel.form
@@ -0,0 +1,1459 @@
+
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/BurpTabPanel.java b/src/main/java/com/netspi/awssigner/view/BurpTabPanel.java
new file mode 100644
index 0000000..0fe4eab
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/BurpTabPanel.java
@@ -0,0 +1,856 @@
+package com.netspi.awssigner.view;
+
+import com.netspi.awssigner.log.LogWriter;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.regex.Pattern;
+import javax.swing.border.EtchedBorder;
+
+/**
+ * This should be the dumb View logic. This should only be interacted with via
+ * the Controller.
+ */
+public class BurpTabPanel extends javax.swing.JPanel {
+
+ /**
+ * Creates new form RootTabPanel
+ */
+ public BurpTabPanel() {
+ initComponents();
+ BurpUIComponentCustomizer.applyBurpStyling(this);
+ }
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is always
+ * regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ globalSettingsPanel = new javax.swing.JPanel();
+ globalSettingsLabel = new javax.swing.JLabel();
+ globalSettingsDescriptionLabel = new javax.swing.JLabel();
+ signingEnabledCheckbox = new javax.swing.JCheckBox();
+ alwaysSignWithProfileLabel = new javax.swing.JLabel();
+ alwaysSignWithProfileComboBox = new javax.swing.JComboBox<>();
+ logLevelLabel = new javax.swing.JLabel();
+ logLevelComboBox = new javax.swing.JComboBox<>();
+ globalSettingsSeparator = new javax.swing.JSeparator();
+ profileManagementLabel = new javax.swing.JLabel();
+ profileManagementDescriptionLabel = new javax.swing.JLabel();
+ addProfileButton = new javax.swing.JButton();
+ deleteProfileButton = new javax.swing.JButton();
+ copyProfileButton = new javax.swing.JButton();
+ importProfilesButton = new javax.swing.JButton();
+ exportProfilesButton = new javax.swing.JButton();
+ profileListScrollPane = new javax.swing.JScrollPane();
+ profileList = new javax.swing.JList<>();
+ rightSideParentPanel = new javax.swing.JPanel();
+ profileConfigurationScrollPane = new javax.swing.JScrollPane();
+ profileConfigurationPanel = new javax.swing.JPanel();
+ profileConfigurationLabel = new javax.swing.JLabel();
+ profileNameLabel = new javax.swing.JLabel();
+ profileStatusLabel = new javax.swing.JLabel();
+ profileStatusTextLabel = new javax.swing.JLabel();
+ profileEnabledCheckbox = new javax.swing.JCheckBox();
+ profileInScopeOnlyCheckbox = new javax.swing.JCheckBox();
+ profileRegionLabel = new javax.swing.JLabel();
+ profileRegionTextField = new FormattedHintTextField(false);
+ profileServiceLabel = new javax.swing.JLabel();
+ profileServiceTextField = new FormattedHintTextField(false);
+ profileKeyIdLabel = new javax.swing.JLabel();
+ profileKeyIdTextField = new FormattedHintTextField(false, Pattern.compile(".+"));
+ testProfileButton = new javax.swing.JButton();
+ credentialCardContainerPanel = new javax.swing.JPanel();
+ staticCredentialsPanel = new javax.swing.JPanel();
+ staticCredentialsConfigurationLabel = new javax.swing.JLabel();
+ staticAccessKeyLabel = new javax.swing.JLabel();
+ staticAccessKeyTextField = new FormattedHintTextField(true, Pattern.compile("[A-Z0-9]{20,}"));
+ staticSecretKeyLabel = new javax.swing.JLabel();
+ staticSecretKeyTextField = new FormattedHintTextField(true, Pattern.compile("[A-Za-z0-9/+=]{40,}"));
+ staticSessionTokenLabel = new javax.swing.JLabel();
+ staticSessionTokenTextField = new FormattedHintTextField(false);
+ assumeRolePanel = new javax.swing.JPanel();
+ assumeRoleConfigurationLabel = new javax.swing.JLabel();
+ assumeRoleAssumerProfileLabel = new javax.swing.JLabel();
+ assumeRoleAssumerProfileComboBox = new javax.swing.JComboBox<>();
+ assumeRoleRoleArnLabel = new javax.swing.JLabel();
+ assumeRoleRoleArnTextField = new FormattedHintTextField(true, Pattern.compile("arn:.+:iam::[0-9]{12}:role/.+"));
+ assumeRoleSessionNameLabel = new javax.swing.JLabel();
+ assumeRoleSessionNameTextField = new FormattedHintTextField(false);
+ assumeRoleExternalIdLabel = new javax.swing.JLabel();
+ assumeRoleExternalIdTextField = new FormattedHintTextField(false);
+ assumeRoleDurationLabel = new javax.swing.JLabel();
+ assumeRoleDurationTextField = new FormattedHintTextField(false, Pattern.compile("\\d+"));
+ assumeRoleSessionPolicyPanel = new javax.swing.JPanel();
+ assumeRoleSessionPolicyConfigurationLabel = new javax.swing.JLabel();
+ assumeRoleSessionPolicyDescriptionLabel = new javax.swing.JLabel();
+ assumeRoleSessionPolicyScrollPane = new javax.swing.JScrollPane();
+ assumeRoleSessionPolicyTextArea = new javax.swing.JTextArea();
+ assumeRoleSessionPolicyPrettifyButton = new javax.swing.JButton();
+ commandPanel = new javax.swing.JPanel();
+ commandConfigurationLabel = new javax.swing.JLabel();
+ commandConfigurationDescriptionLabel = new javax.swing.JLabel();
+ commandCommandLabel = new javax.swing.JLabel();
+ commandCommandTextField = new FormattedHintTextField(true);
+ commandDurationLabel = new javax.swing.JLabel();
+ commandDurationTextField = new FormattedHintTextField(false, Pattern.compile("\\d+"));
+ commandExtractedSectionLabel = new javax.swing.JLabel();
+ commandExtractedSectionDescriptionLabel = new javax.swing.JLabel();
+ commandExtractedAccessKeyLabel = new javax.swing.JLabel();
+ commandExtractedAccessKeyTextField = new FormattedHintTextField(false);
+ commandExtractedSecretKeyLabel = new javax.swing.JLabel();
+ commandExtractedSecretKeyTextField = new FormattedHintTextField(false);
+ commandExtractedSessionTokenLabel = new javax.swing.JLabel();
+ commandExtractedSessionTokenTextField = new FormattedHintTextField(false);
+
+ setName("topPanel"); // NOI18N
+ addMouseListener(new java.awt.event.MouseAdapter() {
+ public void mouseClicked(java.awt.event.MouseEvent evt) {
+ formMouseClicked(evt);
+ }
+ });
+
+ globalSettingsLabel.setFont(globalSettingsLabel.getFont().deriveFont(globalSettingsLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ globalSettingsLabel.setForeground(new java.awt.Color(255, 102, 51));
+ globalSettingsLabel.setText("Global Settings");
+
+ globalSettingsDescriptionLabel.setFont(globalSettingsDescriptionLabel.getFont());
+ globalSettingsDescriptionLabel.setText("Change extension behavior. Set Always Sign With to force signing of all requests with the specified profile credentials.");
+
+ signingEnabledCheckbox.setFont(signingEnabledCheckbox.getFont());
+ signingEnabledCheckbox.setSelected(true);
+ signingEnabledCheckbox.setText("Signing Enabled");
+ signingEnabledCheckbox.setToolTipText("Enable/Disable request signing globally");
+ signingEnabledCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
+
+ alwaysSignWithProfileLabel.setFont(alwaysSignWithProfileLabel.getFont());
+ alwaysSignWithProfileLabel.setLabelFor(alwaysSignWithProfileComboBox);
+ alwaysSignWithProfileLabel.setText("Always Sign With:");
+ alwaysSignWithProfileLabel.setToolTipText("Sign all requests with the selected profile");
+
+ alwaysSignWithProfileComboBox.setFont(alwaysSignWithProfileComboBox.getFont());
+ alwaysSignWithProfileComboBox.setToolTipText("Sign all requests with the selected profile");
+
+ logLevelLabel.setFont(logLevelLabel.getFont());
+ logLevelLabel.setLabelFor(logLevelComboBox);
+ logLevelLabel.setText("Log Level");
+ logLevelLabel.setToolTipText("Set the extension's logging verbosity");
+
+ logLevelComboBox.setFont(logLevelComboBox.getFont());
+ logLevelComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Error", "Info", "Debug" }));
+ logLevelComboBox.setToolTipText("Set the extension's logging verbosity");
+
+ javax.swing.GroupLayout globalSettingsPanelLayout = new javax.swing.GroupLayout(globalSettingsPanel);
+ globalSettingsPanel.setLayout(globalSettingsPanelLayout);
+ globalSettingsPanelLayout.setHorizontalGroup(
+ globalSettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(globalSettingsPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(globalSettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(globalSettingsLabel)
+ .addGroup(globalSettingsPanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(globalSettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(globalSettingsDescriptionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGroup(globalSettingsPanelLayout.createSequentialGroup()
+ .addComponent(signingEnabledCheckbox)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(alwaysSignWithProfileLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(alwaysSignWithProfileComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(logLevelLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(logLevelComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
+ .addGap(248, 391, Short.MAX_VALUE))
+ .addComponent(globalSettingsSeparator)
+ );
+ globalSettingsPanelLayout.setVerticalGroup(
+ globalSettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(globalSettingsPanelLayout.createSequentialGroup()
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(globalSettingsLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(globalSettingsDescriptionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(globalSettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(signingEnabledCheckbox)
+ .addComponent(alwaysSignWithProfileLabel)
+ .addComponent(alwaysSignWithProfileComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(logLevelLabel)
+ .addComponent(logLevelComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(globalSettingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(8, 8, 8))
+ );
+
+ profileManagementLabel.setFont(profileManagementLabel.getFont().deriveFont(profileManagementLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ profileManagementLabel.setForeground(new java.awt.Color(255, 102, 51));
+ profileManagementLabel.setText("Profile Management");
+
+ profileManagementDescriptionLabel.setFont(profileManagementDescriptionLabel.getFont());
+ profileManagementDescriptionLabel.setText("Manage profiles which provide AWS credentials");
+
+ addProfileButton.setFont(addProfileButton.getFont());
+ addProfileButton.setText("Add");
+ addProfileButton.setToolTipText("Add a new profile");
+
+ deleteProfileButton.setFont(deleteProfileButton.getFont());
+ deleteProfileButton.setText("Delete");
+ deleteProfileButton.setToolTipText("Delete the currently selected profile");
+
+ copyProfileButton.setFont(copyProfileButton.getFont());
+ copyProfileButton.setText("Copy");
+ copyProfileButton.setToolTipText("Copy the currently selected profile");
+
+ importProfilesButton.setFont(importProfilesButton.getFont());
+ importProfilesButton.setText("Import");
+ importProfilesButton.setToolTipText("Import profiles from disk or environment variables");
+
+ exportProfilesButton.setFont(exportProfilesButton.getFont());
+ exportProfilesButton.setText("Export");
+ exportProfilesButton.setToolTipText("Export configured profiles");
+
+ profileList.setFont(profileList.getFont());
+ profileList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
+ profileListScrollPane.setViewportView(profileList);
+
+ profileConfigurationScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
+
+ profileConfigurationLabel.setFont(profileConfigurationLabel.getFont().deriveFont(profileConfigurationLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ profileConfigurationLabel.setForeground(new java.awt.Color(255, 102, 51));
+ profileConfigurationLabel.setText("Profile Configuration:");
+
+ profileNameLabel.setFont(profileNameLabel.getFont().deriveFont(profileNameLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ profileNameLabel.setText("[Add A Profile To Begin]");
+
+ profileStatusLabel.setFont(profileStatusLabel.getFont().deriveFont(profileStatusLabel.getFont().getStyle() | java.awt.Font.BOLD, profileStatusLabel.getFont().getSize()+1));
+ profileStatusLabel.setText("Status:");
+
+ profileStatusTextLabel.setFont(profileStatusTextLabel.getFont().deriveFont(profileStatusTextLabel.getFont().getSize()+1f));
+ profileStatusTextLabel.setText("Must add profile to begin editing");
+
+ profileEnabledCheckbox.setFont(profileEnabledCheckbox.getFont().deriveFont(profileEnabledCheckbox.getFont().getStyle() | java.awt.Font.BOLD, profileEnabledCheckbox.getFont().getSize()+1));
+ profileEnabledCheckbox.setSelected(true);
+ profileEnabledCheckbox.setText("Enabled");
+ profileEnabledCheckbox.setToolTipText("Enables/Disables this profile");
+ profileEnabledCheckbox.setEnabled(false);
+ profileEnabledCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
+ profileEnabledCheckbox.setMargin(new java.awt.Insets(2, 0, 2, 2));
+
+ profileInScopeOnlyCheckbox.setFont(profileInScopeOnlyCheckbox.getFont().deriveFont(profileInScopeOnlyCheckbox.getFont().getStyle() | java.awt.Font.BOLD, profileInScopeOnlyCheckbox.getFont().getSize()+1));
+ profileInScopeOnlyCheckbox.setText("In-Scope Only");
+ profileInScopeOnlyCheckbox.setToolTipText("When checked, only in-scope requests are signed with this profile");
+ profileInScopeOnlyCheckbox.setEnabled(false);
+ profileInScopeOnlyCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
+ profileInScopeOnlyCheckbox.setMargin(new java.awt.Insets(2, 0, 2, 2));
+
+ profileRegionLabel.setFont(profileRegionLabel.getFont().deriveFont(profileRegionLabel.getFont().getStyle() | java.awt.Font.BOLD, profileRegionLabel.getFont().getSize()+1));
+ profileRegionLabel.setLabelFor(profileRegionTextField);
+ profileRegionLabel.setText("Region:");
+
+ profileRegionTextField.setFont(profileRegionTextField.getFont());
+ profileRegionTextField.setToolTipText("If set, this will be the region set for all signed requests, overriding the value in the original request");
+ profileRegionTextField.setEnabled(false);
+
+ profileServiceLabel.setFont(profileServiceLabel.getFont().deriveFont(profileServiceLabel.getFont().getStyle() | java.awt.Font.BOLD, profileServiceLabel.getFont().getSize()+1));
+ profileServiceLabel.setLabelFor(profileServiceTextField);
+ profileServiceLabel.setText("Service:");
+
+ profileServiceTextField.setFont(profileServiceTextField.getFont());
+ profileServiceTextField.setToolTipText("If set, this will be the service set for all signed requests, overriding the value in the original request");
+ profileServiceTextField.setEnabled(false);
+
+ profileKeyIdLabel.setFont(profileKeyIdLabel.getFont().deriveFont(profileKeyIdLabel.getFont().getStyle() | java.awt.Font.BOLD, profileKeyIdLabel.getFont().getSize()+1));
+ profileKeyIdLabel.setLabelFor(profileKeyIdTextField);
+ profileKeyIdLabel.setText("Key Id:");
+
+ profileKeyIdTextField.setFont(profileKeyIdTextField.getFont());
+ profileKeyIdTextField.setToolTipText("If set, this profile will sign all requests which were originally signed with this Key Id. The request will be resigned with the configuration below");
+ profileKeyIdTextField.setEnabled(false);
+
+ testProfileButton.setFont(testProfileButton.getFont().deriveFont(testProfileButton.getFont().getStyle() | java.awt.Font.BOLD, testProfileButton.getFont().getSize()+1));
+ testProfileButton.setText("Test Profile Credentials");
+ testProfileButton.setToolTipText("Tests the credential configuration below and updates this profile's status with the results");
+ testProfileButton.setEnabled(false);
+
+ credentialCardContainerPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
+ credentialCardContainerPanel.setLayout(new java.awt.CardLayout());
+
+ staticCredentialsPanel.setName(""); // NOI18N
+
+ staticCredentialsConfigurationLabel.setFont(staticCredentialsConfigurationLabel.getFont().deriveFont(staticCredentialsConfigurationLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ staticCredentialsConfigurationLabel.setForeground(new java.awt.Color(255, 102, 51));
+ staticCredentialsConfigurationLabel.setText("Static Credentials Configuration");
+
+ staticAccessKeyLabel.setFont(staticAccessKeyLabel.getFont().deriveFont(staticAccessKeyLabel.getFont().getStyle() | java.awt.Font.BOLD, staticAccessKeyLabel.getFont().getSize()+1));
+ staticAccessKeyLabel.setLabelFor(staticAccessKeyTextField);
+ staticAccessKeyLabel.setText("Access Key:");
+ staticAccessKeyLabel.setToolTipText("The access key of the credentials");
+
+ staticAccessKeyTextField.setToolTipText("The access key to sign requests");
+ staticAccessKeyTextField.setEnabled(false);
+
+ staticSecretKeyLabel.setFont(staticSecretKeyLabel.getFont().deriveFont(staticSecretKeyLabel.getFont().getStyle() | java.awt.Font.BOLD, staticSecretKeyLabel.getFont().getSize()+1));
+ staticSecretKeyLabel.setLabelFor(staticSecretKeyTextField);
+ staticSecretKeyLabel.setText("Secret Key:");
+ staticSecretKeyLabel.setToolTipText("The secret key of the credentials.");
+
+ staticSecretKeyTextField.setToolTipText("The secret key to sign requests");
+ staticSecretKeyTextField.setEnabled(false);
+
+ staticSessionTokenLabel.setFont(staticSessionTokenLabel.getFont().deriveFont(staticSessionTokenLabel.getFont().getStyle() | java.awt.Font.BOLD, staticSessionTokenLabel.getFont().getSize()+1));
+ staticSessionTokenLabel.setLabelFor(staticSessionTokenTextField);
+ staticSessionTokenLabel.setText("Session Token:");
+ staticSessionTokenLabel.setToolTipText("The optional session token of the credentials.");
+
+ staticSessionTokenTextField.setToolTipText("The optional session token to sign requests");
+ staticSessionTokenTextField.setEnabled(false);
+
+ javax.swing.GroupLayout staticCredentialsPanelLayout = new javax.swing.GroupLayout(staticCredentialsPanel);
+ staticCredentialsPanel.setLayout(staticCredentialsPanelLayout);
+ staticCredentialsPanelLayout.setHorizontalGroup(
+ staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(staticCredentialsPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(staticCredentialsConfigurationLabel)
+ .addGroup(staticCredentialsPanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(staticSessionTokenLabel)
+ .addComponent(staticSecretKeyLabel)
+ .addComponent(staticAccessKeyLabel))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addComponent(staticSecretKeyTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)
+ .addComponent(staticSessionTokenTextField)
+ .addComponent(staticAccessKeyTextField, javax.swing.GroupLayout.Alignment.LEADING))))
+ .addContainerGap(761, Short.MAX_VALUE))
+ );
+ staticCredentialsPanelLayout.setVerticalGroup(
+ staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(staticCredentialsPanelLayout.createSequentialGroup()
+ .addComponent(staticCredentialsConfigurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(staticAccessKeyLabel)
+ .addComponent(staticAccessKeyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(staticSecretKeyLabel)
+ .addComponent(staticSecretKeyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(staticCredentialsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(staticSessionTokenLabel)
+ .addComponent(staticSessionTokenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(0, 0, Short.MAX_VALUE))
+ );
+
+ credentialCardContainerPanel.add(staticCredentialsPanel, "static_credentials_card");
+
+ assumeRolePanel.setName(""); // NOI18N
+
+ assumeRoleConfigurationLabel.setFont(assumeRoleConfigurationLabel.getFont().deriveFont(assumeRoleConfigurationLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ assumeRoleConfigurationLabel.setForeground(new java.awt.Color(255, 102, 51));
+ assumeRoleConfigurationLabel.setText("AssumeRole Configuration");
+
+ assumeRoleAssumerProfileLabel.setFont(assumeRoleAssumerProfileLabel.getFont().deriveFont(assumeRoleAssumerProfileLabel.getFont().getStyle() | java.awt.Font.BOLD, assumeRoleAssumerProfileLabel.getFont().getSize()+1));
+ assumeRoleAssumerProfileLabel.setLabelFor(assumeRoleAssumerProfileComboBox);
+ assumeRoleAssumerProfileLabel.setText("Assumer Profile:");
+ assumeRoleAssumerProfileLabel.setToolTipText("Set the profile which assume the specified role");
+
+ assumeRoleAssumerProfileComboBox.setFont(assumeRoleAssumerProfileComboBox.getFont());
+ assumeRoleAssumerProfileComboBox.setToolTipText("Set the profile which will be used to assume the role specified below");
+
+ assumeRoleRoleArnLabel.setFont(assumeRoleRoleArnLabel.getFont().deriveFont(assumeRoleRoleArnLabel.getFont().getStyle() | java.awt.Font.BOLD, assumeRoleRoleArnLabel.getFont().getSize()+1));
+ assumeRoleRoleArnLabel.setLabelFor(assumeRoleRoleArnTextField);
+ assumeRoleRoleArnLabel.setText("Role ARN:");
+ assumeRoleRoleArnLabel.setToolTipText("The role to be assumed");
+
+ assumeRoleRoleArnTextField.setFont(assumeRoleRoleArnTextField.getFont());
+ assumeRoleRoleArnTextField.setToolTipText("The role to be assumed. This role's trust policy must trust the \"Assumer Profile\" to assume this role");
+
+ assumeRoleSessionNameLabel.setFont(assumeRoleSessionNameLabel.getFont().deriveFont(assumeRoleSessionNameLabel.getFont().getStyle() | java.awt.Font.BOLD, assumeRoleSessionNameLabel.getFont().getSize()+1));
+ assumeRoleSessionNameLabel.setLabelFor(assumeRoleSessionNameTextField);
+ assumeRoleSessionNameLabel.setText("Session Name:");
+ assumeRoleSessionNameLabel.setToolTipText("An identifier for the assumed role session.");
+
+ assumeRoleSessionNameTextField.setFont(assumeRoleSessionNameTextField.getFont());
+ assumeRoleSessionNameTextField.setToolTipText("An identifier for the assumed role session.");
+
+ assumeRoleExternalIdLabel.setFont(assumeRoleExternalIdLabel.getFont().deriveFont(assumeRoleExternalIdLabel.getFont().getStyle() | java.awt.Font.BOLD, assumeRoleExternalIdLabel.getFont().getSize()+1));
+ assumeRoleExternalIdLabel.setLabelFor(assumeRoleExternalIdTextField);
+ assumeRoleExternalIdLabel.setText("External Id:");
+ assumeRoleExternalIdLabel.setToolTipText("A unique identifier that might be required when you assume a role in another account.");
+
+ assumeRoleExternalIdTextField.setFont(assumeRoleExternalIdTextField.getFont());
+ assumeRoleExternalIdTextField.setToolTipText("A unique identifier that may be required when you assume the role.");
+
+ assumeRoleDurationLabel.setFont(assumeRoleDurationLabel.getFont().deriveFont(assumeRoleDurationLabel.getFont().getStyle() | java.awt.Font.BOLD, assumeRoleDurationLabel.getFont().getSize()+1));
+ assumeRoleDurationLabel.setLabelFor(assumeRoleDurationTextField);
+ assumeRoleDurationLabel.setText("Duration (Seconds):");
+ assumeRoleDurationLabel.setToolTipText("The lifetime of the session. The credentials will be renewed as required.");
+
+ assumeRoleDurationTextField.setFont(assumeRoleDurationTextField.getFont());
+ assumeRoleDurationTextField.setToolTipText("The lifetime of the session. The credentials will be renewed as required.");
+
+ assumeRoleSessionPolicyConfigurationLabel.setFont(assumeRoleSessionPolicyConfigurationLabel.getFont().deriveFont(assumeRoleSessionPolicyConfigurationLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ assumeRoleSessionPolicyConfigurationLabel.setForeground(new java.awt.Color(255, 102, 51));
+ assumeRoleSessionPolicyConfigurationLabel.setText("Session Policy Configuration");
+
+ assumeRoleSessionPolicyDescriptionLabel.setFont(assumeRoleSessionPolicyDescriptionLabel.getFont());
+ assumeRoleSessionPolicyDescriptionLabel.setText(" The session policy is an optional IAM policy which further restricts the permissions of the assumed role. The permissions for a session are the intersection of the identity-based policies for the IAM role used to create the session and the session policy.");
+ assumeRoleSessionPolicyDescriptionLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+
+ assumeRoleSessionPolicyTextArea.setColumns(20);
+ assumeRoleSessionPolicyTextArea.setRows(5);
+ assumeRoleSessionPolicyScrollPane.setViewportView(assumeRoleSessionPolicyTextArea);
+
+ assumeRoleSessionPolicyPrettifyButton.setFont(assumeRoleSessionPolicyPrettifyButton.getFont());
+ assumeRoleSessionPolicyPrettifyButton.setText("Prettify");
+ assumeRoleSessionPolicyPrettifyButton.setToolTipText("Attempt to format the session policy.");
+
+ javax.swing.GroupLayout assumeRoleSessionPolicyPanelLayout = new javax.swing.GroupLayout(assumeRoleSessionPolicyPanel);
+ assumeRoleSessionPolicyPanel.setLayout(assumeRoleSessionPolicyPanelLayout);
+ assumeRoleSessionPolicyPanelLayout.setHorizontalGroup(
+ assumeRoleSessionPolicyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(assumeRoleSessionPolicyPanelLayout.createSequentialGroup()
+ .addGap(20, 20, 20)
+ .addGroup(assumeRoleSessionPolicyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleSessionPolicyConfigurationLabel)
+ .addComponent(assumeRoleSessionPolicyDescriptionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 680, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(assumeRoleSessionPolicyPrettifyButton)
+ .addComponent(assumeRoleSessionPolicyScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 680, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(90, Short.MAX_VALUE))
+ );
+ assumeRoleSessionPolicyPanelLayout.setVerticalGroup(
+ assumeRoleSessionPolicyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(assumeRoleSessionPolicyPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(assumeRoleSessionPolicyConfigurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(assumeRoleSessionPolicyDescriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(assumeRoleSessionPolicyScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(assumeRoleSessionPolicyPrettifyButton))
+ );
+
+ javax.swing.GroupLayout assumeRolePanelLayout = new javax.swing.GroupLayout(assumeRolePanel);
+ assumeRolePanel.setLayout(assumeRolePanelLayout);
+ assumeRolePanelLayout.setHorizontalGroup(
+ assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(assumeRolePanelLayout.createSequentialGroup()
+ .addGap(20, 20, 20)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleConfigurationLabel)
+ .addGroup(assumeRolePanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(assumeRolePanelLayout.createSequentialGroup()
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleDurationLabel)
+ .addComponent(assumeRoleExternalIdLabel))
+ .addGap(10, 10, 10)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addComponent(assumeRoleExternalIdTextField, javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleSessionNameTextField, javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleRoleArnTextField, javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleDurationTextField)
+ .addComponent(assumeRoleAssumerProfileComboBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE)))
+ .addComponent(assumeRoleSessionNameLabel)
+ .addComponent(assumeRoleAssumerProfileLabel)
+ .addComponent(assumeRoleRoleArnLabel))))
+ .addContainerGap(754, Short.MAX_VALUE))
+ .addGroup(assumeRolePanelLayout.createSequentialGroup()
+ .addComponent(assumeRoleSessionPolicyPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(0, 668, Short.MAX_VALUE))
+ );
+ assumeRolePanelLayout.setVerticalGroup(
+ assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(assumeRolePanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(assumeRoleConfigurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(11, 11, 11)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(assumeRoleAssumerProfileLabel)
+ .addComponent(assumeRoleAssumerProfileComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(assumeRoleRoleArnLabel)
+ .addComponent(assumeRoleRoleArnTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(assumeRoleSessionNameLabel)
+ .addComponent(assumeRoleSessionNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(assumeRoleExternalIdLabel)
+ .addComponent(assumeRoleExternalIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(assumeRolePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(assumeRoleDurationLabel)
+ .addComponent(assumeRoleDurationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(assumeRoleSessionPolicyPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ credentialCardContainerPanel.add(assumeRolePanel, "assume_role_card");
+
+ commandPanel.setName(""); // NOI18N
+
+ commandConfigurationLabel.setFont(commandConfigurationLabel.getFont().deriveFont(commandConfigurationLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ commandConfigurationLabel.setForeground(new java.awt.Color(255, 102, 51));
+ commandConfigurationLabel.setText("Command Configuration");
+
+ commandConfigurationDescriptionLabel.setText("The provided command will be executed to obtain credentials for request signing, as required. If a Duration value is provided, the credentials will considered valid for that duration. If a Duration value is not provided, the credentials will be cached for 60 minutes. If the Duration value is value is 0, then the command will be executed before each request. The extension will attempt to identify and extract the first valid Access Key, Secret Key and Session Token in the command stdout output.");
+ commandConfigurationDescriptionLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+ commandConfigurationDescriptionLabel.setPreferredSize(new java.awt.Dimension(500, 14));
+
+ commandCommandLabel.setFont(commandCommandLabel.getFont().deriveFont(commandCommandLabel.getFont().getStyle() | java.awt.Font.BOLD, commandCommandLabel.getFont().getSize()+1));
+ commandCommandLabel.setText("Command:");
+ commandCommandLabel.setToolTipText("The command to be executed to fetch credentials.");
+
+ commandCommandTextField.setToolTipText("The command to be executed to fetch credentials.");
+
+ commandDurationLabel.setFont(commandDurationLabel.getFont().deriveFont(commandDurationLabel.getFont().getStyle() | java.awt.Font.BOLD, commandDurationLabel.getFont().getSize()+1));
+ commandDurationLabel.setText("Duration (Seconds):");
+ commandDurationLabel.setToolTipText("The lifetime of the session. The credentials will be renewed as required.");
+
+ commandDurationTextField.setToolTipText("The lifetime of the credentials returned by the command. The credentials will be renewed as required.");
+
+ commandExtractedSectionLabel.setFont(commandExtractedSectionLabel.getFont().deriveFont(commandExtractedSectionLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ commandExtractedSectionLabel.setForeground(new java.awt.Color(255, 102, 51));
+ commandExtractedSectionLabel.setText("Extracted Credentials");
+
+ commandExtractedSectionDescriptionLabel.setText("Click the Test Profile Credentials button above to test the provided command, credential extraction and the credentials' validity. The most recently extracted credentials are shown below.");
+ commandExtractedSectionDescriptionLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+ commandExtractedSectionDescriptionLabel.setPreferredSize(new java.awt.Dimension(500, 14));
+
+ commandExtractedAccessKeyLabel.setFont(commandExtractedAccessKeyLabel.getFont().deriveFont(commandExtractedAccessKeyLabel.getFont().getStyle() | java.awt.Font.BOLD, commandExtractedAccessKeyLabel.getFont().getSize()+1));
+ commandExtractedAccessKeyLabel.setLabelFor(commandExtractedAccessKeyTextField);
+ commandExtractedAccessKeyLabel.setText("Access Key:");
+ commandExtractedAccessKeyLabel.setToolTipText("The most recently extracted access key.");
+
+ commandExtractedAccessKeyTextField.setEditable(false);
+ commandExtractedAccessKeyTextField.setToolTipText("The most recently extracted access key.");
+
+ commandExtractedSecretKeyLabel.setFont(commandExtractedSecretKeyLabel.getFont().deriveFont(commandExtractedSecretKeyLabel.getFont().getStyle() | java.awt.Font.BOLD, commandExtractedSecretKeyLabel.getFont().getSize()+1));
+ commandExtractedSecretKeyLabel.setLabelFor(commandExtractedSecretKeyTextField);
+ commandExtractedSecretKeyLabel.setText("Secret Key:");
+ commandExtractedSecretKeyLabel.setToolTipText("The most recently extracted secret key.");
+
+ commandExtractedSecretKeyTextField.setEditable(false);
+ commandExtractedSecretKeyTextField.setToolTipText("The most recently extracted secret key.");
+
+ commandExtractedSessionTokenLabel.setFont(commandExtractedSessionTokenLabel.getFont().deriveFont(commandExtractedSessionTokenLabel.getFont().getStyle() | java.awt.Font.BOLD, commandExtractedSessionTokenLabel.getFont().getSize()+1));
+ commandExtractedSessionTokenLabel.setLabelFor(commandExtractedSessionTokenTextField);
+ commandExtractedSessionTokenLabel.setText("Session Token:");
+ commandExtractedSessionTokenLabel.setToolTipText("The most recently extracted session token.");
+
+ commandExtractedSessionTokenTextField.setEditable(false);
+ commandExtractedSessionTokenTextField.setToolTipText("The most recently extracted session token.");
+
+ javax.swing.GroupLayout commandPanelLayout = new javax.swing.GroupLayout(commandPanel);
+ commandPanel.setLayout(commandPanelLayout);
+ commandPanelLayout.setHorizontalGroup(
+ commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(commandPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(commandConfigurationLabel)
+ .addGroup(commandPanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(commandExtractedSectionLabel)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addComponent(commandConfigurationDescriptionLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
+ .addGroup(javax.swing.GroupLayout.Alignment.LEADING, commandPanelLayout.createSequentialGroup()
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(commandDurationLabel)
+ .addComponent(commandCommandLabel))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addComponent(commandCommandTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE)
+ .addComponent(commandDurationTextField))))
+ .addGroup(commandPanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
+ .addComponent(commandExtractedSectionDescriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 672, Short.MAX_VALUE)
+ .addGroup(commandPanelLayout.createSequentialGroup()
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(commandExtractedSessionTokenLabel)
+ .addComponent(commandExtractedSecretKeyLabel)
+ .addComponent(commandExtractedAccessKeyLabel))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
+ .addComponent(commandExtractedSecretKeyTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
+ .addComponent(commandExtractedAccessKeyTextField)
+ .addComponent(commandExtractedSessionTokenTextField))))))))
+ .addContainerGap(760, Short.MAX_VALUE))
+ );
+ commandPanelLayout.setVerticalGroup(
+ commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(commandPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(commandConfigurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(commandConfigurationDescriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(commandCommandLabel)
+ .addComponent(commandCommandTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(commandDurationLabel)
+ .addComponent(commandDurationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(commandExtractedSectionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(commandExtractedSectionDescriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(commandExtractedAccessKeyLabel)
+ .addComponent(commandExtractedAccessKeyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(commandExtractedSecretKeyLabel)
+ .addComponent(commandExtractedSecretKeyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(commandPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(commandExtractedSessionTokenLabel)
+ .addComponent(commandExtractedSessionTokenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(342, Short.MAX_VALUE))
+ );
+
+ credentialCardContainerPanel.add(commandPanel, "command_card");
+
+ javax.swing.GroupLayout profileConfigurationPanelLayout = new javax.swing.GroupLayout(profileConfigurationPanel);
+ profileConfigurationPanel.setLayout(profileConfigurationPanelLayout);
+ profileConfigurationPanelLayout.setHorizontalGroup(
+ profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addComponent(profileStatusLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(profileStatusTextLabel))
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileServiceLabel)
+ .addComponent(profileKeyIdLabel)
+ .addComponent(profileRegionLabel))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
+ .addComponent(profileServiceTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 625, Short.MAX_VALUE)
+ .addComponent(profileRegionTextField, javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileKeyIdTextField)))
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addComponent(profileEnabledCheckbox)
+ .addGap(18, 18, 18)
+ .addComponent(profileInScopeOnlyCheckbox))
+ .addComponent(testProfileButton)))
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addComponent(profileConfigurationLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(profileNameLabel)))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addComponent(credentialCardContainerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ );
+ profileConfigurationPanelLayout.setVerticalGroup(
+ profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(profileConfigurationPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileConfigurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(profileNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileStatusLabel)
+ .addComponent(profileStatusTextLabel))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileEnabledCheckbox)
+ .addComponent(profileInScopeOnlyCheckbox))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileRegionLabel)
+ .addComponent(profileRegionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileServiceLabel)
+ .addComponent(profileServiceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(profileConfigurationPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileKeyIdLabel)
+ .addComponent(profileKeyIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(testProfileButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(credentialCardContainerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ profileConfigurationScrollPane.setViewportView(profileConfigurationPanel);
+
+ javax.swing.GroupLayout rightSideParentPanelLayout = new javax.swing.GroupLayout(rightSideParentPanel);
+ rightSideParentPanel.setLayout(rightSideParentPanelLayout);
+ rightSideParentPanelLayout.setHorizontalGroup(
+ rightSideParentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(rightSideParentPanelLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(profileConfigurationScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
+ );
+ rightSideParentPanelLayout.setVerticalGroup(
+ rightSideParentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileConfigurationScrollPane)
+ );
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(globalSettingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(profileManagementDescriptionLabel)
+ .addGap(18, 18, 18))
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileManagementLabel)
+ .addGroup(layout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
+ .addComponent(deleteProfileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(importProfilesButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(copyProfileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(exportProfilesButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(addProfileButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(profileListScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)))
+ .addGap(6, 6, 6)))
+ .addComponent(rightSideParentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(globalSettingsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(rightSideParentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(profileManagementLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(profileManagementDescriptionLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(addProfileButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(deleteProfileButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(copyProfileButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(importProfilesButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(exportProfilesButton))
+ .addComponent(profileListScrollPane))
+ .addGap(0, 0, Short.MAX_VALUE))))
+ );
+ }// //GEN-END:initComponents
+
+ private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
+ LogWriter.logDebug("Grabbing focus for top-level panel.");
+ this.requestFocusInWindow();
+ }//GEN-LAST:event_formMouseClicked
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ public javax.swing.JButton addProfileButton;
+ public javax.swing.JComboBox alwaysSignWithProfileComboBox;
+ private javax.swing.JLabel alwaysSignWithProfileLabel;
+ public javax.swing.JComboBox assumeRoleAssumerProfileComboBox;
+ private javax.swing.JLabel assumeRoleAssumerProfileLabel;
+ private javax.swing.JLabel assumeRoleConfigurationLabel;
+ private javax.swing.JLabel assumeRoleDurationLabel;
+ public javax.swing.JTextField assumeRoleDurationTextField;
+ private javax.swing.JLabel assumeRoleExternalIdLabel;
+ public javax.swing.JTextField assumeRoleExternalIdTextField;
+ public javax.swing.JPanel assumeRolePanel;
+ private javax.swing.JLabel assumeRoleRoleArnLabel;
+ public javax.swing.JTextField assumeRoleRoleArnTextField;
+ private javax.swing.JLabel assumeRoleSessionNameLabel;
+ public javax.swing.JTextField assumeRoleSessionNameTextField;
+ private javax.swing.JLabel assumeRoleSessionPolicyConfigurationLabel;
+ private javax.swing.JLabel assumeRoleSessionPolicyDescriptionLabel;
+ private javax.swing.JPanel assumeRoleSessionPolicyPanel;
+ public javax.swing.JButton assumeRoleSessionPolicyPrettifyButton;
+ private javax.swing.JScrollPane assumeRoleSessionPolicyScrollPane;
+ public javax.swing.JTextArea assumeRoleSessionPolicyTextArea;
+ private javax.swing.JLabel commandCommandLabel;
+ public javax.swing.JTextField commandCommandTextField;
+ private javax.swing.JLabel commandConfigurationDescriptionLabel;
+ private javax.swing.JLabel commandConfigurationLabel;
+ private javax.swing.JLabel commandDurationLabel;
+ public javax.swing.JTextField commandDurationTextField;
+ private javax.swing.JLabel commandExtractedAccessKeyLabel;
+ public javax.swing.JTextField commandExtractedAccessKeyTextField;
+ private javax.swing.JLabel commandExtractedSecretKeyLabel;
+ public javax.swing.JTextField commandExtractedSecretKeyTextField;
+ private javax.swing.JLabel commandExtractedSectionDescriptionLabel;
+ private javax.swing.JLabel commandExtractedSectionLabel;
+ private javax.swing.JLabel commandExtractedSessionTokenLabel;
+ public javax.swing.JTextField commandExtractedSessionTokenTextField;
+ public javax.swing.JPanel commandPanel;
+ public javax.swing.JButton copyProfileButton;
+ public javax.swing.JPanel credentialCardContainerPanel;
+ public javax.swing.JButton deleteProfileButton;
+ public javax.swing.JButton exportProfilesButton;
+ private javax.swing.JLabel globalSettingsDescriptionLabel;
+ private javax.swing.JLabel globalSettingsLabel;
+ public javax.swing.JPanel globalSettingsPanel;
+ private javax.swing.JSeparator globalSettingsSeparator;
+ public javax.swing.JButton importProfilesButton;
+ public javax.swing.JComboBox logLevelComboBox;
+ private javax.swing.JLabel logLevelLabel;
+ private javax.swing.JLabel profileConfigurationLabel;
+ public javax.swing.JPanel profileConfigurationPanel;
+ public javax.swing.JScrollPane profileConfigurationScrollPane;
+ public javax.swing.JCheckBox profileEnabledCheckbox;
+ public javax.swing.JCheckBox profileInScopeOnlyCheckbox;
+ private javax.swing.JLabel profileKeyIdLabel;
+ public javax.swing.JTextField profileKeyIdTextField;
+ public javax.swing.JList profileList;
+ public javax.swing.JScrollPane profileListScrollPane;
+ private javax.swing.JLabel profileManagementDescriptionLabel;
+ private javax.swing.JLabel profileManagementLabel;
+ public javax.swing.JLabel profileNameLabel;
+ private javax.swing.JLabel profileRegionLabel;
+ public javax.swing.JTextField profileRegionTextField;
+ private javax.swing.JLabel profileServiceLabel;
+ public javax.swing.JTextField profileServiceTextField;
+ private javax.swing.JLabel profileStatusLabel;
+ public javax.swing.JLabel profileStatusTextLabel;
+ public javax.swing.JPanel rightSideParentPanel;
+ public javax.swing.JCheckBox signingEnabledCheckbox;
+ private javax.swing.JLabel staticAccessKeyLabel;
+ public javax.swing.JTextField staticAccessKeyTextField;
+ private javax.swing.JLabel staticCredentialsConfigurationLabel;
+ public javax.swing.JPanel staticCredentialsPanel;
+ private javax.swing.JLabel staticSecretKeyLabel;
+ public javax.swing.JTextField staticSecretKeyTextField;
+ private javax.swing.JLabel staticSessionTokenLabel;
+ public javax.swing.JTextField staticSessionTokenTextField;
+ public javax.swing.JButton testProfileButton;
+ // End of variables declaration//GEN-END:variables
+}
diff --git a/src/main/java/com/netspi/awssigner/view/BurpUIComponentCustomizer.java b/src/main/java/com/netspi/awssigner/view/BurpUIComponentCustomizer.java
new file mode 100644
index 0000000..f853914
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/BurpUIComponentCustomizer.java
@@ -0,0 +1,19 @@
+package com.netspi.awssigner.view;
+
+import java.awt.Component;
+import java.util.function.Consumer;
+
+/**
+ * This is a workaround to apply Burp styling when possible without completely destroying the MVC OOP design...
+ */
+public class BurpUIComponentCustomizer {
+
+ //Default to no-op
+ private static Consumer styler = ((Component c)->{});
+ public static void setBurpStyler(Consumer stylingFunction){
+ styler = stylingFunction;
+ }
+ public static void applyBurpStyling(Component component){
+ styler.accept(component);
+ }
+}
diff --git a/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.form b/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.form
new file mode 100644
index 0000000..0374f40
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.form
@@ -0,0 +1,244 @@
+
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.java b/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.java
new file mode 100644
index 0000000..e4e3e0f
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/CopyProfileDialog.java
@@ -0,0 +1,295 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package com.netspi.awssigner.view;
+
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ *
+ * @author jkarnes
+ */
+public class CopyProfileDialog extends javax.swing.JDialog {
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is always
+ * regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ profileTypeButtonGroup = new javax.swing.ButtonGroup();
+ AddProfileTitleLabel = new javax.swing.JLabel();
+ profileNameLabel = new javax.swing.JLabel();
+ profileNameTextField = new FormattedHintTextField(true);
+ profileNameDescriptionLabel = new javax.swing.JLabel();
+ profileTypeLabel = new javax.swing.JLabel();
+ staticCredentialsRadioButton = new javax.swing.JRadioButton();
+ assumeRoleRadioButton = new javax.swing.JRadioButton();
+ commandRadioButton = new javax.swing.JRadioButton();
+ okButton = new javax.swing.JButton();
+ cancelButton = new javax.swing.JButton();
+ errorTextLabel = new javax.swing.JLabel();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Copy Signing Profile");
+
+ AddProfileTitleLabel.setFont(AddProfileTitleLabel.getFont().deriveFont(AddProfileTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, 15));
+ AddProfileTitleLabel.setForeground(new java.awt.Color(255, 102, 51));
+ AddProfileTitleLabel.setText("Copy Profile");
+
+ profileNameLabel.setFont(profileNameLabel.getFont().deriveFont(profileNameLabel.getFont().getStyle() | java.awt.Font.BOLD, profileNameLabel.getFont().getSize()+1));
+ profileNameLabel.setLabelFor(profileNameTextField);
+ profileNameLabel.setText("Profile Name:");
+ profileNameLabel.setToolTipText("The name of the new profile.");
+
+ profileNameTextField.setToolTipText("The name of the new profile.");
+ profileNameTextField.setText(originalProfile.getName() + " - Copy");
+
+ profileNameDescriptionLabel.setText("The profile name must be unique.");
+
+ profileTypeLabel.setFont(profileTypeLabel.getFont().deriveFont(profileTypeLabel.getFont().getStyle() | java.awt.Font.BOLD, profileTypeLabel.getFont().getSize()+1));
+ profileTypeLabel.setText("Profile Type:");
+ profileTypeLabel.setToolTipText("The command to be executed to fetch credentials.");
+
+ profileTypeButtonGroup.add(staticCredentialsRadioButton);
+ staticCredentialsRadioButton.setFont(staticCredentialsRadioButton.getFont());
+ staticCredentialsRadioButton.setText("Static Credentials");
+ staticCredentialsRadioButton.setEnabled(false);
+ staticCredentialsRadioButton.setSelected(originalProfile instanceof StaticCredentialsProfile);
+
+ profileTypeButtonGroup.add(assumeRoleRadioButton);
+ assumeRoleRadioButton.setFont(assumeRoleRadioButton.getFont());
+ assumeRoleRadioButton.setText("AssumeRole");
+ assumeRoleRadioButton.setEnabled(false);
+ assumeRoleRadioButton.setSelected(originalProfile instanceof AssumeRoleProfile);
+
+ profileTypeButtonGroup.add(commandRadioButton);
+ commandRadioButton.setFont(commandRadioButton.getFont());
+ commandRadioButton.setText("Command");
+ commandRadioButton.setEnabled(false);
+ commandRadioButton.setSelected(originalProfile instanceof CommandProfile);
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ cancelButton.setText("Cancel");
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ errorTextLabel.setFont(errorTextLabel.getFont().deriveFont(errorTextLabel.getFont().getStyle() | java.awt.Font.BOLD));
+ errorTextLabel.setForeground(new java.awt.Color(255, 0, 0));
+ errorTextLabel.setText("The profile name already exists");
+ errorTextLabel.setVisible(false);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(AddProfileTitleLabel)
+ .addGap(0, 0, Short.MAX_VALUE))
+ .addGroup(layout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(profileNameLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(profileNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE))
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(profileTypeLabel)
+ .addGroup(layout.createSequentialGroup()
+ .addGap(10, 10, 10)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(assumeRoleRadioButton)
+ .addComponent(staticCredentialsRadioButton)
+ .addComponent(commandRadioButton)
+ .addComponent(profileNameDescriptionLabel)))
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(okButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(cancelButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(errorTextLabel)))
+ .addGap(0, 0, Short.MAX_VALUE)))))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(AddProfileTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(profileNameLabel)
+ .addComponent(profileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(profileNameDescriptionLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(profileTypeLabel)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(staticCredentialsRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(assumeRoleRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(commandRadioButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(okButton)
+ .addComponent(cancelButton)
+ .addComponent(errorTextLabel))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+ //Get the user's choice of name
+ String profileName = profileNameTextField.getText();
+
+ //Check if profile name was provided
+ if (profileName == null || profileName.isEmpty()) {
+ errorTextLabel.setText("The profile name is required");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Check if we already have a profile with this name. If so, bail out.
+ if (existingProfileNames.contains(profileName)) {
+ errorTextLabel.setText("The profile name already exists");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Get the type and create copied profle
+ if (originalProfile instanceof StaticCredentialsProfile) {
+ StaticCredentialsProfile originalTemp = (StaticCredentialsProfile)originalProfile;
+ StaticCredentialsProfile temp = new StaticCredentialsProfile(profileName);
+ temp.setAccessKey(originalTemp.getAccessKey().orElse(null));
+ temp.setSecretKey(originalTemp.getSecretKey().orElse(null));
+ temp.setSessionToken(originalTemp.getSessionToken().orElse(null));
+ result = temp;
+ } else if (originalProfile instanceof AssumeRoleProfile) {
+ AssumeRoleProfile originalTemp = (AssumeRoleProfile)originalProfile;
+ AssumeRoleProfile temp = new AssumeRoleProfile(profileName);
+ temp.setAssumerProfile(originalTemp.getAssumerProfile().orElse(null));
+ temp.setRoleArn(originalTemp.getRoleArn().orElse(null));
+ temp.setSessionName(originalTemp.getSessionName().orElse(null));
+ temp.setExternalId(originalTemp.getExternalId().orElse(null));
+ temp.setDurationSeconds(originalTemp.getDurationSeconds().orElse(null));
+ temp.setSessionPolicy(originalTemp.getSessionPolicy().orElse(null));
+ result = temp;
+ } else if (originalProfile instanceof CommandProfile) {
+ CommandProfile originalTemp = (CommandProfile)originalProfile;
+ CommandProfile temp = new CommandProfile(profileName);
+ temp.setCommand(originalTemp.getCommand().orElse(null));
+ temp.setDurationSeconds(originalTemp.getDurationSeconds().orElse(null));
+ result = temp;
+ } else {
+ //No button selected
+ errorTextLabel.setText("The profile type is required");
+ errorTextLabel.setVisible(true);
+ return;
+ }
+
+ //Set common profile fields
+ result.setEnabled(originalProfile.isEnabled());
+ result.setInScopeOnly(originalProfile.isInScopeOnly());
+ result.setRegion(originalProfile.getRegion().orElse(null));
+ result.setService(originalProfile.getService().orElse(null));
+ result.setKeyId(originalProfile.getKeyId().orElse(null));
+
+ //Close the dialog
+ setVisible(false);
+ dispose();
+
+ }//GEN-LAST:event_okButtonActionPerformed
+
+ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ //Close the dialog
+ setVisible(false);
+ dispose();
+ }//GEN-LAST:event_cancelButtonActionPerformed
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ /* Create and display the dialog */
+ java.awt.EventQueue.invokeLater(() -> {
+ CopyProfileDialog dialog = new CopyProfileDialog(new javax.swing.JFrame(), true, new ArrayList<>(), new StaticCredentialsProfile("Example Profile"));
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ @Override
+ public void windowClosing(java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ });
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel AddProfileTitleLabel;
+ private javax.swing.JRadioButton assumeRoleRadioButton;
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JRadioButton commandRadioButton;
+ private javax.swing.JLabel errorTextLabel;
+ private javax.swing.JButton okButton;
+ private javax.swing.JLabel profileNameDescriptionLabel;
+ private javax.swing.JLabel profileNameLabel;
+ public javax.swing.JTextField profileNameTextField;
+ private javax.swing.ButtonGroup profileTypeButtonGroup;
+ private javax.swing.JLabel profileTypeLabel;
+ private javax.swing.JRadioButton staticCredentialsRadioButton;
+ // End of variables declaration//GEN-END:variables
+ //START CUSTOM (NON-GENERATED) CODE
+
+ private Profile result = null;
+ private final List existingProfileNames;
+ private final Profile originalProfile;
+
+ /**
+ * Creates new form AddProfileDialog
+ */
+ public CopyProfileDialog(java.awt.Frame parent, boolean modal, List existingProfileNames, Profile originalProfile) {
+ super(parent, modal);
+ this.existingProfileNames = existingProfileNames;
+ this.originalProfile = originalProfile;
+ initComponents();
+ BurpUIComponentCustomizer.applyBurpStyling(this);
+ }
+
+ /**
+ * Shows the dialog and gets the user's choice
+ *
+ * @return The result object or null if the dialog was closed/cancelled
+ */
+ public Optional showDialog() {
+ setVisible(true);
+ return Optional.ofNullable(result);
+ }
+}
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/FormattedHintTextField.java b/src/main/java/com/netspi/awssigner/view/FormattedHintTextField.java
new file mode 100644
index 0000000..714c771
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/FormattedHintTextField.java
@@ -0,0 +1,130 @@
+package com.netspi.awssigner.view;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Insets;
+import java.awt.RenderingHints;
+import java.util.regex.Pattern;
+import javax.swing.BorderFactory;
+import javax.swing.InputVerifier;
+import javax.swing.JComponent;
+import javax.swing.JTextField;
+import javax.swing.border.Border;
+
+/**
+ * Hacky workaround to enable a hint message in a format-validated text field.
+ *
+ * Cobbled together from here:
+ * https://stackoverflow.com/questions/1738966/java-jtextfield-with-input-hint
+ * https://itqna.net/questions/17762/how-validate-text-field-inputverifier
+ */
+public class FormattedHintTextField extends JTextField {
+
+ private final boolean required;
+ private Pattern format = null;
+ private final String additionalHelpText;
+
+ public FormattedHintTextField(boolean required) {
+ //Pass along required and allow any non-empty input for the pattern
+ this(required, Pattern.compile(".+"));
+ }
+
+ public FormattedHintTextField(boolean required, Pattern format) {
+ //Pass along required and format, no additional help text
+ this(required, format, null);
+ }
+
+ public FormattedHintTextField(boolean required, Pattern format, String additionalHelpText) {
+ super();
+ this.required = required;
+ this.format = format;
+ this.additionalHelpText = additionalHelpText;
+
+ setInputVerifier(new InputVerifier() {
+ Border originalBorder;
+
+ @Override
+ public boolean verify(JComponent input) {
+
+ JTextField comp = (JTextField) input;
+ String inputText = comp.getText();
+
+ //Check for null/empty input
+ if (inputText == null || inputText.isBlank()) {
+ //Return indication based on whether or not the input is required
+ return !required;
+ } else {
+ //There is some input. Check it against the expected format
+ return format.matcher(inputText).matches();
+ }
+ }
+
+ @Override
+ public boolean shouldYieldFocus(JComponent input) {
+ boolean isValid = verify(input);
+
+ if (!isValid) {
+ originalBorder = originalBorder == null ? input.getBorder() : originalBorder;
+ input.setBorder(BorderFactory.createLineBorder(Color.red, 2));
+ } else {
+ if (originalBorder != null) {
+ input.setBorder(originalBorder);
+ originalBorder = null;
+ }
+ }
+
+ //If we return isValid here, we can keep focus when invalid input is submitted. This feels wrong though.
+ return true;
+ }
+ });
+ }
+
+ @Override
+ public void paintComponent(final Graphics USE_g2d_INSTEAD) {
+ //Check optional or required
+ String hint = required ? "Required" : "Optional";
+ //Add help text, if we have any
+ if (additionalHelpText != null && !additionalHelpText.trim().isEmpty()) {
+ hint = hint + " - " + additionalHelpText;
+ }
+
+ if (!this.isEnabled() || !this.isEditable()) {
+ hint = "Input Disabled";
+ }
+
+ final Graphics2D g2d = (Graphics2D) USE_g2d_INSTEAD;
+ super.paintComponent(g2d);
+
+ if (getText().isEmpty()) {
+ g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+
+ final Insets ins = getInsets();
+ final FontMetrics fm = g2d.getFontMetrics();
+
+ final int cB = getBackground().getRGB();
+ final int cF = getForeground().getRGB();
+ final int m = 0xfefefefe;
+ final int c2 = ((cB & m) >>> 1) + ((cF & m) >>> 1);
+
+ //Only update the color if it's enabled or editabled. Otherwise leave default
+ if (this.isEnabled() || this.isEditable()) {
+ g2d.setColor(new Color(c2, true));
+ }
+
+ g2d.setFont(g2d.getFont().deriveFont(Font.ITALIC));
+ g2d.drawString(hint, ins.left, getHeight() - fm.getDescent() - ins.bottom);
+ }
+ }
+
+ public boolean isRequired() {
+ return required;
+ }
+
+ public Pattern getFormat() {
+ return format;
+ }
+
+}
diff --git a/src/main/java/com/netspi/awssigner/view/ImportDialog.form b/src/main/java/com/netspi/awssigner/view/ImportDialog.form
new file mode 100644
index 0000000..624dbcc
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/ImportDialog.form
@@ -0,0 +1,262 @@
+
+
+
diff --git a/src/main/java/com/netspi/awssigner/view/ImportDialog.java b/src/main/java/com/netspi/awssigner/view/ImportDialog.java
new file mode 100644
index 0000000..79b3126
--- /dev/null
+++ b/src/main/java/com/netspi/awssigner/view/ImportDialog.java
@@ -0,0 +1,508 @@
+/*
+ * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
+ * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template
+ */
+package com.netspi.awssigner.view;
+
+import com.netspi.awssigner.log.LogWriter;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import com.netspi.awssigner.model.persistence.ProfileImporter;
+import com.netspi.awssigner.model.persistence.AutoProfileImporter;
+import com.netspi.awssigner.model.persistence.ClipboardProfileImporter;
+import com.netspi.awssigner.model.persistence.EnvironmentVariableProfileImporter;
+import com.netspi.awssigner.model.persistence.FileProfileImporter;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.event.TableModelEvent;
+import javax.swing.table.DefaultTableModel;
+import javax.swing.table.TableModel;
+
+/**
+ *
+ * @author jkarnes
+ */
+public class ImportDialog extends javax.swing.JDialog {
+
+ private static final int SELECT_COLUMN_INDEX = 0;
+ private static final int NAME_COLUMN_INDEX = 1;
+ private static final int KEYID_COLUMN_INDEX = 2;
+ private static final int TYPE_COLUMN_INDEX = 3;
+
+ private final List profiles = new ArrayList<>();
+ private List result = null;
+ private final List existingProfileNames;
+
+ public ImportDialog(java.awt.Frame parent, boolean modal, List existingProfileNames) {
+ super(parent, modal);
+ this.existingProfileNames = existingProfileNames;
+ initComponents();
+ BurpUIComponentCustomizer.applyBurpStyling(this);
+ }
+
+ /**
+ * Shows the dialog and gets the user's choice
+ *
+ * @return The result object or null if the dialog was closed/cancelled
+ */
+ public Optional> showDialog() {
+ setVisible(true);
+ return Optional.ofNullable(result);
+ }
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is always
+ * regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jPanel1 = new javax.swing.JPanel();
+ autoButton = new javax.swing.JButton();
+ fileButton = new javax.swing.JButton();
+ envButton = new javax.swing.JButton();
+ clipboardButton = new javax.swing.JButton();
+ jPanel2 = new javax.swing.JPanel();
+ selectAllButton = new javax.swing.JButton();
+ selectNoneButton = new javax.swing.JButton();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ profileTable = new javax.swing.JTable();
+ okButton = new javax.swing.JButton();
+ cancelButton = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Import Signing Profiles");
+
+ jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Source", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 102, 51))); // NOI18N
+
+ autoButton.setText("Auto");
+ autoButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ autoButtonActionPerformed(evt);
+ }
+ });
+
+ fileButton.setText("File");
+ fileButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ fileButtonActionPerformed(evt);
+ }
+ });
+
+ envButton.setText("Env");
+ envButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ envButtonActionPerformed(evt);
+ }
+ });
+
+ clipboardButton.setText("Clipboard");
+ clipboardButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ clipboardButtonActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createSequentialGroup()
+ .addComponent(autoButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(fileButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(envButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(clipboardButton))
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(autoButton)
+ .addComponent(fileButton)
+ .addComponent(envButton)
+ .addComponent(clipboardButton))
+ );
+
+ jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(255, 102, 51))); // NOI18N
+
+ selectAllButton.setText("All");
+ selectAllButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ selectAllButtonActionPerformed(evt);
+ }
+ });
+
+ selectNoneButton.setText("None");
+ selectNoneButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ selectNoneButtonActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createSequentialGroup()
+ .addComponent(selectAllButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(selectNoneButton))
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(selectAllButton)
+ .addComponent(selectNoneButton))
+ );
+
+ jScrollPane2.setPreferredSize(new java.awt.Dimension(900, 200));
+
+ profileTable.setModel(new javax.swing.table.DefaultTableModel(
+ new Object [][] {
+
+ },
+ new String [] {
+ "Import", "Name", "Access Key Id", "Type"
+ }
+ ) {
+ Class[] types = new Class [] {
+ java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
+ };
+ boolean[] canEdit = new boolean [] {
+ true, true, false, false
+ };
+
+ public Class getColumnClass(int columnIndex) {
+ return types [columnIndex];
+ }
+
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return canEdit [columnIndex];
+ }
+ });
+ profileTable.getTableHeader().setReorderingAllowed(false);
+ jScrollPane2.setViewportView(profileTable);
+ if (profileTable.getColumnModel().getColumnCount() > 0) {
+ profileTable.getColumnModel().getColumn(0).setMinWidth(25);
+ profileTable.getColumnModel().getColumn(0).setPreferredWidth(60);
+ profileTable.getColumnModel().getColumn(0).setMaxWidth(75);
+ profileTable.getColumnModel().getColumn(1).setMinWidth(150);
+ profileTable.getColumnModel().getColumn(1).setPreferredWidth(200);
+ profileTable.getColumnModel().getColumn(2).setMinWidth(220);
+ profileTable.getColumnModel().getColumn(2).setPreferredWidth(250);
+ profileTable.getColumnModel().getColumn(3).setMinWidth(25);
+ profileTable.getColumnModel().getColumn(3).setPreferredWidth(125);
+ profileTable.getColumnModel().getColumn(3).setMaxWidth(150);
+ }
+ profileTable.getModel().addTableModelListener(this::onTableModelEvent);
+
+ okButton.setText("OK");
+ okButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ okButtonActionPerformed(evt);
+ }
+ });
+
+ cancelButton.setText("Cancel");
+ cancelButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancelButtonActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(0, 520, Short.MAX_VALUE))
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 910, Short.MAX_VALUE))
+ .addContainerGap())
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(okButton)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(cancelButton)
+ .addGap(379, 379, 379))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(okButton)
+ .addComponent(cancelButton))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
+ //Close the dialog
+ setVisible(false);
+ dispose();
+ }//GEN-LAST:event_cancelButtonActionPerformed
+
+ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
+ //Remove all non-selected rows
+ int index = 0;
+ for (Iterator iterator = profiles.iterator(); iterator.hasNext(); index++) {
+ iterator.next();
+ if (!(boolean) profileTable.getModel().getValueAt(index, SELECT_COLUMN_INDEX)) {
+ iterator.remove();
+ }
+ }
+ LogWriter.logDebug(profiles.size() + " profile(s) remaining after removing unselected profiles.");
+
+ Set allProfileNames = profiles.stream().map(Profile::getName).collect(Collectors.toSet());
+
+ //Check if there are any collisions with existing profiles.
+ Set existingNameCollisions = allProfileNames.stream().filter(name -> {
+ return existingProfileNames.contains(name);
+ }).collect(Collectors.toSet());
+
+ //Check if there are any collisions within the new profiles to be imported.
+ Set uniqueNames = new HashSet<>();
+ Set duplicateNames = allProfileNames.stream()
+ .filter(n -> !uniqueNames.add(n)) // Set.add() returns false if the element was already in the set.
+ .collect(Collectors.toSet());
+
+ //Check if any assume role profiles to be imported are missing their assumer
+ Set assumeRoleMissingParent = profiles.stream().filter(profile -> {
+ return profile instanceof AssumeRoleProfile
+ && !allProfileNames.contains(((AssumeRoleProfile) profile).getAssumerProfile().get().getName());
+ }).map(profile -> {
+ return "AssumeRole: " + profile.getName() + " - Missing Assumer Profile: " + ((AssumeRoleProfile) profile).getAssumerProfile().get().getName();
+ })
+ .collect(Collectors.toSet());
+
+ if (!existingNameCollisions.isEmpty()) {
+ JOptionPane.showMessageDialog(this,
+ "Profiles with the following names already exist.\nPlease rename these in the table before importing:\n" + existingNameCollisions.stream().collect(Collectors.joining(", ")),
+ "Profile Name Collision",
+ JOptionPane.ERROR_MESSAGE);
+ } else if (!duplicateNames.isEmpty()) {
+ JOptionPane.showMessageDialog(this,
+ "The following profile names appear twice in the table.\nPlease rename one before importing:\n" + duplicateNames.stream().collect(Collectors.joining(", ")),
+ "Profile Name Collision",
+ JOptionPane.ERROR_MESSAGE);
+ } else if (!assumeRoleMissingParent.isEmpty()) {
+ JOptionPane.showMessageDialog(this,
+ "The following assume role profile are imported without their parent assumer profile.\nPlease import the parent assumer profile as well:\n" + assumeRoleMissingParent.stream().collect(Collectors.joining(",\n")),
+ "Profile Name Collision",
+ JOptionPane.ERROR_MESSAGE);
+ } else {
+ //Set the result object
+ result = profiles;
+ LogWriter.logInfo("Importing " + result.size() + " profile(s): " + result.stream().map(Profile::getName).collect(Collectors.joining(", ")));
+ //Close the dialog
+ setVisible(false);
+ dispose();
+ }
+ }//GEN-LAST:event_okButtonActionPerformed
+
+ private void selectAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllButtonActionPerformed
+ DefaultTableModel tableModel = ((DefaultTableModel) profileTable.getModel());
+ for (int i = 0; i < tableModel.getRowCount(); i++) {
+ tableModel.setValueAt(true, i, SELECT_COLUMN_INDEX);
+ }
+ }//GEN-LAST:event_selectAllButtonActionPerformed
+
+ private void selectNoneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectNoneButtonActionPerformed
+ DefaultTableModel tableModel = ((DefaultTableModel) profileTable.getModel());
+ for (int i = 0; i < tableModel.getRowCount(); i++) {
+ tableModel.setValueAt(false, i, SELECT_COLUMN_INDEX);
+ }
+ }//GEN-LAST:event_selectNoneButtonActionPerformed
+
+ private void autoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoButtonActionPerformed
+ ProfileImporter importer = new AutoProfileImporter();
+
+ List newProfiles = importer.importProfiles();
+ LogWriter.logDebug("Auto import found " + newProfiles.size() + " profile(s)");
+ addProfilesToTable(newProfiles);
+ }//GEN-LAST:event_autoButtonActionPerformed
+
+ private void envButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_envButtonActionPerformed
+ ProfileImporter importer = new EnvironmentVariableProfileImporter();
+
+ List newProfiles = importer.importProfiles();
+ LogWriter.logDebug("Environment Variable import found " + newProfiles.size() + " profile(s)");
+ addProfilesToTable(newProfiles);
+
+ }//GEN-LAST:event_envButtonActionPerformed
+
+ private void clipboardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clipboardButtonActionPerformed
+ ProfileImporter importer = new ClipboardProfileImporter();
+
+ List newProfiles = importer.importProfiles();
+ LogWriter.logDebug("Clipboard import found " + newProfiles.size() + " profile(s)");
+ addProfilesToTable(newProfiles);
+ }//GEN-LAST:event_clipboardButtonActionPerformed
+
+ private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButtonActionPerformed
+ JFileChooser chooser = new JFileChooser(System.getProperty("user.home"));
+ chooser.setFileHidingEnabled(false);
+ if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
+ Path fileSelection = Paths.get(chooser.getSelectedFile().getPath());
+ LogWriter.logDebug("Selected path from file dialog: " + fileSelection);
+ FileProfileImporter fileImporter = new FileProfileImporter(fileSelection);
+ List newProfiles = fileImporter.importProfiles();
+ LogWriter.logInfo("Imported " + newProfiles.size() + " profile(s) from file: " + fileSelection);
+ addProfilesToTable(newProfiles);
+ } else {
+ LogWriter.logDebug("No file chosen in file prompt");
+ }
+ }//GEN-LAST:event_fileButtonActionPerformed
+
+ private void addProfilesToTable(List newProfiles) {
+ DefaultTableModel tableModel = (DefaultTableModel) profileTable.getModel();
+ for (Profile newProfile : newProfiles) {
+ String typeName = null;
+ if (newProfile instanceof StaticCredentialsProfile) {
+ typeName = "Static Credentials";
+ } else if (newProfile instanceof AssumeRoleProfile) {
+ typeName = "Assume Role";
+ } else if (newProfile instanceof CommandProfile) {
+ typeName = "Command";
+ } else {
+ LogWriter.logError("Unexpected profile type: " + newProfile.getClass());
+ continue;
+ }
+
+ //Loop until we have a unique name. Starting with the name as-is, then (1), (2), ...
+ String originalName = newProfile.getName();
+ String name = originalName;
+ int i = 0;
+ while (profileNameExistsInCollection(profiles, name)) {
+ i++;
+ name = originalName + " (" + i + ")";
+ }
+ //Here, a unique name has been found
+ newProfile.setName(name);
+
+ //Add to the cumulative list
+ profiles.add(newProfile);
+
+ //Get a key id to show (if possible)
+ String keyId = "N/A";
+ if (newProfile instanceof StaticCredentialsProfile) {
+ keyId = ((StaticCredentialsProfile) newProfile).getAccessKey().orElse("");
+ }
+ if (newProfile.getKeyId().isPresent()) {
+ keyId = newProfile.getKeyId().get();
+ }
+ //Add to our table
+ tableModel.addRow(new Object[]{true, newProfile.getName(), keyId, typeName});
+ }
+ }
+
+ private boolean profileNameExistsInCollection(Collection profiles, String name) {
+ return profiles.stream().map(Profile::getName).filter(profileName -> profileName.equals(name)).findAny().isPresent();
+ }
+
+ private void onTableModelEvent(TableModelEvent event) {
+ //Too noisey, even for debug
+ //LogWriter.logDebug("Import Table model event. Type: " + event.getType() + " Column: " + event.getColumn() + " First Row: " + event.getFirstRow() + " Last Row: " + event.getLastRow());
+ //We only care about updates to the name column
+ if (event.getType() == TableModelEvent.UPDATE && event.getColumn() == NAME_COLUMN_INDEX) {
+ //get the new name of the profile
+ String newName = (String) ((TableModel) event.getSource()).getValueAt(event.getFirstRow(), NAME_COLUMN_INDEX);
+ //get the corresponding profile from our list.
+ Profile profile = profiles.get(event.getFirstRow());
+
+ LogWriter.logDebug("Updating profile: " + profile + " new name: " + newName);
+ //Set the new value
+ profile.setName(newName);
+ }
+
+ }
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ /* Set the Nimbus look and feel */
+ //
+ /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
+ * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
+ */
+ try {
+ for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ javax.swing.UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (ClassNotFoundException ex) {
+ java.util.logging.Logger.getLogger(ImportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (InstantiationException ex) {
+ java.util.logging.Logger.getLogger(ImportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (IllegalAccessException ex) {
+ java.util.logging.Logger.getLogger(ImportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (javax.swing.UnsupportedLookAndFeelException ex) {
+ java.util.logging.Logger.getLogger(ImportDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ }
+ //
+
+ /* Create and display the dialog */
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ ImportDialog dialog = new ImportDialog(new javax.swing.JFrame(), true, Collections.emptyList());
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ @Override
+ public void windowClosing(java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ }
+ });
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton autoButton;
+ private javax.swing.JButton cancelButton;
+ private javax.swing.JButton clipboardButton;
+ private javax.swing.JButton envButton;
+ private javax.swing.JButton fileButton;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JButton okButton;
+ private javax.swing.JTable profileTable;
+ private javax.swing.JButton selectAllButton;
+ private javax.swing.JButton selectNoneButton;
+ // End of variables declaration//GEN-END:variables
+
+}
diff --git a/src/main/main.iml b/src/main/main.iml
deleted file mode 100644
index b0d96eb..0000000
--- a/src/main/main.iml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/test/java/com/netspi/awssigner/model/persistence/CredentialsParserTest.java b/src/test/java/com/netspi/awssigner/model/persistence/CredentialsParserTest.java
new file mode 100644
index 0000000..8aa9de7
--- /dev/null
+++ b/src/test/java/com/netspi/awssigner/model/persistence/CredentialsParserTest.java
@@ -0,0 +1,161 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.credentials.CredentialsParser;
+import com.netspi.awssigner.credentials.SigningCredentials;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Optional;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+public class CredentialsParserTest {
+
+ private final Path parentTestInputFolder = Paths.get("src", "test", "resources", "CredentialsParserInputs");
+
+ @Test
+ public void testSingleSimpleProfile() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertTrue(creds.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testSingleSimpleProfileWithSession() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_with_session.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testSettingsText() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("settings_text.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testGetSessionTokenOutput() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("get-session-token_output.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("mgJteE7dZgSLC2eo2vKsAUWRSnchrWzCRnoDpUSJ", creds.getSecretKey());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testExternalCommandOutput() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("external_command_example.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testEnvironmentVariablesCommands() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("environment_variables.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testCLIConfigure() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("cli_configure_example.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", creds.getSecretKey());
+ assertTrue(creds.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testAssumeRoleXMLOneLine() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("assume-role_output_xml_oneline.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("DcCc9H6oCkGUEXAMPLEx8NIfVG8kO2T/3jORxuZY", creds.getSecretKey());
+ assertEquals("AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testAssumeRoleXMLMultiLine() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("assume-role_output_xml.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("AKIAIOSFODNN7EXAMPLE", creds.getAccessKey());
+ assertEquals("DcCc9H6oCkGUEXAMPLEx8NIfVG8kO2T/3jORxuZY", creds.getSecretKey());
+ assertEquals("AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testAssumeRoleJSONMultiLine() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("assume-role_output.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("ASIAJEXAMPLEXEG2JICA", creds.getAccessKey());
+ assertEquals("FTNBND5Q6mEXAMPLEe27V0Pce/03EShqVZTTsLzF", creds.getSecretKey());
+ assertEquals("AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=", creds.getSessionToken().get());
+ }
+
+ @Test
+ public void testAssumeRoleJSONOneLine() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("assume-role_output_oneline.txt");
+ byte[] bytes = Files.readAllBytes(inputPath);
+ String rawText = new String(bytes, StandardCharsets.UTF_8);
+ Optional result = CredentialsParser.parseCredentialsFromText(rawText);
+ assertTrue(result.isPresent());
+ SigningCredentials creds = result.get();
+ assertEquals("ASIAJEXAMPLEXEG2JICA", creds.getAccessKey());
+ assertEquals("FTNBND5Q6mEXAMPLEe27V0Pce/03EShqVZTTsLzF", creds.getSecretKey());
+ assertEquals("AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=", creds.getSessionToken().get());
+ }
+
+}
diff --git a/src/test/java/com/netspi/awssigner/model/persistence/FileProfileImporterTest.java b/src/test/java/com/netspi/awssigner/model/persistence/FileProfileImporterTest.java
new file mode 100644
index 0000000..7a24790
--- /dev/null
+++ b/src/test/java/com/netspi/awssigner/model/persistence/FileProfileImporterTest.java
@@ -0,0 +1,248 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+public class FileProfileImporterTest {
+
+ private final Path parentTestInputFolder = Paths.get("src", "test", "resources", "FileProfileImportInputs");
+
+ @Test
+ public void testSimpleSingleImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("default", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testSingleImportWithProfileName() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_profile_name.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("my-profile", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testSingleImportWithConfig() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_with_config.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("default", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testSingleImportWithIgnoredExtraProperties() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_with_ignored_extras.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("default", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testSingleImportWithSession() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_with_session.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("default", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertEquals("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk", staticCredentialsProfile.getSessionToken().get());
+ }
+
+ @Test
+ public void testSingleImportMixedCase() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("single_simple_profile_test_mixed_case.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("default", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testMultipleImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("multiple_profile_test.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(2, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("profile1", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODAA7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+
+ profile = importProfiles.get(1);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("profile2", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODBB7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("BBalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+ }
+
+ @Test
+ public void testAssumeRoleSingleImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("assume_role_profile_test.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(2, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("user1", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+
+ profile = importProfiles.get(1);
+ assertTrue(profile instanceof AssumeRoleProfile);
+ AssumeRoleProfile assumeRoleCredentialsProfile = (AssumeRoleProfile) profile;
+ assertEquals("marketingadmin", assumeRoleCredentialsProfile.getName());
+ assertEquals(importProfiles.get(0), assumeRoleCredentialsProfile.getAssumerProfile().get());
+ assertEquals("arn:aws:iam::123456789012:role/marketingadminrole", assumeRoleCredentialsProfile.getRoleArn().get());
+ assertEquals(3600, assumeRoleCredentialsProfile.getDurationSeconds().get());
+ assertEquals("123456", assumeRoleCredentialsProfile.getExternalId().get());
+ assertEquals("Session_Maria_Garcia", assumeRoleCredentialsProfile.getSessionName().get());
+ assertTrue(assumeRoleCredentialsProfile.getSessionPolicy().isEmpty());
+ }
+
+ @Test
+ public void testNestedAssumeRoleImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("nested_assume_role_profile_test.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(4, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof StaticCredentialsProfile);
+ StaticCredentialsProfile staticCredentialsProfile = (StaticCredentialsProfile) profile;
+ assertEquals("static", staticCredentialsProfile.getName());
+ assertEquals("AKIAIOSFODNN7EXAMPLE", staticCredentialsProfile.getAccessKey().get());
+ assertEquals("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", staticCredentialsProfile.getSecretKey().get());
+ assertTrue(staticCredentialsProfile.getSessionToken().isEmpty());
+
+ profile = importProfiles.get(1);
+ assertTrue(profile instanceof AssumeRoleProfile);
+ AssumeRoleProfile assumeRoleCredentialsProfile = (AssumeRoleProfile) profile;
+ assertEquals("assume1", assumeRoleCredentialsProfile.getName());
+ assertEquals(importProfiles.get(0), assumeRoleCredentialsProfile.getAssumerProfile().get());
+ assertEquals("arn:aws:iam::123456789012:role/marketingadminrole", assumeRoleCredentialsProfile.getRoleArn().get());
+ assertEquals(3600, assumeRoleCredentialsProfile.getDurationSeconds().get());
+ assertEquals("123456", assumeRoleCredentialsProfile.getExternalId().get());
+ assertEquals("Session_Maria_Garcia", assumeRoleCredentialsProfile.getSessionName().get());
+ assertTrue(assumeRoleCredentialsProfile.getSessionPolicy().isEmpty());
+
+ profile = importProfiles.get(2);
+ assertTrue(profile instanceof AssumeRoleProfile);
+ assumeRoleCredentialsProfile = (AssumeRoleProfile) profile;
+ assertEquals("assume2", assumeRoleCredentialsProfile.getName());
+ assertEquals(importProfiles.get(1), assumeRoleCredentialsProfile.getAssumerProfile().get());
+ assertEquals("arn:aws:iam::123456789012:role/marketingadminrole", assumeRoleCredentialsProfile.getRoleArn().get());
+ assertEquals(3600, assumeRoleCredentialsProfile.getDurationSeconds().get().intValue());
+ assertEquals("123456", assumeRoleCredentialsProfile.getExternalId().get());
+ assertEquals("Session_Maria_Garcia", assumeRoleCredentialsProfile.getSessionName().get());
+ assertTrue(assumeRoleCredentialsProfile.getSessionPolicy().isEmpty());
+
+ profile = importProfiles.get(3);
+ assertTrue(profile instanceof AssumeRoleProfile);
+ assumeRoleCredentialsProfile = (AssumeRoleProfile) profile;
+ assertEquals("assume3", assumeRoleCredentialsProfile.getName());
+ assertEquals(importProfiles.get(2), assumeRoleCredentialsProfile.getAssumerProfile().get());
+ assertEquals("arn:aws:iam::123456789012:role/marketingadminrole", assumeRoleCredentialsProfile.getRoleArn().get());
+ assertEquals(3600, assumeRoleCredentialsProfile.getDurationSeconds().get().intValue());
+ assertEquals("123456", assumeRoleCredentialsProfile.getExternalId().get());
+ assertEquals("Session_Maria_Garcia", assumeRoleCredentialsProfile.getSessionName().get());
+ assertTrue(assumeRoleCredentialsProfile.getSessionPolicy().isEmpty());
+ }
+
+ @Test
+ public void testExternalCommandImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("external_command_profile_test.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof CommandProfile);
+ CommandProfile commandProfile = (CommandProfile) profile;
+ assertEquals("developer", commandProfile.getName());
+ assertTrue(commandProfile.getKeyId().isEmpty());
+ assertEquals("/opt/bin/awscreds-custom --username helen", commandProfile.getCommand().get());
+ assertEquals(3600, commandProfile.getDurationSeconds().get().intValue());
+
+ }
+
+ @Test
+ public void testExternalCommandNoDurationImport() throws IOException {
+ Path inputPath = parentTestInputFolder.resolve("external_command_profile_no_duration.txt");
+ FileProfileImporter importer = new FileProfileImporter(inputPath);
+ List importProfiles = importer.importProfiles();
+ assertEquals(1, importProfiles.size());
+
+ Profile profile = importProfiles.get(0);
+ assertTrue(profile instanceof CommandProfile);
+ CommandProfile commandProfile = (CommandProfile) profile;
+ assertEquals("developer", commandProfile.getName());
+ assertTrue(commandProfile.getKeyId().isEmpty());
+ assertEquals("/opt/bin/awscreds-custom --username helen", commandProfile.getCommand().get());
+ assertTrue(commandProfile.getDurationSeconds().isEmpty());
+
+ }
+
+}
diff --git a/src/test/java/com/netspi/awssigner/model/persistence/ProfileExporterTest.java b/src/test/java/com/netspi/awssigner/model/persistence/ProfileExporterTest.java
new file mode 100644
index 0000000..37e97df
--- /dev/null
+++ b/src/test/java/com/netspi/awssigner/model/persistence/ProfileExporterTest.java
@@ -0,0 +1,279 @@
+package com.netspi.awssigner.model.persistence;
+
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.netspi.awssigner.model.AssumeRoleProfile;
+import com.netspi.awssigner.model.CommandProfile;
+import com.netspi.awssigner.model.Profile;
+import com.netspi.awssigner.model.StaticCredentialsProfile;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+
+public class ProfileExporterTest {
+
+ private Path tempFile;
+ private ProfileExporter exporter;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ tempFile = Files.createTempFile("ProfileExporterTest", null);
+ exporter = new ProfileExporter(tempFile);
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ Files.deleteIfExists(tempFile);
+ }
+
+ @Test
+ public void testStaticCreds() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ StaticCredentialsProfile exportProfile = new StaticCredentialsProfile("name");
+ exportProfile.setAccessKey("AKIAIOSFODNN7EXAMPLE");
+ exportProfile.setSecretKey("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
+
+ exportProfiles.add(exportProfile);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ StaticCredentialsProfile importProfile = (StaticCredentialsProfile) importProfiles.get(0);
+ assertEquals(exportProfile.getName(), importProfile.getName());
+ assertEquals(exportProfile.getAccessKey().get(), importProfile.getAccessKey().get());
+ assertEquals(exportProfile.getSecretKey().get(), importProfile.getSecretKey().get());
+ }
+
+ @Test
+ public void testStaticCredsWithAllFields() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ StaticCredentialsProfile exportProfile = new StaticCredentialsProfile("name");
+ exportProfile.setAccessKey("AKIAIOSFODNN7EXAMPLE");
+ exportProfile.setSecretKey("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
+ exportProfile.setSessionToken("AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=");
+ exportProfile.setEnabled(false);
+ exportProfile.setInScopeOnly(true);
+ exportProfile.setKeyId("AKIAIOSFODNN8EXAMPLE");
+ exportProfile.setRegion("us-west-2");
+ exportProfile.setService("some-service");
+
+ exportProfiles.add(exportProfile);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ StaticCredentialsProfile importProfile = (StaticCredentialsProfile) importProfiles.get(0);
+ assertEquals(exportProfile.getName(), importProfile.getName());
+ assertEquals(exportProfile.getAccessKey().get(), importProfile.getAccessKey().get());
+ assertEquals(exportProfile.getSecretKey().get(), importProfile.getSecretKey().get());
+ assertEquals(exportProfile.getSessionToken().get(), importProfile.getSessionToken().get());
+ assertEquals(exportProfile.isEnabled(), importProfile.isEnabled());
+ assertEquals(exportProfile.isInScopeOnly(), importProfile.isInScopeOnly());
+ assertEquals(exportProfile.getKeyId().get(), importProfile.getKeyId().get());
+ assertEquals(exportProfile.getRegion().get(), importProfile.getRegion().get());
+ assertEquals(exportProfile.getService().get(), importProfile.getService().get());
+ }
+
+ @Test
+ public void testCommandProfile() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ CommandProfile exportProfile = new CommandProfile("name");
+ exportProfile.setCommand("/opt/bin/awscreds-custom --username will");
+
+ exportProfiles.add(exportProfile);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ CommandProfile importProfile = (CommandProfile) importProfiles.get(0);
+ assertEquals(exportProfile.getName(), importProfile.getName());
+ assertEquals(exportProfile.getCommand().get(), importProfile.getCommand().get());
+ }
+
+ @Test
+ public void testCommandProfileWithAllFields() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ CommandProfile exportProfile = new CommandProfile("name");
+ exportProfile.setCommand("/opt/bin/awscreds-custom --username will");
+ exportProfile.setDurationSeconds(10);
+ exportProfile.setEnabled(false);
+ exportProfile.setInScopeOnly(true);
+ exportProfile.setKeyId("AKIAIOSFODNN8EXAMPLE");
+ exportProfile.setRegion("us-west-2");
+ exportProfile.setService("some-service");
+
+ exportProfiles.add(exportProfile);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ CommandProfile importProfile = (CommandProfile) importProfiles.get(0);
+ assertEquals(exportProfile.getName(), importProfile.getName());
+ assertEquals(exportProfile.getCommand().get(), importProfile.getCommand().get());
+ assertEquals(exportProfile.getDurationSeconds().get(), importProfile.getDurationSeconds().get());
+ assertEquals(exportProfile.isEnabled(), importProfile.isEnabled());
+ assertEquals(exportProfile.isInScopeOnly(), importProfile.isInScopeOnly());
+ assertEquals(exportProfile.getKeyId().get(), importProfile.getKeyId().get());
+ assertEquals(exportProfile.getRegion().get(), importProfile.getRegion().get());
+ assertEquals(exportProfile.getService().get(), importProfile.getService().get());
+ }
+
+ @Test
+ public void testAssumeProfile() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ StaticCredentialsProfile exportProfile1 = new StaticCredentialsProfile("name");
+ exportProfile1.setAccessKey("AKIAIOSFODNN7EXAMPLE");
+ exportProfile1.setSecretKey("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
+
+ exportProfiles.add(exportProfile1);
+
+ AssumeRoleProfile exportProfile2 = new AssumeRoleProfile("name2");
+ exportProfile2.setAssumerProfile(exportProfile1);
+ exportProfile2.setRoleArn("arn:aws:iam::123456789012:role/testrole");
+
+ exportProfiles.add(exportProfile2);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ StaticCredentialsProfile importProfile1 = (StaticCredentialsProfile) importProfiles.get(0);
+ assertEquals(exportProfile1.getName(), importProfile1.getName());
+ assertEquals(exportProfile1.getAccessKey().get(), importProfile1.getAccessKey().get());
+ assertEquals(exportProfile1.getSecretKey().get(), importProfile1.getSecretKey().get());
+
+ AssumeRoleProfile importProfile2 = (AssumeRoleProfile) importProfiles.get(1);
+ assertEquals(exportProfile2.getName(), importProfile2.getName());
+ assertEquals(exportProfile2.getAssumerProfile().get(), importProfile2.getAssumerProfile().get());
+ assertEquals(exportProfile2.getRoleArn().get(), importProfile2.getRoleArn().get());
+ }
+
+ @Test
+ public void testAssumeProfileWithSessionPolicyWithLineBreaks() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ StaticCredentialsProfile exportProfile1 = new StaticCredentialsProfile("name");
+ exportProfile1.setAccessKey("AKIAIOSFODNN7EXAMPLE");
+ exportProfile1.setSecretKey("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
+
+ exportProfiles.add(exportProfile1);
+
+ AssumeRoleProfile exportProfile2 = new AssumeRoleProfile("name2");
+ exportProfile2.setAssumerProfile(exportProfile1);
+ exportProfile2.setRoleArn("arn:aws:iam::123456789012:role/testrole");
+
+ //Set some complex session policy
+ String sessionPolicy = "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"AllowListingOfUserFolder\", \"Action\": [ \"s3:ListBucket\" ], \"Effect\": \"Allow\", \"Resource\": [ \"arn:aws:s3:::${transfer:HomeBucket}\" ], \"Condition\": { \"StringLike\": { \"s3:prefix\": [ \"${transfer:HomeFolder}/*\", \"${transfer:HomeFolder}\" ] } } }, { \"Sid\": \"HomeDirObjectAccess\", \"Effect\": \"Allow\", \"Action\": [ \"s3:PutObject\", \"s3:GetObject\", \"s3:DeleteObject\", \"s3:DeleteObjectVersion\", \"s3:GetObjectVersion\", \"s3:GetObjectACL\", \"s3:PutObjectACL\" ], \"Resource\": \"arn:aws:s3:::${transfer:HomeDirectory}*\" } ]} ";
+ //Parse the session policy text into JSON
+ JsonObject json = JsonParser.parseString(sessionPolicy).getAsJsonObject();
+ //Back to a string with pretty-printing
+ String prettyJson = new GsonBuilder().setPrettyPrinting().create().toJson(json);
+ exportProfile2.setSessionPolicy(prettyJson);
+
+ exportProfiles.add(exportProfile2);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ StaticCredentialsProfile importProfile1 = (StaticCredentialsProfile) importProfiles.get(0);
+ assertEquals(exportProfile1.getName(), importProfile1.getName());
+ assertEquals(exportProfile1.getAccessKey().get(), importProfile1.getAccessKey().get());
+ assertEquals(exportProfile1.getSecretKey().get(), importProfile1.getSecretKey().get());
+
+ AssumeRoleProfile importProfile2 = (AssumeRoleProfile) importProfiles.get(1);
+ assertEquals(exportProfile2.getName(), importProfile2.getName());
+ assertEquals(exportProfile2.getAssumerProfile().get(), importProfile2.getAssumerProfile().get());
+ assertEquals(exportProfile2.getRoleArn().get(), importProfile2.getRoleArn().get());
+
+ //Is the session policy stil the same (ignoring whitespace)?
+ assertEquals(sessionPolicy.replaceAll("\\s+", " ").trim(), importProfile2.getSessionPolicy().get().replaceAll("\\s+", " ").trim());
+ }
+
+ @Test
+ public void testAssumeProfileWithAllFields() throws Exception {
+ List exportProfiles = new ArrayList<>();
+
+ StaticCredentialsProfile exportProfile1 = new StaticCredentialsProfile("name");
+ exportProfile1.setAccessKey("AKIAIOSFODNN7EXAMPLE");
+ exportProfile1.setSecretKey("AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
+
+ exportProfiles.add(exportProfile1);
+
+ AssumeRoleProfile exportProfile2 = new AssumeRoleProfile("name2");
+ exportProfile2.setAssumerProfile(exportProfile1);
+ exportProfile2.setRoleArn("arn:aws:iam::123456789012:role/testrole");
+ exportProfile2.setExternalId("some_ext_id");
+ exportProfile2.setSessionName("my_session_name");
+ exportProfile2.setSessionPolicy("{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"AllowListingOfUserFolder\", \"Action\": [ \"s3:ListBucket\" ], \"Effect\": \"Allow\", \"Resource\": [ \"arn:aws:s3:::${transfer:HomeBucket}\" ], \"Condition\": { \"StringLike\": { \"s3:prefix\": [ \"${transfer:HomeFolder}/*\", \"${transfer:HomeFolder}\" ] } } }, { \"Sid\": \"HomeDirObjectAccess\", \"Effect\": \"Allow\", \"Action\": [ \"s3:PutObject\", \"s3:GetObject\", \"s3:DeleteObject\", \"s3:DeleteObjectVersion\", \"s3:GetObjectVersion\", \"s3:GetObjectACL\", \"s3:PutObjectACL\" ], \"Resource\": \"arn:aws:s3:::${transfer:HomeDirectory}*\" } ]} ");
+ exportProfile2.setDurationSeconds(10);
+ exportProfile2.setEnabled(false);
+ exportProfile2.setInScopeOnly(true);
+ exportProfile2.setKeyId("AKIAIOSFODNN8EXAMPLE");
+ exportProfile2.setRegion("us-west-2");
+ exportProfile2.setService("some-service");
+
+ exportProfiles.add(exportProfile2);
+
+ exporter.exportProfiles(exportProfiles);
+
+ FileProfileImporter importer = new FileProfileImporter(tempFile);
+ List importProfiles = importer.importProfiles();
+
+ assertEquals(exportProfiles.size(), importProfiles.size());
+
+ StaticCredentialsProfile importProfile1 = (StaticCredentialsProfile) importProfiles.get(0);
+ assertEquals(exportProfile1.getName(), importProfile1.getName());
+ assertEquals(exportProfile1.getAccessKey().get(), importProfile1.getAccessKey().get());
+ assertEquals(exportProfile1.getSecretKey().get(), importProfile1.getSecretKey().get());
+
+ AssumeRoleProfile importProfile2 = (AssumeRoleProfile) importProfiles.get(1);
+ assertEquals(exportProfile2.getName(), importProfile2.getName());
+ assertEquals(exportProfile2.getAssumerProfile().get(), importProfile2.getAssumerProfile().get());
+ assertEquals(exportProfile2.getRoleArn().get(), importProfile2.getRoleArn().get());
+ assertEquals(exportProfile2.getDurationSeconds().get(), importProfile2.getDurationSeconds().get());
+ assertEquals(exportProfile2.getExternalId().get(), importProfile2.getExternalId().get());
+ assertEquals(exportProfile2.getSessionName().get(), importProfile2.getSessionName().get());
+ assertEquals(exportProfile2.getSessionPolicy().get().replaceAll("\\s+", " ").trim(), importProfile2.getSessionPolicy().get().replaceAll("\\s+", " ").trim());
+ assertEquals(exportProfile2.isEnabled(), importProfile2.isEnabled());
+ assertEquals(exportProfile2.isInScopeOnly(), importProfile2.isInScopeOnly());
+ assertEquals(exportProfile2.getKeyId().get(), importProfile2.getKeyId().get());
+ assertEquals(exportProfile2.getRegion().get(), importProfile2.getRegion().get());
+ assertEquals(exportProfile2.getService().get(), importProfile2.getService().get());
+ }
+
+}
diff --git a/src/test/resources/CredentialsParserInputs/assume-role_output.txt b/src/test/resources/CredentialsParserInputs/assume-role_output.txt
new file mode 100644
index 0000000..9c0eac1
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/assume-role_output.txt
@@ -0,0 +1,12 @@
+{
+ "AssumedRoleUser": {
+ "AssumedRoleId": "AROA3XFRBF535PLBIFPI6:s3-access-example",
+ "Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"
+ },
+ "Credentials": {
+ "SecretAccessKey": "FTNBND5Q6mEXAMPLEe27V0Pce/03EShqVZTTsLzF",
+ "SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
+ "Expiration": "2016-03-15T00:05:07Z",
+ "AccessKeyId": "ASIAJEXAMPLEXEG2JICA"
+ }
+}
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/assume-role_output_oneline.txt b/src/test/resources/CredentialsParserInputs/assume-role_output_oneline.txt
new file mode 100644
index 0000000..f8e06aa
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/assume-role_output_oneline.txt
@@ -0,0 +1 @@
+{"AssumedRoleUser":{"AssumedRoleId": "AROA3XFRBF535PLBIFPI4:s3-access-example","Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"},"Credentials": {"SecretAccessKey": "FTNBND5Q6mEXAMPLEe27V0Pce/03EShqVZTTsLzF","SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=","Expiration": "2016-03-15T00:05:07Z","AccessKeyId": "ASIAJEXAMPLEXEG2JICA"}}
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/assume-role_output_xml.txt b/src/test/resources/CredentialsParserInputs/assume-role_output_xml.txt
new file mode 100644
index 0000000..bce1b13
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/assume-role_output_xml.txt
@@ -0,0 +1,23 @@
+
+
+DevUser123
+
+
+ AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==
+
+
+ DcCc9H6oCkGUEXAMPLEx8NIfVG8kO2T/3jORxuZY
+
+ 2019-07-15T23:28:33.359Z
+ AKIAIOSFODNN7EXAMPLE
+
+
+ arn:aws:sts::123456789012:assumed-role/demo/John
+ ARO123EXAMPLE123:John
+
+8
+
+
+c6104cbe-af31-11e0-8154-cbc7ccf896c7
+
+
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/assume-role_output_xml_oneline.txt b/src/test/resources/CredentialsParserInputs/assume-role_output_xml_oneline.txt
new file mode 100644
index 0000000..bcff928
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/assume-role_output_xml_oneline.txt
@@ -0,0 +1 @@
+DevUser123AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==DcCc9H6oCkGUEXAMPLEx8NIfVG8kO2T/3jORxuZY2019-07-15T23:28:33.359ZAKIAIOSFODNN7EXAMPLEarn:aws:sts::123456789012:assumed-role/demo/JohnARO123EXAMPLE123:John8c6104cbe-af31-11e0-8154-cbc7ccf896c7
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/cli_configure_example.txt b/src/test/resources/CredentialsParserInputs/cli_configure_example.txt
new file mode 100644
index 0000000..5e43229
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/cli_configure_example.txt
@@ -0,0 +1,5 @@
+$ aws configure
+AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
+AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+Default region name [None]: us-west-2
+Default output format [None]: json
diff --git a/src/test/resources/CredentialsParserInputs/environment_variables.txt b/src/test/resources/CredentialsParserInputs/environment_variables.txt
new file mode 100644
index 0000000..15e731b
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/environment_variables.txt
@@ -0,0 +1,4 @@
+export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
+export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+export AWS_SESSION_TOKEN=AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE
+export AWS_DEFAULT_REGION=us-west-2
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/external_command_example.txt b/src/test/resources/CredentialsParserInputs/external_command_example.txt
new file mode 100644
index 0000000..679ae41
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/external_command_example.txt
@@ -0,0 +1,7 @@
+{
+ "Version": 1,
+ "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
+ "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
+ "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk",
+ "Expiration": "ISO8601 timestamp when the credentials expire"
+}
diff --git a/src/test/resources/CredentialsParserInputs/get-session-token_output.txt b/src/test/resources/CredentialsParserInputs/get-session-token_output.txt
new file mode 100644
index 0000000..132fb61
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/get-session-token_output.txt
@@ -0,0 +1,8 @@
+{
+ "Credentials": {
+ "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
+ "SecretAccessKey": "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",
+ "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
+ "Expiration": "2020-05-19T18:06:10+00:00"
+ }
+}
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/settings_text.txt b/src/test/resources/CredentialsParserInputs/settings_text.txt
new file mode 100644
index 0000000..895ad3b
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/settings_text.txt
@@ -0,0 +1,25 @@
+Global settings
+aws_access_key_id
+Specifies the AWS access key used as part of the credentials to authenticate the command request. Although this can be stored in the config file, we recommend that you store this in the credentials file.
+
+Can be overridden by the AWS_ACCESS_KEY_ID environment variable. You can't specify the access key ID as a command line option.
+
+aws_access_key_id = AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key
+Specifies the AWS secret key used as part of the credentials to authenticate the command request. Although this can be stored in the config file, we recommend that you store this in the credentials file.
+
+Can be overridden by the AWS_SECRET_ACCESS_KEY environment variable. You can't specify the secret access key as a command line option.
+
+aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+aws_session_token
+Specifies an AWS session token. A session token is required only if you manually specify temporary security credentials. Although this can be stored in the config file, we recommend that you store this in the credentials file.
+
+Can be overridden by the AWS_SESSION_TOKEN environment variable. You can't specify the session token as a command line option.
+
+aws_session_token = AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk
+ca_bundle
+Specifies a CA certificate bundle (a file with the .pem extension) that is used to verify SSL certificates.
+
+Can be overridden by the AWS_CA_Bundle environment variable or the --ca-bundle command line option.
+
+ca_bundle = dev/apps/ca-certs/cabundle-2019mar05.pem
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/single_simple_profile_test.txt b/src/test/resources/CredentialsParserInputs/single_simple_profile_test.txt
new file mode 100644
index 0000000..eaf069e
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/single_simple_profile_test.txt
@@ -0,0 +1,3 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/CredentialsParserInputs/single_simple_profile_test_with_session.txt b/src/test/resources/CredentialsParserInputs/single_simple_profile_test_with_session.txt
new file mode 100644
index 0000000..82d6dfc
--- /dev/null
+++ b/src/test/resources/CredentialsParserInputs/single_simple_profile_test_with_session.txt
@@ -0,0 +1,4 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+aws_session_token = AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/assume_role_profile_test.txt b/src/test/resources/FileProfileImportInputs/assume_role_profile_test.txt
new file mode 100644
index 0000000..8606540
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/assume_role_profile_test.txt
@@ -0,0 +1,10 @@
+[profile user1]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+
+[profile marketingadmin]
+role_arn = arn:aws:iam::123456789012:role/marketingadminrole
+source_profile = user1
+duration_seconds = 3600
+external_id = 123456
+role_session_name = Session_Maria_Garcia
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/external_command_profile_no_duration.txt b/src/test/resources/FileProfileImportInputs/external_command_profile_no_duration.txt
new file mode 100644
index 0000000..76e74f6
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/external_command_profile_no_duration.txt
@@ -0,0 +1,2 @@
+[profile developer]
+credential_process = /opt/bin/awscreds-custom --username helen
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/external_command_profile_test.txt b/src/test/resources/FileProfileImportInputs/external_command_profile_test.txt
new file mode 100644
index 0000000..7698945
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/external_command_profile_test.txt
@@ -0,0 +1,3 @@
+[profile developer]
+credential_process = /opt/bin/awscreds-custom --username helen
+duration_seconds = 3600
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/multiple_profile_test.txt b/src/test/resources/FileProfileImportInputs/multiple_profile_test.txt
new file mode 100644
index 0000000..d3e1143
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/multiple_profile_test.txt
@@ -0,0 +1,7 @@
+[profile1]
+aws_access_key_id=AKIAIOSFODAA7EXAMPLE
+aws_secret_access_key=AAalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+
+[profile2]
+aws_access_key_id=AKIAIOSFODBB7EXAMPLE
+aws_secret_access_key=BBalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/nested_assume_role_profile_test.txt b/src/test/resources/FileProfileImportInputs/nested_assume_role_profile_test.txt
new file mode 100644
index 0000000..b63634d
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/nested_assume_role_profile_test.txt
@@ -0,0 +1,24 @@
+[profile assume3]
+role_arn = arn:aws:iam::123456789012:role/marketingadminrole
+source_profile = assume2
+duration_seconds = 3600
+external_id = 123456
+role_session_name = Session_Maria_Garcia
+
+[profile assume2]
+role_arn = arn:aws:iam::123456789012:role/marketingadminrole
+source_profile = assume1
+duration_seconds = 3600
+external_id = 123456
+role_session_name = Session_Maria_Garcia
+
+[profile assume1]
+role_arn = arn:aws:iam::123456789012:role/marketingadminrole
+source_profile = static
+duration_seconds = 3600
+external_id = 123456
+role_session_name = Session_Maria_Garcia
+
+[profile static]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test.txt
new file mode 100644
index 0000000..eaf069e
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test.txt
@@ -0,0 +1,3 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test_mixed_case.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_mixed_case.txt
new file mode 100644
index 0000000..c47c581
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_mixed_case.txt
@@ -0,0 +1,3 @@
+[default]
+AWS_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_SECRET_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test_profile_name.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_profile_name.txt
new file mode 100644
index 0000000..3e24ebd
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_profile_name.txt
@@ -0,0 +1,3 @@
+[profile my-profile]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_config.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_config.txt
new file mode 100644
index 0000000..57c493d
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_config.txt
@@ -0,0 +1,5 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+region=us-west-2
+output=json
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_ignored_extras.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_ignored_extras.txt
new file mode 100644
index 0000000..93be90e
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_ignored_extras.txt
@@ -0,0 +1,6 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+ca_bundle = dev/apps/ca-certs/cabundle-2019mar05.pem
+cli_auto_prompt = on-partial
+cli_binary_format = raw-in-base64-out
\ No newline at end of file
diff --git a/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_session.txt b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_session.txt
new file mode 100644
index 0000000..82d6dfc
--- /dev/null
+++ b/src/test/resources/FileProfileImportInputs/single_simple_profile_test_with_session.txt
@@ -0,0 +1,4 @@
+[default]
+aws_access_key_id=AKIAIOSFODNN7EXAMPLE
+aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
+aws_session_token = AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk
\ No newline at end of file