예제 #1
0
def query(anchore_config, image, imagefile, include_allanchore, module):
    """
    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).

    Execute the specified query (module) with any parameters it requires. Modules are scripts in a specific location.

    Each query has its own parameters and outputs.

    Examples using pre-defined queries:

    'anchore query --image nginx:latest list-packages all'
    'anchore query has-package wget'
    'anchore query --image nginx:latest list-files-detail all'
    'anchore query cve-scan all'

    """

    global config, imagelist, nav
    ecode = 0
    success = True
    config = anchore_config

    if module:
        if image and imagefile:
            raise click.BadOptionUsage(
                'Can only use one of --image, --imagefile')

        try:
            imagedict = build_image_list(anchore_config, image, imagefile,
                                         not (image or imagefile),
                                         include_allanchore)
            imagelist = list(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 input images")
            sys.exit(1)

    try:
        nav = init_nav_contexts()
        result = nav.run_query(list(module))
        if result:
            anchore_utils.print_result(config, result)

        if nav.check_for_warnings(result):
            ecode = 2

    except:
        anchore_print_err("query operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #2
0
def query(module):
    """
    Execute the specified query (module) with any parameters it requires. Modules are scripts in a specific location.

    Each query has its own parameters and outputs.

    Examples using pre-defined queries:

    Query all images to see which have the package 'wget' installed:
    'anchore explore query has-package wget'

    """
    ecode = 0
    try:
        nav, vis = init_nav_vis_contexts()

        result = nav.run_query(list(module))
        if result:
            anchore_utils.print_result(config, result)

        if nav.check_for_warnings(result):
            ecode = 2

    except:
        anchore_print_err("query operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #3
0
파일: query.py 프로젝트: anchore/anchore
def query(anchore_config, image, imagefile, include_allanchore, module):
    """
    Image IDs can be specified as hash ids, repo names (e.g. centos), or tags (e.g. centos:latest).

    Execute the specified query (module) with any parameters it requires. Modules are scripts in a specific location.

    Each query has its own parameters and outputs.

    Examples using pre-defined queries:

    'anchore query --image nginx:latest list-packages all'
    'anchore query has-package wget'
    'anchore query --image nginx:latest list-files-detail all'
    'anchore query cve-scan all'

    """

    global config, imagelist, nav
    ecode = 0
    success = True
    config = anchore_config

    if module:
        if image and imagefile:
            raise click.BadOptionUsage('Can only use one of --image, --imagefile')

        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 input images")
            sys.exit(1)

    try:
        nav = init_nav_contexts()

        result = nav.run_query(list(module))
        if result:
            anchore_utils.print_result(config, result)

        if nav.check_for_warnings(result):
            ecode = 2

    except:
        anchore_print_err("query operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #4
0
파일: analyzer.py 프로젝트: tgerla/anchore
def gate(anchore_config, force, image, imagefile, include_allanchore, editpolicy, 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

    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

    try:
        imagedict = build_image_list(anchore_config, image, imagefile, not (image or imagefile), include_allanchore)
        imagelist = imagedict.keys()
    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
        else:
            try:
                # run the gates
                result = con.run_gates()
                if result:
                    anchore_utils.print_result(anchore_config, result)
                    success = True
                    ecode = con.result_get_highest_action(result)
            except Exception as err:
                print str(err)
                anchore_print_err("failed to run gates")
                ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #5
0
def show_familytree():
    """Show image family tree image IDs"""
    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_familytree()
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()    
    sys.exit(ecode)
예제 #6
0
def show_familytree():
    """Show image family tree image IDs"""
    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.run_query(['show-familytree', 'all'])
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #7
0
def show_layers():
    """Show image layer IDs"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_layers()
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #8
0
def show_dockerfile():
    """Generate (or display actual) image Dockerfile"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.run_query(['show-dockerfile', 'all'])
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #9
0
파일: toolbox.py 프로젝트: anchore/anchore
def show_layers():
    """Show image layer IDs"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.run_query(['show-layers', 'all'])
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #10
0
파일: toolbox.py 프로젝트: anchore/anchore
def show_dockerfile():
    """Generate (or display actual) image Dockerfile"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.run_query(['show-dockerfile', 'all'])
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #11
0
def show_taghistory():
    """Show history of all known repo/tags for image"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_taghistory()
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #12
0
def generate_dockerfile():
    """Generate (or display actual) image Dockerfile"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_dockerfile_contents()
        if result:
            anchore_utils.print_result(config, result, outputmode='raw')

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #13
0
def generate_dockerfile():
    """Generate (or display actual) image Dockerfile"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_dockerfile_contents()
        if result:
            anchore_utils.print_result(config, result, outputmode='raw')

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #14
0
def show_taghistory():
    """Show history of all known repo/tags for image"""


    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_taghistory()
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #15
0
파일: audit.py 프로젝트: anchore/anchore
def report():
    """
    Show analysis report of the specified image(s).

    The analysis report includes information on:

    \b
    Image Id - The image id (as a hash)

    Type - The type of image (--imagetype option used when anchore analyze was run)

    CurrentTags - The current set of repo tags on the image

    AllTags - The set of all repo tags that have been on the image during analysis passes

    GateStatus - The overall aggregate gate output status: GO|STOP|WARN

    Size - The size in bytes of the image on disk
    
    Counts - The counts for various attributes of the images such as packages, files, and suid files

    BaseDiffs - Differences of this image from its base image

    Report outputs these entries in a table format by default.
    """
    ecode = 0

    try:
        nav = init_nav_contexts()
        result = nav.generate_reports()

        #result = generate_reports(imagelist, showall=all, showdetails=details)

        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #16
0
def report():
    """
    Show analysis report of the specified image(s).

    The analysis report includes information on:

    \b
    Image Id - The image id (as a hash)

    Type - The type of image (--imagetype option used when anchore analyze was run)

    CurrentTags - The current set of repo tags on the image

    AllTags - The set of all repo tags that have been on the image during analysis passes

    GateStatus - The overall aggregate gate output status: GO|STOP|WARN

    Size - The size in bytes of the image on disk
    
    Counts - The counts for various attributes of the images such as packages, files, and suid files

    BaseDiffs - Differences of this image from its base image

    Report outputs these entries in a table format by default.
    """
    ecode = 0

    try:
        nav = init_nav_contexts()
        result = nav.generate_reports()

        #result = generate_reports(imagelist, showall=all, showdetails=details)

        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #17
0
파일: toolbox.py 프로젝트: tgerla/anchore
def show_layers():
    """Show image layer IDs"""

    if not nav:
        sys.exit(1)

    ecode = 0
    try:
        result = nav.get_layers()
        if result:
            anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        #import traceback
        #traceback.print_exc()
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #18
0
def show_analyzer_status():
    """Show analyzer status for specified image"""

    ecode = 0
    try:
        image = contexts['anchore_allimages'][imagelist[0]]
        analyzer_status = contexts['anchore_db'].load_analyzer_manifest(
            image.meta['imageId'])
        result = {
            image.meta['imageId']: {
                'result': {
                    'header': [
                        'Analyzer', 'Status', '*Type', 'LastExec', 'Exitcode',
                        'Checksum'
                    ],
                    'rows': []
                }
            }
        }
        for script in analyzer_status.keys():
            adata = analyzer_status[script]
            nicetime = datetime.datetime.fromtimestamp(
                adata['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
            try:
                row = [
                    script.split('/')[-1], adata['status'], adata['atype'],
                    nicetime,
                    str(adata['returncode']), adata['csum']
                ]
                result[image.meta['imageId']]['result']['rows'].append(row)
            except:
                pass
        if result:
            anchore_utils.print_result(config, result)
    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #19
0
파일: toolbox.py 프로젝트: anchore/anchore
def show_analyzer_status():
    """Show analyzer status for specified image"""

    ecode = 0
    try:
        image=contexts['anchore_allimages'][imagelist[0]]
        analyzer_status = contexts['anchore_db'].load_analyzer_manifest(image.meta['imageId'])
        result = {image.meta['imageId']:{'result':{'header':['Analyzer', 'Status', '*Type', 'LastExec', 'Exitcode', 'Checksum'], 'rows':[]}}}
        for script in analyzer_status.keys():
            adata = analyzer_status[script]
            nicetime = datetime.datetime.fromtimestamp(adata['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
            try:
                row = [script.split('/')[-1], adata['status'], adata['atype'], nicetime, str(adata['returncode']), adata['csum']]
                result[image.meta['imageId']]['result']['rows'].append(row)        
            except:
                pass
        if result:
            anchore_utils.print_result(config, result)
    except:
        anchore_print_err("operation failed")
        ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #20
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)
예제 #21
0
def gate(
    anchore_config,
    force,
    image,
    imagefile,
    include_allanchore,
    editpolicy,
    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

    if image and imagefile:
        raise click.BadOptionUsage('Can only use one of --image, --imagefile')

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

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

    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
        else:
            try:
                # run the gates
                result = con.run_gates()
                if result:
                    anchore_utils.print_result(anchore_config, result)
                    success = True
                    ecode = con.result_get_highest_action(result)
            except Exception as err:
                print str(err)
                anchore_print_err("failed to run gates")
                ecode = 1

    contexts['anchore_allimages'].clear()
    sys.exit(ecode)
예제 #22
0
파일: toolbox.py 프로젝트: anchore/anchore
def images(no_trunc):
    ecode = 0

    import datetime
    
    try:
        anchoreDB = contexts['anchore_db']

        header = ["Repository", "Tag", "Image ID", "Distro", "Last Analyzed", "Size"]
        result = {"multi":{'result':{'header':header, 'rows':[]}}}

        hasData = False
        for image in anchoreDB.load_all_images_iter():
            try:
                imageId = image[0]
                imagedata = image[1]
                meta = imagedata['meta']

                name = meta['humanname']
                shortId = meta['shortId']
                size = meta['sizebytes']

                if no_trunc:
                    printId = imageId
                else:
                    printId = shortId

                patt = re.match("(.*):(.*)", name)
                if patt:
                    repo = patt.group(1)
                    tag = patt.group(2)
                else:
                    repo = "<none>"
                    tag = "<none>"

                oldtags = ','.join(imagedata['anchore_all_tags'])

                if meta['usertype']:
                    atype = meta['usertype']
                else:
                    atype = "<none>"

                distrometa = anchore_utils.get_distro_from_imageId(imageId)
                distro = distrometa['DISTRO'] + "/" + distrometa['DISTROVERS']

                amanifest = anchoreDB.load_analyzer_manifest(imageId)
                latest = 0;
                if amanifest:
                    for a in amanifest.keys():
                        ts = amanifest[a]['timestamp']
                        if ts > latest:
                            latest = ts
                
                if latest:
                    timestr = datetime.datetime.fromtimestamp(int(latest)).strftime('%m-%d-%Y %H:%M:%S')
                else:
                    timestr = "Not Analyzed"
                    
                row = [repo, tag, printId, distro, timestr, str(round(float(size) / 1024.0 / 1024.0, 2)) + "M"]
                result['multi']['result']['rows'].append(row)
                #t.add_row(row)
                hasData = True
            except Exception as err:
                raise err

        anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1            

    sys.exit(ecode)
예제 #23
0
def images(no_trunc):
    ecode = 0

    import datetime

    try:
        anchoreDB = contexts['anchore_db']

        header = [
            "Repository", "Tag", "Image ID", "Distro", "Last Analyzed", "Size"
        ]
        result = {"multi": {'result': {'header': header, 'rows': []}}}

        hasData = False
        for image in anchoreDB.load_all_images_iter():
            try:
                imageId = image[0]
                imagedata = image[1]
                meta = imagedata['meta']

                name = meta['humanname']
                shortId = meta['shortId']
                size = meta['sizebytes']

                if no_trunc:
                    printId = imageId
                else:
                    printId = shortId

                patt = re.match("(.*):(.*)", name)
                if patt:
                    repo = patt.group(1)
                    tag = patt.group(2)
                else:
                    repo = "<none>"
                    tag = "<none>"

                oldtags = ','.join(imagedata['anchore_all_tags'])

                if meta['usertype']:
                    atype = meta['usertype']
                else:
                    atype = "<none>"

                distrometa = anchore_utils.get_distro_from_imageId(imageId)
                distro = distrometa['DISTRO'] + "/" + distrometa['DISTROVERS']

                amanifest = anchoreDB.load_analyzer_manifest(imageId)
                latest = 0
                if amanifest:
                    for a in amanifest.keys():
                        ts = amanifest[a]['timestamp']
                        if ts > latest:
                            latest = ts

                if latest:
                    timestr = datetime.datetime.fromtimestamp(
                        int(latest)).strftime('%m-%d-%Y %H:%M:%S')
                else:
                    timestr = "Not Analyzed"

                row = [
                    repo, tag, printId, distro, timestr,
                    str(round(float(size) / 1024.0 / 1024.0, 2)) + "M"
                ]
                result['multi']['result']['rows'].append(row)
                #t.add_row(row)
                hasData = True
            except Exception as err:
                raise err

        anchore_utils.print_result(config, result)

    except:
        anchore_print_err("operation failed")
        ecode = 1

    sys.exit(ecode)
예제 #24
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)
예제 #25
0
파일: analyzer.py 프로젝트: anchore/anchore
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)