Sonatype Platform Plugin for Jenkins - Lifecycle
Sonatype Platform Plugin for Jenkins (previously known as the Nexus Platform Plugin for Jenkins) integrates Jenkins with Lifecycle to perform SCA open-source evaluations during the application build and to push the CI analysis back to CSM pull request.
This integration also works with Nexus Repository.
Prerequisites
Sonatype Platform Plugin for Jenkins uses the HTTP proxy setting defined in Jenkins under Manage Jenkins > Manage Plugins > Advanced. To bypass the HTTP proxy server you must update the non-proxy host to include the IQ Server.
Installation
Download latest version:
Install through the Jenkins UI
Download the most recent version of the plugin.
Sign in to Jenkins as an administrator.
Navigate to the Manage Jenkins > Plugins page.
Click on the Advanced tab.
Choose the
.hpi
file you previously downloaded.Optionally you may enter the URL to the archive file under the Deploy Plugin section.
Deploy the plugin.
Install through the Jenkins Plugin Manager
Sign in to Jenkins as an administrator.
Navigate to Manage Jenkins.
In the System Configuration section, click on Plugins.
In available plugins, search and install the UpdateSites Manager plugin.
Once installed, navigate to Manage Jenkins.
In the Uncategorized section, click on Manage UpdateSites.
Click on Add → Update Site, and enter the required information:
ID: sonatype-update-site.
Note
'sonatype-update-site' must be used as stated. This ID is essential for system functionality and must not be altered or renamed.
URL:
https://download.sonatype.com/integrations/jenkins-uc/update-center.json
Mark the checkbox "Need CA Certificate" and paste the following certificate:
-----BEGIN CERTIFICATE----- MIIDHzCCAgegAwIBAgIJAP+lqAK85t4HMA0GCSqGSIb3DQEBCwUAMCYxCzAJBgNVBAYTAlVTMRcwFQYDVQQKDA5Tb25hdHlwZSwgSW5jLjAeFw0yNDA0MTYyMDI3MzNaFw0yNzA0MTYyMDI3MzNaMCYxCzAJBgNVBAYTAlVTMRcwFQYDVQQKDA5Tb25hdHlwZSwgSW5jLjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOSSYo277GaxCRlk9/waQ+ytNU/suCqb8SlGeAWHpleZFwvFVxxG0MU1nEI7tgKCXoyXMdbM/bXFgTzjthAOcgNQaAFDY4aUO6DPjPxMv3FTHn4FqdCfL+zEBSzmMD9R3wwblRjcnhc0c5pq+2+jopu0no0nmvEo/KczPnDfmCS90v87ACkNMcVEaIe+AYDgBGMLcY3QeouEsLnKE6FNnovzyW8h8kBRHWiolgDlA6J0KRpqOKfpdtYrA22YzhsSw7WX4Tj2rZDhHmlZ6tT3zkXHM5evXR7H9aMalF+LVhg2ShUhCIfxVpKgvLd80N39+iBOvT02/7DsB2WaYvr6TxECAwEAAaNQME4wHQYDVR0OBBYEFIzUBWpQAwcpuPr94D7k9SMTGEV2MB8GA1UdIwQYMBaAFIzUBWpQAwcpuPr94D7k9SMTGEV2MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFkrkGZ+PoZ5JGM0rin7pCk/1e2dCeeh3/uMaQQ0QYyC4jMbsYfid/V8io2AQLujOUt9TLhNvRDIaFanUBfBdw9deHTrJf4Zm45FQGbytDOgOcF4hZ58yBjJv+Fs9ARFmF3rkWjWDcnIE9eNeXv82UD+lDyTEVH88Sb6qddkOHnAMT7dwCVDpxycWYWpPmwPM7Yf6a+shshPJqveD65RyJbolk4u49owJ3hYpLwmPvDfN9sxaqRVrdKg3RnYWf+faU1bMGXQEj/0tIipHvYuDzOCTGC587zByu589SHYjEPg2i7ud1EYXkeb7nEjfsYUzum3jGx7u1MDQ5RaxPyNxyA= -----END CERTIFICATE-----
Click Apply and Save.
Navigate to Manage Jenkins → Plugins page.
In the Plugin Manager window, select the Available plugins tab and enter "Nexus Platform Plugin" in the search box.
Note
If the plugin does not appear after adding the new site, try clicking the refresh button at the top right corner.
Mark the Install checkbox to select the Nexus Platform Plugin and click the Install button at the top right corner.
Success messages will appear as the plugin and its extensions are installed.
Install Using Alternative Methods
Sonatype Platform Plugin for Jenkins can be installed using the Jenkins CLI.
Configuration
Jenkins can be configured to connect with one or more instances of IQ Server to use when evaluating your application builds. The first instance in the list is used by default.
The configured user for IQ Server must have the Evaluate Application permission. We recommend creating a Jenkins service account and using tokens to reduce the risk of exposing credentials.
Sign in to Jenkins as an administrator.
Navigate to the Manage Jenkins > System.
In the Sonatype Nexus section, select Nexus IQ Server from the Add Nexus IQ Server drop-down menu and enter the following information:
Display Name: The name used to select an IQ Server instance.
Server ID: ID to specify an IQ Server instance in pipeline builds.
Server URL: The location of the IQ Server.
Credentials:
Click Add and select Jenkins.
On the modal, enter the IQ Server username and password. Click Add.
Note
You can learn more about user roles in the Sonatype Lifecycle documentation.
Select the credentials from the drop-down list.
Click the Test Connection button. If the connection is successfully established, you'll see a confirmation message.
The IQ report summary is embedded in Jenkins build reports. Optionally, select the 'Hide embedded reports in Jenkins' checkbox to only link to the report.
Click the Save button.
Adding an Evaluation to a Build
Pipeline refers to both Declarative and Scripted Jenkins Pipelines.
Project (or Job) refers to a Jenkins item, such as a Freestyle project, Multi-configuration project, or Maven project, that allows selecting an explicit build step from a drop-down menu and filling in form field values inside the build configuration.
The scan patterns supported by default are **/*.jar, **/*.war, **/*.ear, **/*.zip, **/*.tar.gz.
To use other patterns, a manual override of iqScanPatterns
is required, as described in the pipeline build step below.
Adding Pipeline Build Step
Use the following steps to add a Lifecycle Policy Evaluation build step to a pipeline build:
On the Pipeline project page, click Pipeline Syntax in the left menu to open the Snippet Generator.
In Snippet Generator > Steps, under Sample Step, select nexusPolicyEvaluation: Invoke Lifecycle Policy Evaluation.
Fill in the values for the policy evaluation.
Click the Generate Pipeline Script button.
Copy the generated script and paste it into the desired stage of your pipeline script.
Example Pipeline Script
nexusPolicyEvaluation( iqApplication: 'SampApp', iqInstanceId: 'MyIQServer1', iqStage: 'build' )
Example Pipeline Script with Scan Patterns to Override Defaults
nexusPolicyEvaluation( iqApplication: 'SampApp', iqInstanceId: 'MyIQServer1', iqScanPatterns: [[scanPattern: '**/*.js'], [scanPattern: '**/*.zip']], iqStage: 'build', iqOrganization: '55040769ec08424e84049356a3362d07' )
The scan patterns support exclude patterns. The exclude patterns start with a '!' character and must be specified after all other included patterns. For example, the following scan patterns will consider for evaluation all files except those under the '.git' directory:
iqScanPatterns: [[scanPattern: '**'], [scanPattern: '!.git/**']]
Example Pipeline Script Overriding Most Advanced Options
nexusPolicyEvaluation( advancedProperties: 'test=value', enableDebugLogging: true, failBuildOnNetworkError: true, failBuildOnScanningErrors: true, iqApplication: selectedApplication('sandbox-application'), iqInstanceId: 'MyIQServer1', iqModuleExcludes: [[moduleExclude: '**/module-2-exclude/module.xml'], [moduleExclude: '**/module-1-exclude/module.xml']], iqScanPatterns: [[scanPattern: '**/other/*.jar'], [scanPattern: '**/special/*.jar']], iqStage: 'build', jobCredentialsId: 'iq-server-localhost' )
Adding Project Step
Use the following steps to add a Lifecycle Policy Evaluation build step to a project:
On the project page, click Configure in the left menu.
Click Build Steps.
Click the Add Build Step button.
Select Invoke Nexus Policy Evaluation.
Fill in the values for the policy evaluation.
Click Save.
Policy Evaluation Values and Advanced Options
IQ Instance: Select an IQ Server that will be used to run the policy evaluation.
Stage: Select Develop, Source, Build, Stage Release, Release, or Operate. This controls the stage the policy evaluation is run against on the IQ Server. Only the stages you are licensed to appear in the list.
Note
The severity of the IQ Server Policy Actions for a Stage determines the final build result. A Warn action equates to an UNSTABLE build. A Fail action equates to a FAILURE.
Organization (optional): Select an organization from the list. If automatic application creation is enabled and the application does not exist, it will be created under the selected organization. If both the application and the organization IDs are provided, and the application already exists under a different organization, the evaluation process stops with an error message. This mechanism is in place to prevent accidental configurations, which could unintentionally alter the evaluation history of existing applications.
Application: Select an application from the list of available IQ Server applications. This determines the policy elements (policies, labels, and license threat groups) to associate with this build and is managed via the IQ Server. An application can also be specified that is not on the list. If automatic application creation is enabled, an application with the specified ID will automatically be created if it does not already exist in the IQ Server.
Scan Targets: By default, the plugin scans all supported files (
**/*.jar, **/*.war, **/*.ear, **/*.zip, **/*.tar.gz
) in the workspace. Any special non-archive files like manifests may incur special handling depending on the version of the plugin used. Each scan target field takes an Apache Ant-styled pattern (i.e. **/*.js). Supplying custom scan targets will limit scanning to only those files matching the scan targets. Only one scan target can be placed on each line.Reachability Analysis: If enabled, this feature will identify vulnerable components that can be reached by executing the application.
Advanced Options:
Module excludes in workspace: Here you can exclude any of the
module.xml
files from evaluation. Module Excludes takes Apache Ant-styled patterns (i.e. **/sonatype-clm/module.xml). Once you define your module excludes, click Add.Note
Module Excludes is only for excluding
module.xml
files generated by Sonatype CLM for Maven and is not an option for excluding scan targets.Fail build when unable to communicate with IQ Server:
failBuildOnNetworkError
- Enabling the option will fail the build when the IQ Server is unreachable.Fail build when there are scanning errors:
failBuildOnScanningErrors
- Enabling this option will fail the build when there are scanning errors, e.g. malformed files that could not be read.Unstable build when there are scanning warnings:
unstableBuildOnScanningWarnings
- Disabling this option will mark the Jenkins job asSUCCESS
instead ofUNSTABLE
if the policy evaluation has alerts with a warn action. The option is enabled by default.Use job specific credentials: This allows overriding the global credential configuration with job-specific authentication credentials. Select any of the existing credentials or click Add and select Jenkins to open the Jenkins Credentials Provider pop-up.
Enable debug logging: Increase the verbosity of the plugin-specific job logging to aid in diagnosing scanning problems or verifying scanning configuration.
Advanced properties: In a few cases, Sonatype support may provide additional parameters to the plugin using this input.
Evaluating Docker Images
Use the container prefix in the scan pattern to scan the docker images you want to scan.
nexusPolicyEvaluation iqApplication: 'appId', iqInstanceId: 'MyIQServer1', iqScanPatterns: [[scanPattern: 'container:namespace/image:image-tag']], iqStage: 'build'
Reviewing Evaluation Results
Once the build is complete, a summary is shown on the project page. The three boxes (red, orange, and yellow) located below the link give you counts for policy violations and are based on the associated severity (critical, severe, and moderate).
In addition to the summary, a historical graph is shown to indicate policy health over time.
The Application Report is accessible from the summary by clicking "view report" or "Lifecycle Policy Evaluation" in the left-hand navigation. Additionally, a Build Report is available within Jenkins by clicking the "IQ Build Report" in the left-hand navigation. This build report shows which components caused a 'warn' or 'fail' action on a particular build.
If you are looking for previous report results, navigate to a specific build report in the Build History. Click on the link View Report to view the build report in IQ Server.
Returned Pipeline Stage Statuses
When an evaluation is performed by the plugin, the stage status depends on the configured policy actions.
Jenkins shows
unstable
for the build when the policy action is set toWARN
Jenkins shows
failed
for the build when the policy action is set toFAIL
When the policy action is set to
No Action
, discovered policy violations will have no effect on the Jenkins build state.
Use the variable currentBuild.result
to examine the value returned within the pipeline script.
def evaluation = nexusPolicyEvaluation failBuildOnNetworkError: false, iqApplication: '18776', iqStage: 'build' echo "currentBuild.result ${currentBuild.result}"
Using Policy Evaluation Results
Utilizing the Sonatype for Jenkins plugin provides full component intelligence and the ability to run policy against your application. Jenkins pipelines let you invoke a build step as part of the build process and use the results for complex workflows. For example, objects returned from a build pipeline step can be used to provide feedback in the application about the process of an evaluation.
Note
The following is just an example of how to code using the policy evaluation results. If you need to incorporate this feature in your pipeline, we recommend using the Automated Commit Feedback capability.
Example: Set up a pipeline build that uses the results of a policy evaluation to push data to a GitHub pull request.
Start a new Jenkins pipeline job for a Maven build.
Add a build stage that calls Maven clean package, wrapped in a few GitHub status updates. For this example, consider sending an update pending when we start the build and have it update the status to indicate if the build succeeded:
stage('Build') { postGitHub commitId, 'pending', 'build', 'Build is running' try { sh "${mvnHome}/bin/mvn clean package" postGitHub commitId, 'success', 'build', 'Build succeeded' } catch (error) { postGitHub commitId, 'failure', 'build', 'Build failed' throw error } }
Add a call to the GitHub API to update the status. To do this, set and declare the
gitHubApiToken
andproject
variables and then create the following function:def postGitHub(commitId, state, context, description, targetUrl) { def payload = JsonOutput.toJson( state: state, context: context, description: description, target_url: targetUrl ) sh "curl -H \"Authorization: token ${gitHubApiToken}\" --request POST --data '${payload}' https://api.github.com/repos/${project}/statuses/${commitId} > /dev/null" }
After the build, we need to run a Lifecycle Analysis to determine the policy evaluation results. This will let GitHub know Lifecycle Analysis is running and then do the policy evaluation.
The easiest way to do this is by using the Jenkins Pipeline Syntax helper to generate a Groovy script:
Click the Pipeline Syntax link on your build configuration screen to open the Pipeline Syntax helper. Select nexusPolicyEvaluation as the sample step, select the IQ instance, stage and application you’d like to evaluate against, and then click Generate Pipeline Script. Copy the script and paste it into your pipeline script.
To process the evaluation results, set a
policyEvaluation
variable to the result. Like with the build, you’ll want to look at whether the build result is a failure or not to determine how to update your GitHub pull request. You can also add a link to the Application Composition Report. Having this available in your pull request lets you go directly to the evaluation, see why it failed, and perform remediation. An example Lifecycle Analysis script is shown below:stage('Lifecycle Analysis') { postGitHub commitId, 'pending', 'analysis', 'Lifecycle Analysis is running' try { def policyEvaluation = nexusPolicyEvaluation iqApplication: 'webgoat', iqInstanceId: 'MyIQServer1', iqStage: 'build' postGitHub commitId, 'success', 'analysis', 'Lifecycle Analysis succeeded', "${policyEvaluation.applicationCompositionReportUrl}" } catch (error) { def policyEvaluation = error.policyEvaluation postGitHub commitId, 'failure', 'analysis', 'Lifecycle Analysis failed', "${policyEvaluation.applicationCompositionReportUrl}" throw error } }
Save your pipeline and then run the build. When the build has been completed, you should see successful steps for Build and Lifecycle Analysis. In your GitHub pull request, you will see the successful checks and you can click the details link to view your report and address alerts or reevaluate policy.
Note
When you access various properties on objects in a pipeline build, Jenkins has security permissions that restrict unauthorized use. In Manage Jenkins navigate to In-process Script Approval and approve scripts (i.e., application composition report, affected component count) for the analysis to run. Lack of script approvals will result in errors like:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to
use method com.sonatype.nexus.api.iq.ApplicationPolicyEvaluation getApplicationCompositionReportUrl
In the above example, we utilized cURL to interact with the GitHub API and provide analysis feedback to GitHub. Many companies use GitHub for code review, and noting the status of CI builds in your pull request is a powerful analysis tool.
In addition to GitHub, you can use the object returned from the policy evaluation with almost anything that provides an interactive API or other Jenkins plugins.
A nexusPolicyEvaluation Pipeline step returns an evaluation result data model from which your Pipeline script may read additional information:
Pipeline application policy evaluation data model
public class ApplicationPolicyEvaluation { private final List<PolicyAlert> policyAlerts; private final int affectedComponentCount; private final int criticalComponentCount; private final int severeComponentCount; private final int moderateComponentCount; private final String applicationCompositionReportUrl; } public class PolicyAlert { private final PolicyFact trigger; private final List<? extends Action> actions; } public class Action { private final String actionTypeId; private final String target; private final String targetType; } public class PolicyFacts { private final String policyId; private final String policyName; private final int threatLevel; }
Reachability Analysis (Previously Call Flow Analysis)
Reachability Analysis detects method signatures in the application code that contain components (belonging to the Maven ecosystem) with potentially exploitable security vulnerabilities and are in the execution path. The policy violations occurring due to such components, will be assigned the status of Reachable
on the application report. Clicking on the policy violation gives the details of the implicated component.
This helps developers prioritize the remediation of such policy violations by replacing the vulnerable components that are reachable by executing the application.
For more details refer to Reachability Analysis.
This configuration is suitable for Pipeline, Multi-branch Pipeline, or any other build types that make use of the Jenkins pipeline (including using Jenkinsfile).
Enabling Reachability Analysis
To enable Reachability Analysis via the Jenkins plugin, you must first install the Jenkins plugin in the Jenkins instance in charge of running the project pipelines.
Example Pipeline Script Enable Reachability Analysis
nexusPolicyEvaluation( // ... iqScanPatterns: [ [scanPattern: '**/target/sonatype-clm/module.xml'], ], callflow: [ enable: true ] )
The table below details the properties in the example script above.
Name | Type | Description |
---|---|---|
Required: Yes | Boolean | Enable Reachability Analysis |
Required: No Default:IQ Scan Patterns | List<String> | See: Includes |
The evaluation report will show a Reachable policy violation as below: