~ubuntu-branches/ubuntu/wily/bandit/wily-proposed

« back to all changes in this revision

Viewing changes to bandit/bandit.py

  • Committer: Package Import Robot
  • Author(s): Dave Walker (Daviey)
  • Date: 2015-07-22 09:01:39 UTC
  • Revision ID: package-import@ubuntu.com-20150722090139-fl0nluy0x8m9ctx4
Tags: upstream-0.12.0
ImportĀ upstreamĀ versionĀ 0.12.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding:utf-8 -*-
 
2
#
 
3
# Copyright 2014 Hewlett-Packard Development Company, L.P.
 
4
#
 
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may
 
6
# not use this file except in compliance with the License. You may obtain
 
7
# a copy of the License at
 
8
#
 
9
#      http://www.apache.org/licenses/LICENSE-2.0
 
10
#
 
11
# Unless required by applicable law or agreed to in writing, software
 
12
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 
13
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 
14
# License for the specific language governing permissions and limitations
 
15
# under the License.
 
16
from __future__ import absolute_import
 
17
 
 
18
import argparse
 
19
import logging
 
20
import os
 
21
import sys
 
22
 
 
23
from bandit.core import extension_loader as ext_loader
 
24
from bandit.core import manager as b_manager
 
25
 
 
26
default_test_config = 'bandit.yaml'
 
27
 
 
28
 
 
29
def main():
 
30
    extension_mgr = ext_loader.MANAGER
 
31
    parser = argparse.ArgumentParser(
 
32
        description='Bandit - a Python source code analyzer.'
 
33
    )
 
34
    parser.add_argument(
 
35
        'targets', metavar='targets', type=str, nargs='+',
 
36
        help='source file(s) or directory(s) to be tested'
 
37
    )
 
38
    parser.add_argument(
 
39
        '-r', '--recursive', dest='recursive',
 
40
        action='store_true', help='process files in subdirectories'
 
41
    )
 
42
    parser.add_argument(
 
43
        '-a', '--aggregate', dest='agg_type',
 
44
        action='store', default='file', type=str,
 
45
        choices=['file', 'vuln'],
 
46
        help='group results by vulnerability type or file it occurs in'
 
47
    )
 
48
    parser.add_argument(
 
49
        '-n', '--number', dest='context_lines',
 
50
        action='store', default=-1, type=int,
 
51
        help='max number of code lines to display for each issue identified'
 
52
    )
 
53
    parser.add_argument(
 
54
        '-c', '--configfile', dest='config_file',
 
55
        action='store', default=None, type=str,
 
56
        help=('test config file, defaults to /etc/bandit/bandit.yaml, or'
 
57
              './bandit.yaml if not given')
 
58
    )
 
59
    parser.add_argument(
 
60
        '-p', '--profile', dest='profile',
 
61
        action='store', default=None, type=str,
 
62
        help='test set profile in config to use (defaults to all tests)'
 
63
    )
 
64
    parser.add_argument(
 
65
        '-l', '--level', dest='level', action='count',
 
66
        default=1, help='results level filter'
 
67
    )
 
68
    parser.add_argument(
 
69
        '-f', '--format', dest='output_format', action='store',
 
70
        default='txt', help='specify output format',
 
71
        choices=sorted(extension_mgr.formatter_names)
 
72
    )
 
73
    parser.add_argument(
 
74
        '-o', '--output', dest='output_file', action='store',
 
75
        default=None, help='write report to filename'
 
76
    )
 
77
    parser.add_argument(
 
78
        '-v', '--verbose', dest='verbose', action='store_true',
 
79
        help='show extra information like excluded and included files'
 
80
    )
 
81
    parser.add_argument(
 
82
        '-d', '--debug', dest='debug', action='store_true',
 
83
        help='turn on debug mode'
 
84
    )
 
85
    parser.set_defaults(debug=False)
 
86
    parser.set_defaults(verbose=False)
 
87
 
 
88
    parser.epilog = ('The following plugin suites were discovered and'
 
89
                     ' loaded: [' +
 
90
                     ', '.join(extension_mgr.plugin_names) + ']')
 
91
 
 
92
    # setup work - parse arguments, and initialize BanditManager
 
93
    args = parser.parse_args()
 
94
    config_file = args.config_file
 
95
    if not config_file:
 
96
 
 
97
        home_config = None
 
98
 
 
99
        # attempt to get the home directory from environment
 
100
        home_dir = os.environ.get('HOME')
 
101
        if home_dir:
 
102
            home_config = "%s/.config/bandit/%s" % (home_dir,
 
103
                                                    default_test_config)
 
104
 
 
105
        installed_config = str(os.path.dirname(os.path.realpath(__file__)) +
 
106
                               '/config/%s' % default_test_config)
 
107
 
 
108
        # prefer config file in the following order:
 
109
        # 1) current directory, 2) user home directory, 3) bundled config
 
110
        config_paths = [default_test_config, home_config, installed_config]
 
111
 
 
112
        for path in config_paths:
 
113
            if path and os.access(path, os.R_OK):
 
114
                config_file = path
 
115
                break
 
116
 
 
117
    if not config_file:
 
118
        # no logger yet, so using print
 
119
        print ("no config found, tried ...")
 
120
        for path in config_paths:
 
121
            if path:
 
122
                print ("\t%s" % path)
 
123
        sys.exit(2)
 
124
 
 
125
    b_mgr = b_manager.BanditManager(config_file, args.agg_type,
 
126
                                    args.debug, profile_name=args.profile,
 
127
                                    verbose=args.verbose)
 
128
    # we getLogger() here because BanditManager has configured it at this point
 
129
    logger = logging.getLogger()
 
130
    if args.output_format != "json":
 
131
        logger.info("using config: %s", config_file)
 
132
        logger.info("running on Python %d.%d.%d", sys.version_info.major,
 
133
                    sys.version_info.minor, sys.version_info.micro)
 
134
 
 
135
    # check ability to write output file, if requested
 
136
    if args.output_file is not None:
 
137
        check_dest = b_mgr.check_output_destination(args.output_file)
 
138
        if check_dest is not True:
 
139
            logger.error(
 
140
                'Problem with specified output destination\n\t%s: %s',
 
141
                check_dest, args.output_file
 
142
            )
 
143
            sys.exit(2)
 
144
 
 
145
    # initiate file discovery step within Bandit Manager
 
146
    b_mgr.discover_files(args.targets, args.recursive)
 
147
 
 
148
    # initiate execution of tests within Bandit Manager
 
149
    b_mgr.run_tests()
 
150
    if args.debug:
 
151
        b_mgr.output_metaast()
 
152
 
 
153
    # trigger output of results by Bandit Manager
 
154
    b_mgr.output_results(args.context_lines, args.level - 1, args.output_file,
 
155
                         args.output_format)
 
156
 
 
157
    # return an exit code of 1 if there are results, 0 otherwise
 
158
    if b_mgr.results_count > 0:
 
159
        sys.exit(1)
 
160
    else:
 
161
        sys.exit(0)
 
162
 
 
163
 
 
164
if __name__ == '__main__':
 
165
    main()