Beispiel #1
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')
Beispiel #2
0
 def test_get_regions(self):
     # All regions
     args = parse_args('-r all')
     regions = get_regions(args)
     self.assertEqual(len(regions), 18)
     # List of regions
     args = parse_args('-r eu-west-1,ap-east-1')
     regions = get_regions(args)
     self.assertEqual(len(regions), 2)
     self.assertIn('eu-west-1', regions)
     self.assertIn('ap-east-1', regions)
     # Single region
     args = parse_args('-r ap-east-1')
     regions = get_regions(args)
     self.assertEqual(regions, ['ap-east-1'])
     # Invalid regions
     with self.assertRaises(ValueError):
         args = parse_args('-r test')
         args.region = None
         get_regions(args)
     with self.assertRaises(ValueError):
         args = parse_args('-r test')
         args.region = ''
         get_regions(args)
     with self.assertRaises(ValueError):
         get_regions(parse_args('-r test'))
Beispiel #3
0
 def test_get_regions(self):
     # All regions
     args = parse_args("-r all")
     regions = get_regions(args)
     self.assertEqual(len(regions), 20)
     # List of regions
     args = parse_args("-r eu-west-1,ap-east-1")
     regions = get_regions(args)
     self.assertEqual(len(regions), 2)
     self.assertIn("eu-west-1", regions)
     self.assertIn("ap-east-1", regions)
     # Single region
     args = parse_args("-r ap-east-1")
     regions = get_regions(args)
     self.assertEqual(regions, ["ap-east-1"])
     # Invalid regions
     with self.assertRaises(ValueError):
         args = parse_args("-r test")
         args.region = None
         get_regions(args)
     with self.assertRaises(ValueError):
         args = parse_args("-r test")
         args.region = ""
         get_regions(args)
     with self.assertRaises(ValueError):
         get_regions(parse_args("-r test"))
Beispiel #4
0
 def test_parse_args(self):
     # Reset sys.argv
     exe = argv[0]
     argv.clear()
     argv.append(exe)
     # No arguments - default values
     args = parse_args()
     self.assertIsNone(args.function)
     self.assertIsNone(args.input)
     self.assertEqual(args.output, "lambdaguard_output")
     self.assertIsNone(args.profile)
     self.assertEqual(args.keys, [None, None])
     self.assertEqual(args.region, "all")
     self.assertIsNone(args.sonarqube)
     self.assertFalse(args.verbose)
     self.assertFalse(args.html)
     # Parse custom arguments
     args = parse_args("-o output -v -f function -k id secret")
     self.assertEqual(args.output, "output")
     self.assertEqual(args.function, "function")
     self.assertEqual(args.keys, ["id", "secret"])
     self.assertTrue(args.verbose)
Beispiel #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, "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("")
Beispiel #6
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('')