Exemplo n.º 1
0
 def test_configure_log(self):
     configure_log("/tmp")
     logger = logging.getLogger()
     # Root logger level
     self.assertEqual(logger.getEffectiveLevel(), logging.WARNING)
     # Log file
     self.assertEqual(logger.handlers[0].baseFilename, self.logpath)
     # Overwrite file
     self.assertEqual(logger.handlers[0].mode, "w")
     # LambdaGuard logger level
     self.assertEqual(logger.handlers[0].level, logging.DEBUG)
Exemplo n.º 2
0
def run(arguments=''):
    args = parse_args(arguments)

    if args.html:
        HTMLReport(args.output).save()
        if args.verbose:
            print(f'HTML report saved to {args.output}/report.html')
        exit(0)

    rmtree(args.output, ignore_errors=True)
    Path(args.output).mkdir(parents=True, exist_ok=True)
    configure_log(args.output)
    identity = STS(f'arn:aws:sts:{args.region}', args.profile, args.keys[0],
                   args.keys[1]).identity
    if args.verbose:
        print(header, end='\n\n')
        for _ in ['UserId', 'Account', 'Arn']:
            align(_, identity[_], orange)
        print('')

    statistics = Statistics(args.output)
    visibility = VisibilityReport(args.output)

    for arn_str in get_functions(args):
        try:
            arn = arnparse(arn_str)
            if args.verbose:
                count = '[' + f'{statistics.statistics["lambdas"]+1}'.rjust(
                    4, ' ') + '] '
                print(f'\r{green}{count}{arn.resource}{nocolor}'.ljust(
                    100, ' '),
                      end='')
            lmbd = Lambda(arn.full, args)
            statistics.parse(lmbd.report())
            visibility.save(lmbd.report())
        except Exception:
            debug(arn_str)

    SecurityReport(args.output).save()
    HTMLReport(args.output).save()

    if args.verbose:
        print('\r' + ' ' * 100, end='\r')  # clear
        align('Lambdas', statistics.statistics["lambdas"])
        align('Security', statistics.statistics["security"]["count"])
        align('Triggers', statistics.statistics["triggers"]["count"])
        align('Resources', statistics.statistics["resources"]["count"])
        align('Layers', statistics.statistics["layers"])
        align('Runtimes', len(statistics.statistics["runtimes"]["items"]))
        align('Regions', len(statistics.statistics["regions"]["items"]))
        print('')
        align('Report', f'{args.output}/report.html')
        align('Log', f'{args.output}/lambdaguard.log')
        print('\n')
Exemplo n.º 3
0
    def test_debug(self):
        configure_log("/tmp")

        # Called without an exception to handle
        self.assertEqual(debug(), None)

        # Logging critical errors
        try:
            1 / 0
        except Exception:
            trace = debug().strip().split("\n")
            etype, evalue = trace[-1].split(": ", 1)
            self.assertEqual(etype, "ZeroDivisionError")
            self.assertEqual(evalue, "division by zero")

            elog = Path(self.logpath).read_text().strip()
            elog.endswith("ZeroDivisionError: division by zero")
Exemplo n.º 4
0
def run(arguments=""):
    """
    Main routine
    """
    args = parse_args(arguments)

    verbose(args, header, end="\n\n")

    if args.html:
        HTMLReport(args.output).save()
        verbose(args, f"Generated {args.output}/report.html", end="\n\n")
        exit(0)

    rmtree(args.output, ignore_errors=True)
    Path(args.output).mkdir(parents=True, exist_ok=True)
    configure_log(args.output)
    usage = get_usage(args)
    verbose(args, "Loading identity")
    region = list(usage.keys())[0]
    sts_arn = f"arn:aws:sts:{region}"
    identity = STS(sts_arn, args.profile, args.keys[0], args.keys[1])
    if args.verbose:
        for _ in ["UserId", "Account", "Arn"]:
            align(_, identity.caller[_], orange)
        print("")

    statistics = Statistics(args.output)
    visibility = VisibilityReport(args.output)
    writes = LambdaWrite(args)
    total_count = 0
    for region_count in usage.values():
        total_count += region_count

    for region in usage.keys():
        args.region = region
        for arn_str in get_functions(args):
            try:
                arn = arnparse(arn_str)
                counter = f'[ {statistics.statistics["lambdas"]+1}/{total_count} ] '
                verbose(args, f"{counter}{arn.resource}")
                lmbd = Lambda(arn.full, args, identity)
                for w in writes.get_for_lambda(arn.full):
                    lmbd.set_writes(w)
                statistics.parse(lmbd.report())
                visibility.save(lmbd.report())
            except Exception:
                debug(arn_str)

    SecurityReport(args.output).save()
    HTMLReport(args.output).save()

    if args.verbose:
        print("\r" + " " * 100, end="\r")  # clear
        align("Lambdas", statistics.statistics["lambdas"])
        align("Security", statistics.statistics["security"]["count"])
        align("Triggers", statistics.statistics["triggers"]["count"])
        align("Resources", statistics.statistics["resources"]["count"])
        align("Layers", statistics.statistics["layers"])
        align("Runtimes", len(statistics.statistics["runtimes"]["items"]))
        align("Regions", len(statistics.statistics["regions"]["items"]))
        print("")
        align("Report", f"{args.output}/report.html")
        align("Log", f"{args.output}/lambdaguard.log")
        print("")
Exemplo n.º 5
0
def run(arguments=''):
    '''
    Main routine
    '''
    args = parse_args(arguments)

    verbose(args, header, end='\n\n')

    if args.html:
        HTMLReport(args.output).save()
        verbose(args, f'Generated {args.output}/report.html', end='\n\n')
        exit(0)

    rmtree(args.output, ignore_errors=True)
    Path(args.output).mkdir(parents=True, exist_ok=True)
    configure_log(args.output)
    usage = get_usage(args)
    verbose(args, f'Loading identity')
    region = list(usage.keys())[0]
    sts_arn = f'arn:aws:sts:{region}'
    identity = STS(sts_arn, args.profile, args.keys[0], args.keys[1])
    if args.verbose:
        for _ in ['UserId', 'Account', 'Arn']:
            align(_, identity.caller[_], orange)
        print('')

    statistics = Statistics(args.output)
    visibility = VisibilityReport(args.output)
    writes = LambdaWrite(args)
    total_count = 0
    for region_count in usage.values():
        total_count += region_count

    for region in usage.keys():
        args.region = region
        for arn_str in get_functions(args):
            try:
                arn = arnparse(arn_str)
                counter = f'[ {statistics.statistics["lambdas"]+1}/{total_count} ] '
                verbose(args, f'{counter}{arn.resource}')
                lmbd = Lambda(arn.full, args, identity)
                for w in writes.get_for_lambda(arn.full):
                    lmbd.set_writes(w)
                statistics.parse(lmbd.report())
                visibility.save(lmbd.report())
            except Exception:
                debug(arn_str)

    SecurityReport(args.output).save()
    HTMLReport(args.output).save()

    if args.verbose:
        print('\r' + ' ' * 100, end='\r')  # clear
        align('Lambdas', statistics.statistics["lambdas"])
        align('Security', statistics.statistics["security"]["count"])
        align('Triggers', statistics.statistics["triggers"]["count"])
        align('Resources', statistics.statistics["resources"]["count"])
        align('Layers', statistics.statistics["layers"])
        align('Runtimes', len(statistics.statistics["runtimes"]["items"]))
        align('Regions', len(statistics.statistics["regions"]["items"]))
        print('')
        align('Report', f'{args.output}/report.html')
        align('Log', f'{args.output}/lambdaguard.log')
        print('')