Exemple #1
0
def gate(anchore_config, force, image, imagefile, include_allanchore,
         editpolicy, rmpolicy, listpolicy, updatepolicy, policy, show_gatehelp,
         show_policytemplate, whitelist):
    """
    Runs gate checks on the specified image(s) or edits the image's gate policy.
    The --editpolicy option is only valid for a single image.

    The --image and --imagefile options are mutually exclusive.

    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).
    """

    ecode = 0
    success = True

    # special option, does not need any image inputs
    if show_gatehelp:
        try:
            gate_info = anchore_utils.discover_gates()
            anchore_print(gate_info, do_formatting=True)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    if show_policytemplate:
        try:
            outstr = "\n"
            gate_info = anchore_utils.discover_gates()
            for g in gate_info.keys():
                for t in gate_info[g].keys():
                    params = list()
                    if 'params' in gate_info[g][t] and gate_info[g][t][
                            'params'] and gate_info[g][t]['params'].lower(
                            ) != 'none':
                        for p in gate_info[g][t]['params'].split(','):
                            params.append(p + "=<a,b,c>")

                    outstr += ':'.join(
                        [g, t, "<STOP|WARN|GO>", ' '.join(params)]) + "\n"

            anchore_print(outstr, do_formatting=False)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    # the rest require some form of image(s) be given as input
    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    if policy and (editpolicy or whitelist or listpolicy or updatepolicy
                   or rmpolicy):
        raise click.BadOptionUsage(
            'Cannot use other policy options when --policy <file> is specified.'
        )

    try:
        imagedict = build_image_list(anchore_config, image, imagefile,
                                     not (image or imagefile),
                                     include_allanchore)
        imagelist = imagedict.keys()

        try:
            ret = anchore_utils.discover_imageIds(imagelist)
        except ValueError as err:
            raise err
        else:
            #imagelist = ret.keys()
            imagelist = ret

    except Exception as err:
        anchore_print_err("could not load any images")
        sys.exit(1)

    try:
        con = controller.Controller(anchore_config=anchore_config,
                                    imagelist=imagelist,
                                    allimages=contexts['anchore_allimages'],
                                    force=force)
    except Exception as err:
        anchore_print_err("gate operation failed")
        ecode = 1
    else:
        if editpolicy:
            if not con.editpolicy():
                ecode = 1
        elif whitelist:
            if not con.editwhitelist():
                ecode = 1
        elif rmpolicy:
            if not con.rmpolicy():
                ecode = 1
            else:
                anchore_print("policies successfully removed.",
                              do_formatting=True)
        elif updatepolicy:
            if not con.updatepolicy(updatepolicy):
                ecode = 1
            else:
                anchore_print("policies successfully updated.",
                              do_formatting=True)
        elif listpolicy:
            result = con.listpolicy()
            record = {}
            if not result:
                ecode = 1
            else:
                try:
                    for imageId in result.keys():
                        record[imageId] = list()
                        pol = result[imageId]
                        for gate in pol.keys():
                            for trigger in pol[gate].keys():
                                if str(pol[gate][trigger]['params']):
                                    outstr = ":".join([
                                        gate, trigger,
                                        str(pol[gate][trigger]['action']),
                                        str(pol[gate][trigger]['params'])
                                    ])
                                else:
                                    outstr = ":".join([
                                        gate, trigger,
                                        str(pol[gate][trigger]['action'])
                                    ])
                                record[imageId].append(outstr)
                    if record:
                        anchore_print(record, do_formatting=True)
                except Exception as err:
                    anchore_print_err("failed to list policies: " + str(err))
                    ecode = 1
        else:
            try:
                # run the gates
                result = con.run_gates(policy=policy)
                if result:
                    anchore_utils.print_result(anchore_config, result)
                    success = True
                    ecode = con.result_get_highest_action(result)
            except Exception as err:
                anchore_print_err("failed to run gates: " + str(err))
                ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
Exemple #2
0
def gate(anchore_config, force, image, imagefile, include_allanchore,
         editpolicy, rmpolicy, listpolicy, updatepolicy, policy, run_bundle,
         bundlefile, usetag, resultsonly, show_gatehelp, show_policytemplate,
         whitelist, global_whitelist, show_triggerids, show_whitelisted):
    """
    Runs gate checks on the specified image(s) or edits the image's gate policy.
    The --editpolicy option is only valid for a single image.

    The --image and --imagefile options are mutually exclusive.

    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).
    """

    ecode = 0
    success = True

    # special option, does not need any image inputs
    if show_gatehelp:
        try:
            gate_info = anchore_utils.discover_gates()
            anchore_print(gate_info, do_formatting=True)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    if show_policytemplate:
        try:
            outstr = "\n"
            gate_info = anchore_utils.discover_gates()
            for g in gate_info.keys():
                for t in gate_info[g].keys():
                    params = list()
                    if 'params' in gate_info[g][t] and gate_info[g][t][
                            'params'] and gate_info[g][t]['params'].lower(
                            ) != 'none':
                        for p in gate_info[g][t]['params'].split(','):
                            params.append(p + "=<a,b,c>")

                    outstr += ':'.join(
                        [g, t, "<STOP|WARN|GO>", ' '.join(params)]) + "\n"

            anchore_print(outstr, do_formatting=False)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    # the rest require some form of image(s) be given as input
    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    if policy and (editpolicy or whitelist or listpolicy or updatepolicy
                   or rmpolicy):
        raise click.BadOptionUsage(
            'Cannot use other policy options when --policy <file> is specified.'
        )

    if (policy and run_bundle):
        raise click.BadOptionUsage(
            'Cannot use both --policy and --run_bundle at the same time.')

    if (run_bundle and
        (editpolicy or whitelist or listpolicy or updatepolicy or rmpolicy)):
        raise click.BadOptionUsage(
            'Cannot use other policy options when --run_bundle is specified.')

    try:
        imagedict = build_image_list(anchore_config, image, imagefile,
                                     not (image or imagefile),
                                     include_allanchore)
        imagelist = imagedict.keys()
        inputimagelist = list(imagelist)

        try:
            ret = anchore_utils.discover_imageIds(imagelist)
        except ValueError as err:
            raise err
        else:
            #imagelist = ret.keys()
            imagelist = ret

    except Exception as err:
        anchore_print_err("could not load any images")
        sys.exit(1)

    try:
        con = controller.Controller(anchore_config=anchore_config,
                                    imagelist=imagelist,
                                    allimages=contexts['anchore_allimages'],
                                    force=force)
    except Exception as err:
        anchore_print_err("gate operation failed")
        ecode = 1
    else:
        if editpolicy:
            if not con.editpolicy():
                ecode = 1
        elif whitelist:
            if not con.editwhitelist():
                ecode = 1
        elif rmpolicy:
            if not con.rmpolicy():
                ecode = 1
            else:
                anchore_print("policies successfully removed.",
                              do_formatting=True)
        elif updatepolicy:
            if not con.updatepolicy(updatepolicy):
                ecode = 1
            else:
                anchore_print("policies successfully updated.",
                              do_formatting=True)
        elif listpolicy:
            result = con.listpolicy()
            record = {}
            if not result:
                ecode = 1
            else:
                try:
                    for imageId in result.keys():
                        record[imageId] = list()
                        pol = result[imageId]
                        for gate in pol.keys():
                            for trigger in pol[gate].keys():
                                if str(pol[gate][trigger]['params']):
                                    outstr = ":".join([
                                        gate, trigger,
                                        str(pol[gate][trigger]['action']),
                                        str(pol[gate][trigger]['params'])
                                    ])
                                else:
                                    outstr = ":".join([
                                        gate, trigger,
                                        str(pol[gate][trigger]['action'])
                                    ])
                                record[imageId].append(outstr)
                    if record:
                        anchore_print(record, do_formatting=True)
                except Exception as err:
                    anchore_print_err("failed to list policies: " + str(err))
                    ecode = 1
        elif run_bundle:
            try:
                if not anchore_policy.check():
                    anchore_print_err(
                        "run-bundle specified, but it appears as though no policy bundles have been synced yet: run 'anchore policybundle sync' to get your latest bundles from anchore.io"
                    )
                    ecode = 1
                else:
                    bundle = anchore_policy.load_policymeta(
                        policymetafile=bundlefile)
                    if not bundle:
                        raise Exception(
                            "could not load stored bundle - run 'anchore policybundle sync' and try again"
                        )

                    bundleId = bundle['id']
                    result, ecode = anchore_policy.run_bundle(
                        anchore_config=anchore_config,
                        imagelist=inputimagelist,
                        matchtag=usetag,
                        bundle=bundle)
                    if not resultsonly:
                        if anchore_config.cliargs['json']:
                            import json
                            anchore_print(json.dumps(result))
                        else:
                            for image in result.keys():
                                for gate_result in result[image][
                                        'evaluations']:
                                    _logger.info(
                                        "BundleId=" + bundleId + " Policy=" +
                                        gate_result['policy_name'] +
                                        " Whitelists=" +
                                        str(gate_result['whitelist_names']))
                                    anchore_utils.print_result(
                                        anchore_config, gate_result['results'])
                    else:
                        final_result = {}
                        for image in result.keys():
                            for gate_result in result[image]['evaluations']:
                                final_result.update(gate_result['results'])
                        anchore_utils.print_result(anchore_config,
                                                   final_result)
            except Exception as err:
                anchore_print_err("failed to run gates")
                ecode = 1

        else:
            try:
                # run the gates
                result = con.run_gates(policy=policy,
                                       global_whitelist=global_whitelist,
                                       show_triggerIds=show_triggerids,
                                       show_whitelisted=show_whitelisted)
                if result:
                    anchore_utils.print_result(anchore_config, result)
                    success = True
                    ecode = con.result_get_highest_action(result)
            except Exception as err:
                anchore_print_err("failed to run gates")
                ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
Exemple #3
0
def gate(anchore_config, force, image, imagefile, include_allanchore, editpolicy, rmpolicy, listpolicy, updatepolicy, policy, run_bundle, bundlefile, usetag, resultsonly, show_gatehelp, show_policytemplate, whitelist, global_whitelist, show_triggerids, show_whitelisted):
    """
    Runs gate checks on the specified image(s) or edits the image's gate policy.
    The --editpolicy option is only valid for a single image.

    The --image and --imagefile options are mutually exclusive.

    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).
    """

    ecode = 0
    success = True

    # special option, does not need any image inputs
    if show_gatehelp:        
        try:
            gate_info = anchore_utils.discover_gates()
            anchore_print(gate_info, do_formatting=True)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    if show_policytemplate:
        try:
            outstr = "\n"
            gate_info = anchore_utils.discover_gates()
            for g in gate_info.keys():
                for t in gate_info[g].keys():
                    params = list()
                    if 'params' in gate_info[g][t] and gate_info[g][t]['params'] and gate_info[g][t]['params'].lower() != 'none':
                        for p in gate_info[g][t]['params'].split(','):
                            params.append(p+"=<a,b,c>")
                        
                    outstr += ':'.join([g, t, "<STOP|WARN|GO>", ' '.join(params)]) + "\n"
            
            anchore_print(outstr, do_formatting=False)
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            sys.exit(1)
        sys.exit(0)

    # the rest require some form of image(s) be given as input
    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    if policy and (editpolicy or whitelist or listpolicy or updatepolicy or rmpolicy):
        raise click.BadOptionUsage('Cannot use other policy options when --policy <file> is specified.')

    if (policy and run_bundle):
        raise click.BadOptionUsage('Cannot use both --policy and --run_bundle at the same time.')

    if (run_bundle and (editpolicy or whitelist or listpolicy or updatepolicy or rmpolicy)):
        raise click.BadOptionUsage('Cannot use other policy options when --run_bundle is specified.')

    if (run_bundle and (usetag and resultsonly)):
        raise click.BadOptionUsage('Cannot use --resultsonly if --usetag is specified.')

    if (run_bundle and (usetag and not image)):
        raise click.BadOptionUsage('Cannot specify --usetag unless gating a single image (using --image)')

    try:
        imagedict = build_image_list(anchore_config, image, imagefile, not (image or imagefile), include_allanchore)
        imagelist = imagedict.keys()
        inputimagelist = list(imagelist)

        try:
            ret = anchore_utils.discover_imageIds(imagelist)
        except ValueError as err:
            raise err
        else:
            imagelist = ret

    except Exception as err:
        anchore_print_err("could not load any images")
        sys.exit(1)

    try:
        con = controller.Controller(anchore_config=anchore_config, imagelist=imagelist, allimages=contexts['anchore_allimages'], force=force)
    except Exception as err:
        anchore_print_err("gate operation failed")
        ecode = 1
    else:
        if editpolicy:
            if not con.editpolicy():
                ecode = 1
        elif whitelist:
            if not con.editwhitelist():
                ecode = 1
        elif rmpolicy:
            if not con.rmpolicy():
                ecode = 1;
            else:
                anchore_print("policies successfully removed.", do_formatting=True)
        elif updatepolicy:
            if not con.updatepolicy(updatepolicy):
                ecode = 1;
            else:
                anchore_print("policies successfully updated.", do_formatting=True)
        elif listpolicy:
            result = con.listpolicy()
            record = {}
            if not result:
                ecode = 1
            else:
                try:
                    for imageId in result.keys():
                        record[imageId] = list()
                        pol = result[imageId]
                        for gate in pol.keys():
                            for trigger in pol[gate].keys():
                                if str(pol[gate][trigger]['params']):
                                    outstr = ":".join([gate, trigger, str(pol[gate][trigger]['action']), str(pol[gate][trigger]['params'])])
                                else:
                                    outstr = ":".join([gate, trigger, str(pol[gate][trigger]['action'])])
                                record[imageId].append(outstr)
                    if record:
                        anchore_print(record, do_formatting=True)
                except Exception as err:
                    anchore_print_err("failed to list policies: " + str(err))
                    ecode = 1
        elif run_bundle:
            try:
                if not anchore_policy.check():
                    anchore_print_err("run-bundle specified, but it appears as though no policy bundles have been synced yet: run 'anchore policybundle sync' to get your latest bundles from anchore.io")
                    ecode = 1
                else:
                    bundle = anchore_policy.load_policymeta(policymetafile=bundlefile)
                    if not bundle:
                        raise Exception("could not load stored bundle - run 'anchore policybundle sync' and try again")

                    bundleId = bundle['id']
                    
                    inputimage = inputimagelist[0]

                    allresults = {}
                    for inputimage in inputimagelist:
                        result, image_ecode = anchore_policy.run_bundle(anchore_config=anchore_config, image=inputimage, matchtags=usetag, bundle=bundle, show_whitelisted=show_whitelisted, show_triggerIds=show_triggerids)
                        allresults.update(result)

                        if image_ecode == 1:
                            ecode = 1
                        elif ecode == 0 and image_ecode > ecode:
                            ecode = image_ecode

                    if not resultsonly:
                        if anchore_config.cliargs['json']:
                            anchore_print(json.dumps(allresults))
                        else:
                            for image in allresults.keys():
                                for gate_result in allresults[image]['evaluations']:
                                    _logger.info("Image="+image + " BundleId="+bundleId+" Policy="+gate_result['policy_name']+" Whitelists="+str(gate_result['whitelist_names']))
                                    anchore_utils.print_result(anchore_config, gate_result['results'])
                    else:
                        final_result = {}
                        for image in allresults.keys():
                            for gate_result in allresults[image]['evaluations']:
                                final_result.update(gate_result['results'])
                        anchore_utils.print_result(anchore_config, final_result)
            except Exception as err:
                anchore_print_err("failed to run gates")
                ecode = 1

        else:
            try:
                # run the gates
                result = con.run_gates(policy=policy, global_whitelist=global_whitelist, show_triggerIds=show_triggerids, show_whitelisted=show_whitelisted)
                if result:
                    anchore_utils.print_result(anchore_config, result)
                    success = True
                    ecode = con.result_get_highest_action(result)
            except Exception as err:
                anchore_print_err("failed to run gates")
                ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)