Package Managers

Add the Agent to a Maven Project

About the Project

The following instructions walks a Java developer through the necessary steps to add the Contrast Java agent to an existing Maven project and reuse the project's existing integration tests to find vulnerabilities. This includes guided changes to an example servlet project. A completed version of the project exists in a GitHub branch.

Before You Start

  1. Install Java 8.
  2. Install git.
  3. Verify your Contrast account connection information.

Step 1: Gather Contrast account information

The Contrast agent requires some configuration to communicate with the Contrast UI. You'll need to obtain these four properties from the Contrast UI:

  • The Contrast URL
  • Your Contrast API key
  • The agent username for your Contrast organization
  • The Service key for your Contrast organization's agent user

The Contrast URL is https://app.contrastsecurity.com/Contrast, or the URL of your on-premises or private cloud instance. You can find the Contrast URL, your API key and agent username by going to the user menu > Organization Settings > API tab in the Contrast UI. You can find your Service key using the link in the API tab, or by navigating to the user menu > Your Account > My Keys section.

Step 2: Create a Contrast configuration file

The Contrast configuration file is a YAML file. Since it contains API credentials, Contrast recommends you create it in a location that only you have access to. For most developers, your home directory is a good choice. Choose a file name that will make sense to you (e.g., .contrast.yml).

  • Create the file and open it in your preferred text editor.

  • Paste in the following contents:

api:
  url: <contrast_url>
  api_key: <your_api_key>
  user_name: <agent_user_name>
  service_key: <agent_user_service_key>
  • Replace <contrast_url>, <your_api_key>, <agent_user_name> and <agent_user_service_key> with the values you obtained from the Contrast UI in the previous step, and save the file.
Configuration hints

You can configure the Contrast Java agent using a file, Java system properties or environment variables. For developers, Contrast recommends putting only the variables that are shared across multiple applications (e.g., credentials and Contrast UI connection details) in this file. That way you can manage them in one place.

Step 3: Clone the examples repository

  • Open a command prompt, and run the following command to clone the examples repository:
$ git clone https://github.com/Contrast-Security-OSS/contrast-java-examples.git
Cloning into 'contrast-java-examples'...
remote: Enumerating objects: 12, done.
remote: Counting objects: 100% (12/12), done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 12 (delta 1), reused 9 (delta 1), pack-reused 0
Unpacking objects: 100% (12/12), done.
  • Then make your working directory the root of the maven-cargo example:
cd contrast-java-examples/maven-cargo

The rest of these instructions are written in the context that you've kept your command prompt open and the working directory is the root of the maven-cargo example.

Step 4: Test and build the project

  • Check to make sure everything starts off in a working state by running the integration test.

The maven-cargo-plugin starts a Jetty server on port 8080, and the EchoServletIT integration test verifies the behavior of the EchoServlet by sending an HTTP request to the Jetty server. Finally, the maven-cargo-plugin shuts down the Jetty server.

$ ./mvnw clean verify
[INFO] Scanning for projects...
[INFO]
[INFO] ---------< com.contrastsecurity.examples:contrast-maven-cargo >---------
[INFO] Building Contrast Maven Cargo Example 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
    ... omitting some output ...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.467 s
[INFO] Finished at: 2019-03-21T22:57:22-04:00
[INFO] ------------------------------------------------------------------------

Note: On Windows, run mvnw.cmd clean verify instead.

  • If this doesn't work, check to make sure you have Java 8 correctly installed.
$ java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

If you had to correct something about your Java installation, try running the tests again. If it still doesn't work, open an issue that explains the problem.

Step 5: Download the Contrast agent

Use the Maven Dependency Plugin to download the agent into the project build directory.

  • Add the following to the properties element of the project POM (pom.xml):
<contrast.version>3.6.3.8220</contrast.version>

You can replace the version and build numbers with those from any Contrast Java agent released to Maven Central.

  • Then add the following to the build.plugins element of the project POM (pom.xml):
<plugin>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.1.1</version>
  <executions>
    <execution>
      <phase>prepare-package</phase>
      <goals>
        <goal>copy</goal>
      </goals>
      <configuration>
        <artifactItems>
          <artifactItem>
            <groupId>com.contrastsecurity</groupId>
            <artifactId>contrast-agent</artifactId>
            <version>${contrast.version}</version>
          </artifactItem>
        </artifactItems>
        <stripVersion>true</stripVersion>
      </configuration>
    </execution>
  </executions>
</plugin>

Step 6: Enable the Contrast agent

Configure the existing Maven Cargo Plugin to include Contrast when starting Jetty.

  • Copy the following configuration element to the start-app-before-IT execution:
<configuration>
  <configuration>
    <properties>
      <cargo.jvmargs>
        -javaagent:${project.build.directory}/dependency/contrast-agent.jar
        -Dcontrast.config.path=${user.home}/.contrast.yml
        -Dcontrast.application.name=maven-cargo-how-to
      </cargo.jvmargs>
    </properties>
  </configuration>
</configuration>
  • Change the value of -Dcontrast.config.path to match the path to the configuration file you created in Step 2.

  • Now re-run the tests. When the application container initializes, you'll see output indicating that Contrast has started.

$ ./mvnw clean verify
[INFO] Scanning for projects...
[INFO]
[INFO] ---------< com.contrastsecurity.examples:contrast-maven-cargo >---------
[INFO] Building Contrast Maven Cargo Example 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
    ... omitting some output ...
[INFO] [talledLocalContainer] [Contrast] Thu Mar 21 23:20:40 EDT 2019 Starting Contrast (build 3.6.2.BACKGROUND) Pat. 8,458,789 B2
    ... omitting more output...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  16.644 s
[INFO] Finished at: 2019-03-21T22:57:22-04:00
[INFO] ------------------------------------------------------------------------

Note: On Windows, run mvnw.cmd clean verify instead.

During the integration test, the agent detects and reports the vulnerable servlet to the Contrast UI. To see the vulnerability report, go to the Vulnerabilities grid in the Contrast UI, and filter your view by the application name maven-cargo-how-to.

Learn More

To integrate Contrast further with your Maven build, check out the Contrast Maven Plugin. You can configure its verify goal to fail your Maven build when vulnerabilities are detected in your test run.

Schedule Automatic Updates on Linux

About Updates with Maven Central

Some users like to automatically update their Contrast Java agent software to the latest version. Linux users can schedule Java agent updates from Maven Central using common Linux tools cron and curl. The following instructions show you how to configure a scheduled Java agent job on an Ubuntu 18.04 Linux host.

Note: Use your preferred editor to create a file with the following contents. The examples provided use tee to create the file.

Before You Start

If you want to perform each step as you follow along with this guide, you can use Vagrant and VirtualBox to create a new Ubuntu 18.04 virtual machine:

vagrant init ubuntu/bionic64
vagrant up
vagrant ssh

Step 1: Install Contrast

  • Create a shared directory for Contrast software:
sudo mkdir -p /opt/contrast
  • Create a script for installing the latest Java agent in the /etc/cron.daily directory. Scripts in this directory execute once daily; as a result, the host updates the latest Java agent each day.

  • Use tee to create this script. Press CTRL+D when you've finished typing all the lines:

$ sudo tee -a /etc/cron.daily/install-latest-contrast-agent > /dev/null
#!/bin/bash -u

CONTRAST_DIRECTORY=/opt/contrast
CONTRAST_FILE_NAME=contrast-agent.jar

curl --fail --silent --location "https://repository.sonatype.org/service/local/artifact/maven/redirect?r=central-proxy&g=com.contrastsecurity&a=contrast-agent&v=LATEST" -o /tmp/$CONTRAST_FILE_NAME
if [ $? -ne 0 ]; then
    echo "Failed to download Contrast Java agent" >&2
    exit 1
fi
mv /tmp/$CONTRAST_FILE_NAME $CONTRAST_DIRECTORY/$CONTRAST_FILE_NAME
  • Set the execute bit on the new script file:
sudo chmod +x /etc/cron.daily/install-latest-contrast-agent
  • To test the script, execute it and then verify that the file exists using stat:
$ sudo /etc/cron.daily/install-latest-contrast-agent
$ stat /opt/contrast/contrast-agent.jar
stat /opt/contrast/contrast-agent.jar
  File: /opt/contrast/contrast-agent.jar
  Size: 10568283        Blocks: 20648      IO Block: 4096   regular file
Device: 801h/2049d      Inode: 256034      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2019-04-11 02:02:01.265775928 +0000
Modify: 2019-04-11 02:24:47.849796936 +0000
Change: 2019-04-11 02:24:47.849796936 +0000
 Birth: -

Step 2: Gather Contrast account information

The Contrast agent requires some configuration to communicate with the Contrast UI. You'll need to obtain these four properties from the Contrast UI:

  • The Contrast URL
  • Your Contrast API key
  • The agent username for your Contrast organization
  • The Service key for your Contrast organization's agent user

The Contrast URL is https://app.contrastsecurity.com/Contrast, or the URL of your on-premises or private cloud instance. You can find the Contrast URL, your API key and agent username by going to the user menu > Organization Settings > API tab in the Contrast UI. You can find your Service key using the link in the API tab, or by navigating to the user menu > Your Account > My Keys section.

Step 3: Configure Contrast

When Contrast is installed on a Linux host, users typically want Contrast-enabled web applications on the host to share basic configuration parameters, such as the ones required to connect to Contrast UI. By convention, Contrast look for configuration in a YAML file at path /etc/contrast/java/contrast_securtiy.yaml on Linux hosts.

  • Create the /etc/contrast/java directory:
sudo mkdir -p /etc/contrast/java
  • Use tee to create the configuration file. Replace <contrast_url>, <your_api_key>, <agent_user_name> and <agent_user_service_key> with the values you obtained from the Contrast UI in the previous step:
$ sudo tee -a /etc/contrast/java/contrast_securtiy.yaml > /dev/null
api:
  url: <contrast_url>
  api_key: <your_api_key>
  user_name: <agent_user_name>
  service_key: <agent_user_service_key>
  • Press CTRL+D when you've finished typing all the lines.

Step 4: Verify the installation

  • Run a diagnostic test to verify that Contrast is installed and properly configured. The host must have Java installed to execute the diagnostic test:
sudo apt install --yes openjdk-11-jre-headless
  • Finally, execute the Java agent's diagnostic test to verify that the agent is installed correctly and can communicate with Contrast UI using the configuration parameters from /etc/contrast/java/contrast_security.yaml:
$ java -jar /opt/contrast/contrast-agent.jar diagnostic
*** Contrast Agent (version 3.6.3-SNAPSHOT)
[!] Attempting to connect to the Contrast TeamServer at https://apptwo.contrastsecurity.com/Contrast (No proxy).
[!] Attempting to resolve domain: apptwo.contrastsecurity.com
        Resolved domain apptwo.contrastsecurity.com to IP Address 52.200.215.12
[+] Client successfully resolved the DNS of the Contrast TeamServer. No proxy needed.
[!] Issuing HTTP request to Contrast...
        Executing request...
        Reading response [200]
        Response size = 4209
        Snippet: <!doctype html> <!--[if gt IE 8]><!--> <html class="no-js" i
[+] Client can connect directly to the Contrast TeamServer. No proxy needed.

Add the Agent to a Gradle Project with Docker

About Contrast with Gradle and Docker

The following instructions walk a Java developer through the necessary steps to add the Contrast Java agent to an existing Gradle project. The example Gradle project uses the Application Plugin and the Docker Plugin to build a Java web application and run JUnit 5 integration tests that verify the web application's behavior. This guide includes the process to include Contrast in the Docker image used for testing so that Contrast Assess analyzes your code during integration testing. A completed version of the project exists in a GitHub branch.

Note: Any part of the following procedures that refer to any form of packaging or distribution are meant for your organization's internal use. Do not distribute Contrast with your application or Docker container outside of your organization. See Contrast's Terms of Service agreement for more information.

Before You Start

  1. Install Java 8.
  2. Install git.
  3. Install Docker.
  4. Obtain a Contrast account.

Step 1: Gather Contrast account information

The Contrast agent requires some configuration to communicate with the Contrast UI. You'll need to obtain these four properties from the Contrast UI:

  • The Contrast URL
  • Your Contrast API key
  • The agent username for your Contrast organization
  • The Service key for your Contrast organization's agent user

The Contrast URL is https://app.contrastsecurity.com/Contrast, or the URL of your on-premises or private cloud instance. You can find the Contrast URL, your API key and agent username by going to the user menu > Organization Settings > API tab in the Contrast UI. You can find your Service key using the link in the API tab, or by navigating to the user menu > Your Account > My Keys section.

Step 2: Configure your environment

Contrast supports multiple ways to configuring the Java agent. As environment variables work well with Docker containers, you'll supply the Contrast agent's configuration using this method.

  • If you're using a Unix-like operating system, create a file for exporting the values obtained in Step 1 as Contrast environment variables.

  • Open a command prompt and run the following command. Replace <contrast_url>, <your_api_key>, <agent_user_name> and <agent_user_service_key> with the values you obtained from the Contrast UI:

$ tee -a ~/.contrastrc > /dev/null
export CONTRAST__API__URL=<contrast_url>
export CONTRAST__API__API_KEY=<your_api_key>
export CONTRAST__API__USER_NAME=<agent_user_name>
export CONTRAST__API__SERVICE_KEY=<agent_user_service_key>
  • Press CTRL+D when you're finished typing all four lines of input to save the values to the $HOME/.contrastrc file.

  • Run the .contrastrc script in the current shell to export the variables to your environment:

$ . ~/.contrastrc

Note: If you're using Windows, refer to Microsoft's documentation to learn how to set environment variables.

Configuration hints

You can configure the Contrast Java agent using a file, Java system properties or environment variables. Contrast recommends using environment variables for credentials and Contrast UI connection details. These values aren't likely to change across the projects in your local development environment. This method is also safer than putting your credentials directly in your build script.

If you close the terminal where you ran the .contrastrc script, you'll have to re-run it when you open a new terminal. Add ~/.contrastrc to the script that initializes your interactive shell to make the configuration persist across terminal sessions. For example, if your shell program is Bash, you can do this by running echo ~/.contrastrc` | tee -a ~/.bashrc.


The rest of these instructions are written in the context that you'll execute further commands from the same terminal used in this step.

Step 3: Clone the examples repository

  • Open a command prompt, and run the following command to clone the examples repository:
$ git clone https://github.com/Contrast-Security-OSS/contrast-java-examples.git
  • Make your working directory the root of the gradle-docker example:
$ cd contrast-java-examples/gradle-docker

The rest of these instructions are written in the context that you execute subsequent commands with gradle-docker as the working directory.

Step 4: Test and build the project

  • Run the tests for this module to make sure everything starts off in a working state:
$ ./gradlew build

BUILD SUCCESSFUL in 3s
4 actionable tasks: 3 executed, 1 up-to-date

Note: On Windows, run gradlew.bat build instead.

  • If this doesn't work, check to make sure you have Java 8 correctly installed:
$ java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

If you had to correct something about your Java installation, try running the tests again. If it still doesn't work, open an issue that explains the problem.

Step 5: Download the Contrast Java agent

  • Add a dependency configuration and declare a dependency on the Contrast Java agent:
configurations {
    contrastAgent
}
def contrast_version = "3.6.3.8220"

dependencies {
    // ... other dependencies omitted
    contrastAgent "com.contrastsecurity:contrast-agent:${contrast_version}"
}
  • Add a task for copying the agent into a directory of the project:
task("copyAgent", type: Copy) {
    from configurations.contrastAgent
    into "${projectDir}/lib"
}

run.dependsOn copyAgent
assemble.dependsOn copyAgent

Step 6: Run the application with Contrast

  • Add the -javaagent property to the JVM arguments passed to the application by modifying the application block of build.gradle:
application {
  // ... rest of block omitted
  def agentBuildPath = "lib/contrast-agent-${contrast_version}.jar"
  def agentProjectPath = Paths.get(getProjectDir().toURI()).resolve(agentBuildPath)


  applicationDefaultJvmArgs = [
          "-javaagent:${agentProjectPath.toString()}"
  ]
}
  • Run the application:
$ ./gradlew run

Note: On Windows, run gradlew.bat run instead.

The application will now start up with Contrast. If you do any manual testing, any security related findings are reported to the Contrast UI. You can press CTRL+C to stop the application.

Step 7: Include Contrast in the Distributable

  • Configure the Distribution Plugin to include the Contrast agent JAR in the bundles created when you run gradle build. (The Distribution Plugin was included when you included the Application Plugin.)
application {

  // ... rest of application config omitted

  distributions {
    main {
      contents {
        from("${projectDir}/lib") {
            into "lib"
        }
      }
    }
  }
}

When Gradle generates the start scripts, it includes the JVM args when starting the application. However, -javaagent points to a JAR file in your project directory, not the JAR file in the application bundle.

  • To point to the correct JAR file, configure the startScripts task to perform some string surgery on the scripts after they're generated:
application {

  // ... rest of application config omitted

  startScripts {
    doLast {
      def shFile = new File(getOutputDir(), project.name)
      shFile.text = shFile.text.replace(agentProjectPath.toString(), "\$APP_HOME/${agentBuildPath}")
      def batFile = new File(getOutputDir(), "${project.name}.bat")
      batFile.text = batFile.text.replace(agentProjectPath.toString(), "%APP_HOME%\\lib\\contrast-agent-${contrast_version}.jar")
    }
  }
}
  • Pass the configuration variables into the container by adding the following commands to the createContainer task in build.gradle:
task createContainer(type: DockerCreateContainer) {
    // ... rest of the config omitted

    envVars = [
        CONTRAST__API__URL: System.getenv("CONTRAST__API__URL"),
        CONTRAST__API__USER_NAME: System.getenv("CONTRAST__API__USER_NAME"),
        CONTRAST__API__SERVICE_KEY: System.getenv("CONTRAST__API__SERVICE_KEY"),
        CONTRAST__API__API_KEY: System.getenv("CONTRAST__API__API_KEY"),
        CONTRAST__APPLICATION__NAME: "${project.name}-how-to"
    ]
}
  • Finally, run the build again:
./gradlew clean build

Note: On Windows, run gradlew.bat clean build instead.

The Docker container now runs the application with Contrast enabled. When the integration test runs, it detects the vulnerable endpoint and reports it to the Contrast UI. To see the vulnerability report, log in to the Contrast UI, navigate to the Vulnerabilities grid, and filter your view by the application name gradle-docker-how-to.

Learn More

To integrate Contrast further with your Gradle build, check out the Contrast Gradle Plugin. You can configure its contrastVerify task to fail your Gradle build when Contrast detects vulnerabilities in your test run.