#!/usr/bin/env python2

'''
This script aims to be the most generic and the most explicit possible.
It works with OWASP ZAP API Python client.
To use it, you have to load the Python API client module and start ZAP

Before starting this script for the first time: Open ZAP, go to
Tools -> Options -> API -> Generate random Key, copy and paste the key in the
variable "apiKey" of the configuration area

This script is divided into two parts : a configuration area, where you have to
change variables according to your needs, and the part with API calls.

Author : aine-rb on Github, from Sopra Steria
'''

import time
from pprint import pprint
from zapv2 import ZAPv2


#######################################
### BEGINNING OF CONFIGURATION AREA ###
#######################################
## The user only needs to change variable values bellow to make the script
## work according to his/her needs. MANDATORY parameters must not be empty

# MANDATORY. Define the API key generated by ZAP and used to verify actions.
apiKey='qiiutul4utrfub1b8veqs50bk0'

# MANDATORY. Define the listening address of ZAP instance
localProxy = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}

# MANDATORY. True to create another ZAP session (overwrite the former if the
# same name already exists), False to use an existing one
isNewSession = True
# MANDATORY. ZAP Session name
sessionName = 'WebgoatSession'

# Define the list of global exclude URL regular expressions. List can be empty.
# The expressions must follow the java.util.regex.Pattern class syntax
# The following example excludes every single URL except http://localhost:8081
globalExcludeUrl = ['^(?:(?!http:\/\/localhost:8081).*).$']

# MANDATORY. Define if an outgoing proxy server is used
useProxyChain = False
# MANDATORY only if useProxyChain is True, ignored otherwise.
# Outgoing proxy address and port
proxyAddress = 'my.corp.proxy'
proxyPort = '8080'
# Define the addresses to skip in case useProxyChain is True. Ignored
# otherwise. List can be empty.
skipProxyAddresses = ('127.0.0.1;'
                      'localhost')
# MANDATORY only if useProxyChain is True. Ignored otherwise.
# Def
ine if proxy server needs authentication
useProxyChainAuth = False
# MANDATORY only if useProxyChainAuth is True. Ignored otherwise
proxyUsername = ''
proxyPasswor
d = ''
proxyRealm = ''

# MANDATORY. Determine if a proxy script must be loaded. Proxy scripts are
# executed for every request traversing ZAP
useProxyScript = False
# MANDATORY only if useProxyScript is True. Ignored otherwise
proxyScriptName = 'proxyScript.js'
# Script engine values: "Oracle Nashorn" for Javascript,
# "jython" for python, "JSR 223 JRuby Engine" for ruby
proxyScriptEngine = 'Oracle Nashorn'
# Asolute local path
proxyScriptFileName = '/zap/scripts/proxy/proxyScript.js'
proxyScriptDescription = 'This is a description'

# MANDATORY. Determine if context must be configured then used during scans.
# You have to set this parameter to True if you want that ZAP performs scans
# from the point of view of a specific user
useContextForScan = True

# MANDATORY only if useContextForScan is True. Ignored otherwise. Set value to
# True to define a new context. Set value to False to use an existing one.
defineNewContext = True
# MANDATORY only if defineNewContext is True. Ignored otherwise
contextName = 'WebGoat_script-based'
# MANDATORY only if defineNewContext is False. Disregarded otherwise.
# Corresponds to the ID of the context to use
contextId = 0
# Define Context Include URL regular expressions. Ignored if useContextForScan
# is False. You have to put the URL you want to test in this list.
contextIncludeURL = ['http://localhost:8081.*']
# Define Context Exclude URL regular expressions. Ignored if useContextForScan
# is False. List can be empty.
contextExcludeURL = ['http://localhost:8081/WebGoat/j_spring_security_logout',
                     'http://localhost:8081/WebGoat/logout.mvc']

# MANDATORY only if useContextForScan is True. Ignored otherwise. Define the
# session management method for the context. Possible values are:
# "cookieBasedSessionManagement"; "httpAuthSessionManagement"
sessionManagement = 'cookieBasedSessionManagement'

# MANDATORY only if useContextForScan is True. Ignored otherwise. Define
# authentication method for the context. Possible values are:
# "manualAuthentication"; "scriptBasedAuthentication"; "httpAuthentication";
# "formBasedAuthentication"
authMethod = 'scriptBasedAuthentication'

# MANDATORY only if authMethod is set to scriptBasedAuthentication.
# Ignored otherwise
authScriptName = 'TwoStepAuthentication.js'
# Script engine values: Oracle Nashorn for Javascript
# jython for python, JSR 223 JRuby Engine for ruby
authScriptEngine = 'Oracle Nashorn'
# Absolute local path
authScriptFileName = '/zap/scripts/authentication/TwoStepAuthentication.js'
authScriptDescription = 'This is a description'

# MANDATORY only if useContextForScan is True. Ignored otherwise. Each
# name/value pair of authParams are expected to be "x-www-form-urlencoded"
# Here is an example for scriptBasedAuthentication method:
authParams = ('scriptName=' + authScriptName + '&'
              'Submission Form URL=http://localhost:8081/WebGoat/j_spring_security_check&'
              'Username field=username&'
              'Password field=password&'
              'Target URL=http://localhost:8081/WebGoat/welcome.mvc')
## Here is an example for formBasedAuthentication method:
#authParams = ('loginUrl=http://localhost:8081/WebGoat/j_spring_security_check&'
#              'loginRequestData=username%3D%7B%25username%25%7D%26'
#              'password%3D%7B%25password%25%7D')
##Here is an example for httpAuthentication method:
#authParams = ('hostname=http://www.example.com&'
#              'realm=CORP\\administrator&'
#              'port=80')

# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Set the value to True if a loggedin indicator must be used. False if it's a
# logged out indicator that must be used
isLoggedInIndicator = False
# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Define either a loggedin or a loggedout indicator regular expression.
# It allows ZAP to see if the user is always authenticated during scans.
indicatorRegex = '\QLocation: http://localhost:8081/WebGoat/login.mvc\E'


# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Set value to True to create new users, False otherwise
createUser = True
# MANDATORY only if createUser is True. Ignored otherwise. Define the list of
# users, with name and credentials (in x-www-form-urlencoded format)
## Here is an example with the script NashornTwoStepAuthentication.js:
userList = [
    {'name': 'guest', 'credentials': 'Username=guest&Password=guest'},
    {'name': 'webgoat', 'credentials': 'Username=webgoat&Password=webgoat'}
]
## Here is an example with formBasedAuthentication:
#userList = [
#    {'name': 'guest', 'credentials': 'username=guest&password=guest'},
#    {'name': 'webgoat', 'credentials': 'username=webgoat&password=webgoat'}
#]

# MANDATORY only if useContextForScan is True. Ignored otherwise. List can be
# empty. Define the userid list. Created users will be added to this list later
userIdList = []

# MANDATORY. Define the target site to test
target = 'http://localhost:8081/WebGoat'

# You can specify other URL in order to help ZAP discover more site locations
# List can be empty
applicationURL = ['http://localhost:8081/WebGoat/start.mvc',
                  'http://localhost:8081/WebGoat/welcome.mvc',
                  'http://localhost:8081/WebGoat/attack']

# MANDATORY. Set value to True if you want to customize and use a scan policy
useScanPolicy = True
# MANDATORY only if useScanPolicy is True. Ignored otherwise. Set a policy name
scanPolicyName = 'SQL Injection and XSS'
# MANDATORY only if useScanPolicy is True. Ignored otherwise.
# Set value to True to disable all scan types except the ones set in ascanIds,
# False to enable all scan types except the ones set in ascanIds..
isWhiteListPolicy = True
# MANDATORY only if useScanPolicy is True. Ignored otherwise. Set the scan IDs
# to use with the policy. O