def create_workspace(app_info):
    app_id = app_info['guid']
    app_name = app_info['profile']['name']
    app_teams = app_info['profile']['teams']

    workspace_name = get_workspace_name(app_name)
    log.info('Application name "{}" will have workspace name "{}" due to workspace naming requirements'.format(app_name,workspace_name))

    #check to see if workspace already exists
    existing_workspace = vapi().get_workspace_by_name(workspace_name)

    if ((existing_workspace != []) and (existing_workspace[0].get('id','') != '')):
        warning = "There is already a workspace named {} for application guid {}".\
            format(workspace_name, app_id)
        log.warning(warning)
        print(warning)
        return 0

    #create the workspace with the SCA API
    workspace_guid = vapi().create_workspace(workspace_name)

    #assign the teams with the SCA API
    if app_teams != []:
        for team in app_teams:
            team_id = team['team_id']
            vapi().add_workspace_team(workspace_guid,team_id)

    success = "Created workspace named {} with {} teams".format(workspace_name, len(app_teams))
    log.info(success)
Example #2
0
def update_user(userinfo,role):
    userguid = userinfo["user_id"]

    # API users don't have Security Labs access, and don't try to assign to users who already have the role
    if check_for_api_user(userinfo):
        print("Skipping API user",userguid)
        return 0
    if check_for_role(userinfo, role):
        print("Skipping user",userguid,"as role is already present")
        return 0

    ignoreteamrestrictions = 0

    if check_for_teams(userinfo) == 0:
        #check to see if we have an Ignores Team Restrictions bit
        if ((check_for_role(userinfo, "extseclead") == None) 
            or (check_for_role(userinfo,"extexecutive") == None))
            or (check_for_role(userinfo,"extadmin") == None):
            ignoreteamrestrictions = 1

        if ignoreteamrestrictions == 0:
            print("Cannot assign role to user",userguid,"as user has no assigned teams")
            return 0

    roles = construct_user_roles(userinfo,role)
    vapi().update_user(userguid,roles)
    print("Updated user",userguid)

    return 1
Example #3
0
def get_findings(app_info, cwes: List[int], categories: List[int]):
    log.info('Getting findings for application {} (guid {})'.format(
        app_info['profile']['name'], app_info['guid']))
    all_findings = []

    if cwes != None:
        for cwe in cwes:
            params = {'cwe': cwe}
            these_findings = vapi().get_findings(app_info['guid'],
                                                 scantype='DYNAMIC',
                                                 annot='FALSE',
                                                 request_params=params)
            all_findings.extend(these_findings)
    elif categories != None:
        for cat in categories:
            params = {'finding_category': cat}
            these_findings = vapi().get_findings(app_info['guid'],
                                                 scantype='DYNAMIC',
                                                 annot='FALSE',
                                                 request_params=params)
            all_findings.extend(these_findings)
    else:
        these_findings = vapi().get_findings(app_info['guid'],
                                             scantype='DYNAMIC',
                                             annot='FALSE')
        all_findings.extend(these_findings)

    return all_findings
Example #4
0
def get_incomplete_sandbox_scans(this_app_guid, this_app_id):
    sandboxes = vapi().get_app_sandboxes(this_app_guid)

    sandboxscancount = 0

    for sandbox in sandboxes:
        log.debug(
            "Checking sandboxes for application guid {}".format(this_app_guid))
        #check sandbox scan list, need to fall back to XML APIs for this part
        sandboxscancount = 0
        sandboxid = sandbox.get('id')
        data = vapi().get_build_info(
            app_id=this_app_id,
            sandbox_id=sandboxid)  #returns most recent build for sandbox

        builds = etree.fromstring(data)
        buildid = builds[0].get('build_id')
        log.debug("Checking application guid {}, sandbox {}, build {}".format(
            this_app_guid, sandboxid, buildid))
        status = builds[0].get('results_ready')

        if status == 'false':
            log.info(
                "Status for sandbox scan {} in sandbox id {} for application {} was {}"
                .format(buildid, sandboxid, this_app_guid, status))
            sandboxscancount += 1

    return sandboxscancount
def delete_workspace(workspace):
    projects = get_project_count(workspace)
    if projects == 0:
        log.info("Deleting workspace {} (ID {})".format(workspace['name'],workspace['id']))
        vapi().delete_workspace(workspace['id'])
        return 1
    else:
        log.info("Skipping workspace {} (ID {}) with {} projects".format(workspace['name'],\
            workspace['id'],projects))
        return 0
def get_latest_build(guid):
    # Assumes last build is the one to mitigate. Need to check build status
    app = vapi().get_app(guid)
    legacy_id = app['id']
    build_list = vapi().get_build_list(legacy_id)
    build_list_root = etree.fromstring(build_list)
    builds = []
    for build in build_list_root:
        builds.append(build.get('build_id'))

    #builds.sort() #we can actually have builds out of order if they are created in a different order than published

    return builds[len(builds) - 1]
def create_team(teamname, businessunit=""):
    # we will check to see if we already have a team with this name and just return it, if so
    existingteam = find_team_named(teamname)
    if len(existingteam) > 0:
        teamguid = existingteam[0]["team_id"]
        log.info("Found team named {} with guid {}".format(teamname, teamguid))
        return teamguid

    if businessunit == "":
        r = vapi().create_team(team_name=teamname)
    else:
        r = vapi().create_team(team_name=teamname, business_unit=businessunit)
    return r["team_id"]
Example #8
0
def main():
    parser = argparse.ArgumentParser(
        description='This script adds the specified User role for existing users. It can operate on one user '
                    'or all users in the account.')
    parser.add_argument('-u', '--user_id', required=False, help='User ID (GUID) to update. Ignored if --all is specified.')
    parser.add_argument('-l', '--all', required=False, help='Set to TRUE to update all users.', default="true")
    parser.add_argument('-r', '--role', required=False, help='One of SECLAB (default), IDESCAN, ELEARN.', default='SECLAB')
    args = parser.parse_args()

    target_user = args.user_id
    all_users = args.all 
    role = args.role

    if args.role == 'SECLAB':
        role = 'securityLabsUser'
    elif args.role == 'IDESCAN':
        role = 'greenlightideuser'
    elif args.role == 'ELEARN':
        role = 'extelearn'
    else:
        print("Role", role, "is not supported. Role must be one of SECLAB, IDESCAN, ELEARN.")
        return 0

    # CHECK FOR CREDENTIALS EXPIRATION
    creds_expire_days_warning()

    count=0

    if all_users.lower() == "true":
        data = vapi().get_users()
        print("Reviewing",len(data),"total users...")
        for user in data:
            userguid = user["user_id"]
            # skip deleted users
            if user["deleted"] == "true":
                print("Skipping deleted user",userguid)
                return 0

            data2 = vapi().get_user(userguid)

            count += update_user(data2,role)
            next
    elif target_user is None:
        print("You must specify a --user_id (guid) if --all is not specified.")
        exit
    else:
        user = vapi().get_user(target_user)
        count += update_user(user,role)

    print("Added role to",count,"users")
Example #9
0
def generate(period, from_date, to_date, scan_type):
    params = {}

    # parse args
    if period == 'last-day':
        period = 'yesterday'
    elif period == 'last-week':
        period = 'last_week'
    elif period == 'last-month':
        period = 'last_month'
    elif period == 'all-time':
        period = None

    if period == 'range':
        period = None
        if not (from_date == None):
            params['from_date'] = from_date
        if not (to_date == None):
            params['to_date'] = to_date

    if not (period == None):
        params['period'] = period

    if not (scan_type == None):
        params['scan_type'] = scan_type

    if params == {}:
        paramsobject = None
    else:
        paramsobject = params

    # Initiate the Archer report generation job with provided parameters, returns a token
    requestdata = vapi().generate_archer(payload=paramsobject)

    return gettoken(requestdata)
def main():
    parser = argparse.ArgumentParser(
        description=
        'This script sets any expiring sandboxes in the scope to auto-recreate. It can operate on one application '
        'or all applications in the account.')
    parser.add_argument(
        '-a',
        '--app_id',
        required=True,
        help='App ID to update. Ignored if --all is specified.')
    parser.add_argument('-l',
                        '--all',
                        action='store_true',
                        help='Set to TRUE to update all applications.')
    args = parser.parse_args()

    target_app = args.app_id
    all_apps = args.all

    # CHECK FOR CREDENTIALS EXPIRATION
    creds_expire_days_warning()

    if all_apps:

        data = vapi().get_apps()

        print('Evaluating {} applications for update'.format(len(data)))
        for app in data:
            iterations = process_app(app["id"])
            if iterations > 0:
                print("==>Updated {} sandboxes".format(iterations))
    else:
        print("Evaluating application id {} for update".format(target_app))
        iterations = process_app(target_app)
        print("==>Updated {} sandboxes".format(iterations))
def main():
    parser = argparse.ArgumentParser(
        description='This script sets up a new workspace in Veracode SCA for the application profile(s) \
            specified in the arguments, and assigns teams based on the application profile settings.')
    parser.add_argument('-a', '--app_id', help='App GUID for which to set up a workspace. Ignored if -l is provided.')
    parser.add_argument('--all', action="store_true", help='If specified, set up workspaces for all applications.')
    parser.add_argument('--cleanup', action="store_true", help='If specified, delete all workspaces with no projects.')
    args = parser.parse_args()

    # CHECK FOR CREDENTIALS EXPIRATION
    creds_expire_days_warning()

    # set up args

    app_id = args.app_id
    app_all = args.all
    cleanup = args.cleanup

    if app_all:
        apps = vapi().get_apps()
        print("Evaluating {} applications for workspace creation".format(len(apps)))

        for app_info in apps:
            create_workspace(app_info)
    elif cleanup:
        delete_workspaces()
    else:
        if app_id == None:
            print('You must provide an app_id or set --all or --cleanup to "TRUE".')
            return 0
        
        app_info = get_app_info(app_id)
        create_workspace(app_info)
Example #12
0
def main():
    # CHECK FOR CREDENTIALS EXPIRATION
    creds_expire_days_warning()

    data = vapi().get_users()

    for user in data:
        data2 = vapi().get_user(user["user_id"])

        if "api_credentials" in data2:
            date_time_str = parse(data2["api_credentials"]["expiration_ts"])
            date = date_time_str.date()
            time = date_time_str.time()
            print("User {} API Credentials expiration date is {} {}".format(
                user["user_name"], str(date), str(time)))
        else:
            print("User {} has no API credentials".format(user["user_name"]))
def process_app(the_app_id):
    log.info("Getting sandbox info for application {}".format(the_app_id))
    data2 = vapi().get_sandbox_list(the_app_id)

    if len(data2) == 0:
        return 0

    sandbox_list = etree.fromstring(data2)
    sandbox_count = len(sandbox_list)

    if sandbox_count == 1:
        count_noun = "sandbox"
    else:
        count_noun = "sandboxes"

    log.info("app_id {} has {} {}".format(the_app_id, sandbox_count,
                                          count_noun))

    if sandbox_count == 0:
        return 0

    iteration = 0
    for sandbox in sandbox_list:
        sandbox_name = sandbox.get('sandbox_name')
        auto_recreate = sandbox.get('auto_recreate')
        expires = sandbox.get('expires')
        sandbox_id = sandbox.get('sandbox_id')

        if expires == None:
            continue  #can't set auto_recreate on a non-expiring sandbox
        if auto_recreate == 'true':
            continue  #don't set auto_recreate again

        log.info("Updating auto_recreate for sandbox {}, sandbox id {}".format(
            sandbox_name, sandbox_id))
        updated = vapi().update_sandbox(sandbox_id, "autorecreate", True)
        if updated == None:
            return 0  #something went wrong

        updated_xml = etree.fromstring(updated)
        log.info('==>Sandbox {} auto_recreate = {}'.format(
            sandbox_name, updated_xml.get('auto_recreate')))

        iteration += 1

    return iteration
Example #14
0
def creds_expire_days_warning():
    creds = vapi().get_creds()
    exp = datetime.datetime.strptime(creds['expiration_ts'],
                                     "%Y-%m-%dT%H:%M:%S.%f%z")
    delta = exp - datetime.datetime.now().astimezone(
    )  #we get a datetime with timezone...
    if (delta.days < 7):
        print('These API credentials expire ', creds['expiration_ts'])
def find_app_named(appname):
    apps = vapi().get_app_by_name(appname)
    if len(apps) == 0:
        return []

    for app in apps:
        if app["profile"]["name"] == appname:
            return [app]
def create_app(appname, teamguid, businesscriticality="HIGH", businessunit=""):
    if len(find_app_named(appname)) > 0:
        errormsg = "There is already an application named {}".format(appname)
        log.warning(errormsg)
        print(errormsg)
        return 0

    if businessunit == "":
        r = vapi().create_app(app_name=appname,
                              business_criticality=businesscriticality,
                              teams=[teamguid])
    else:
        r = vapi().create_app(app_name=appname,
                              business_criticality=businesscriticality,
                              teams=[teamguid],
                              business_unit=businessunit)
    return r["guid"]
def get_modules_from_summary(app_guid):
    log.info('Getting modules for {}'.format(app_guid))
    summary_report = vapi().get_summary_report(app_guid)
    static_analysis = summary_report.get('static-analysis')
    if static_analysis != None:
        modules = static_analysis.get('modules').get('module')
        return [module['name'] for module in modules]
    else:
        return []
Example #18
0
def downloadreport(token):
    # this will retry until the report is ready, with a 15 second wait between retries
    response = vapi().download_archer(token)

    # handle case where response is empty
    if (reportlength(response) == 0):
        return None

    return response
def update_mitigation_info(build_id, flaw_id_list, action, comment,
                           results_to_app_id):
    r = vapi().set_mitigation_info(build_id, flaw_id_list, action, comment)
    if '<error' in r.decode("UTF-8"):
        logging.info(
            'Error updating mitigation_info for {} in Build ID {}: {}'.format(
                str(flaw_id_list), str(build_id), r.decode('UTF-8')))
        sys.exit(
            '[*] Error updating mitigation_info for {} in Build ID {}'.format(
                str(flaw_id_list), str(build_id)))
    logging.info(
        'Updated mitigation information to {} for Flaw ID {} in {} in Build ID {}'.format(action,\
            str(flaw_id_list), results_to_app_id, build_id))
Example #20
0
def get_user_list(usernames):
    #get list of guids
    user_list = []
    for name in usernames:
        userinfo = vapi().get_user_by_name(
            name)  # note that this call always returns a list of 1, or 0
        if len(userinfo) == 0:
            errorstring = "No user found with name {}".format(name)
            print(errorstring)
            log.warning(errorstring)
            #log
            continue
        userguid = userinfo[0]["user_id"]
        user_list.append(userguid)
    return user_list
def create_api_user(apiname, email, teamguid):
    existinguser = find_user_named(apiname)
    if len(existinguser) > 0:
        # return existing user rather than creating new one
        userguid = existinguser[0]["user_id"]
        log.info("Found a user named {} with guid {}".format(
            apiname, userguid))
        return userguid

    r = vapi().create_user(email=email,
                           firstname=apiname,
                           lastname="API User",
                           type="API",
                           roles=[],
                           teams=[teamguid],
                           username=apiname)
    return r["user_id"]
def prompt_for_app(prompt_text):
    appguid = ""
    app_name_search = input(prompt_text)
    app_candidates = vapi().get_app_by_name(app_name_search)
    if len(app_candidates) == 0:
        print("No matches were found!")
    elif len(app_candidates) > 1:
        print("Please choose an application:")
        for idx, appitem in enumerate(app_candidates, start=1):
            print("{}) {}".format(idx, appitem["profile"]["name"]))
        i = input("Enter number: ")
        try:
            if 0 < int(i) <= len(app_candidates):
                appguid = app_candidates[int(i) - 1].get('guid')
        except ValueError:
            appguid = ""
    else:
        appguid = app_candidates[0].get('guid')

    return appguid
Example #23
0
def get_request_response(findings_list):
    # build a list of dicts containing the detailed finding info and request/response
    log.info('Getting finding details...')
    finding_details_list = []

    for finding in findings_list:
        log.info('Getting finding details for finding {})'.format(
            finding['issue_id']))
        finding_details = {'finding': finding}
        try:
            finding_request_response = vapi().get_dynamic_flaw_info(
                finding['context_guid'], finding['issue_id'])
            finding_details['request_response'] = finding_request_response
            finding_details_list.append(finding_details)
        except reqexcept.RequestException:  # this call may 404 if the request/response information is no longer available for an older finding
            status = "Findings details not available for finding {}, skipping".format(
                finding['issue_id'])
            log.exception(status)
            print(status)

    return finding_details_list
def get_app(app_guid):
    return vapi().get_app(app_guid)
def get_application_name(guid):
    app = vapi().get_app(guid)
    return app['profile']['name']
def findings_api(app_guid):
    return vapi().get_findings(app_guid, scantype='ALL', annot='TRUE')
def get_workspaces():
    return vapi().get_workspaces()
def get_all_apps():
    applist = vapi().get_apps()
    return applist
def get_app_info(guid):
    log.debug('Getting application info for guid {}'.format(guid))
    app_info = vapi().get_app(guid)
    return app_info
def get_findings(app_guid):
    log.info('Getting findings for {}'.format(app_guid))
    return vapi().get_findings(app_guid, scantype='STATIC', annot='FALSE')