Ejemplo n.º 1
0
    def test_casper_scan_with_detailed(self, MockCasperState):
        mock_casper_state = MockCasperState()

        # create required subnet
        subnets = create_subnet()

        # launch 200 static ec2 instances
        count = 2
        instances = create_static_instances(count)

        # launch 3 autoscaled (dynamic) instances
        create_autoscaling_group(
            name="autoscaler1",
            instance_id=instances[0]["InstanceId"],
            subnet=subnets[0],
            count=3,
        )

        casper = Casper()
        casper.casper_state = mock_casper_state
        mock_casper_state.state_resources = {}

        for svc in get_supported_services():
            ghosts = casper.scan(svc, detailed=True)
            print(ghosts)
            for resource_group in ghosts:
                self.assertTrue("resources" in ghosts[resource_group])

        mock_casper_state.load_state.assert_not_called()
Ejemplo n.º 2
0
    def test_run_scan_all_supported_services(
        self, mock_build, mock_scan, _, mock_docopt
    ):
        test_args = ["scan"]
        mock_docopt.return_value = docopt(doc, test_args)
        main.cli()
        mock_build.assert_not_called()

        self.assertEqual(len(get_supported_services()), mock_scan.call_count)
Ejemplo n.º 3
0
    def test_casper_scan(self, MockCasperState):
        mock_casper_state = MockCasperState()

        # create required subnet
        subnets = create_subnet()

        # launch 200 static ec2 instances
        count = 2
        instances = create_static_instances(count)

        # launch 3 autoscaled (dynamic) instances
        create_autoscaling_group(
            name="autoscaler1",
            instance_id=instances[0]["InstanceId"],
            subnet=subnets[0],
            count=3,
        )

        # get the default sg which will show up asa ghosts
        ec2_client = boto3.client("ec2", region_name="us-east-1")
        sgs = ec2_client.describe_security_groups()

        ec2 = ec2_client.describe_instances()
        reservations = [
            reservation["Instances"] for reservation in ec2["Reservations"]
        ]

        casper = Casper()
        casper.casper_state = mock_casper_state
        mock_casper_state.state_resources = {}

        aws_instance = [
            instance["InstanceId"] for instance_group in reservations
            for instance in instance_group if instance["State"]["Code"] == 16
        ]
        aws_security_group = [sg["GroupId"] for sg in sgs["SecurityGroups"]]
        aws_alb = []
        aws_elb = []

        expected_ghosts = {
            "ec2": {
                "aws_instance": {
                    "ids": aws_instance,
                    "count": 5
                },
                "aws_autoscaling_group": {
                    "ids": ["autoscaler1"],
                    "count": 1
                },
                "aws_security_group": {
                    "ids": aws_security_group,
                    "count": 2
                },
                "aws_alb": {
                    "ids": aws_alb,
                    "count": 0
                },
                "aws_elb": {
                    "ids": aws_elb,
                    "count": 0
                },
            },
            "s3": {
                "aws_s3_bucket": {
                    "count": 0,
                    "ids": []
                }
            },
            "iam": {
                "aws_iam_role": {
                    "count": 0,
                    "ids": []
                },
                "aws_iam_user": {
                    "count": 0,
                    "ids": []
                },
            },
        }

        for svc in get_supported_services():
            ghosts = casper.scan(svc)
            for keys in ghosts:
                self.assertEqual(expected_ghosts[svc][keys]["count"],
                                 ghosts[keys]["count"])
                self.assertSetEqual(set(expected_ghosts[svc][keys]["ids"]),
                                    set(ghosts[keys]["ids"]))

        mock_casper_state.load_state.assert_not_called()
Ejemplo n.º 4
0
def run(
    build_command,
    scan_command,
    root_dir,
    aws_profile,
    detailed,
    output_file,
    exclude_cloud_res,
    services_list,
    exclude_state_res,
    exclude_dirs,
    state_file,
    bucket_name,
    loglevel,
):
    # setup logging
    _setup_logging(loglevel=loglevel)
    logger = logging.getLogger("casper")

    if exclude_cloud_res:
        exclude_cloud_res = set(exclude_cloud_res)

    # casper object
    casper = Casper(
        start_directory=root_dir,
        bucket_name=bucket_name,
        state_file=state_file,
        profile=aws_profile,
        exclude_resources=exclude_cloud_res,
    )

    if build_command:

        if exclude_state_res:
            exclude_state_res = set(exclude_state_res)

        if exclude_dirs:
            exclude_dirs = set(exclude_dirs)

        counters = casper.build(exclude_state_res=exclude_state_res,
                                exclude_directories=exclude_dirs)

        # print state statistics
        states = counters["state"]
        resource_groups = counters["resource_group"]
        resources = counters["resource"]

        print("")
        print("Terraform")
        print("--------------------------------------------------------")
        print(f"{states} state(s) checked")
        print(f"{resource_groups} supported resource group(s) discovered")
        print(f"{resources} state resource(s) saved to bucket")
        print("")

    if scan_command:
        # supported services
        supported_services = get_supported_services()
        if services_list:
            services = [s for s in services_list if s in supported_services]
            if len(services) == 0:
                logger.warning("No supported service specified")
            elif len(services) < len(services_list):
                logger.warning("Ignoring one or more unsupported services")
        else:
            services = supported_services

        svc_ghost = {}
        for svc in services:
            svc_ghost[svc] = casper.scan(service_name=svc, detailed=detailed)

        print("")
        for svc in services:
            print(svc.upper())
            print("--------------------------------------------------------")
            for key in svc_ghost[svc].keys():
                count = svc_ghost[svc][key]["count"]
                if count > 0:
                    print(f"{count} ghost {key} found")
            print("")

        if output_file:
            with open(output_file, "w") as fid:
                fid.write(
                    json.dumps(svc_ghost,
                               indent=4,
                               sort_keys=True,
                               default=str))

            print("--------------------------------------------------------")
            print(f"Full result written to "
                  f"{os.path.join(os.getcwd(), output_file)}")
Ejemplo n.º 5
0
 def test_get_all_supported_service(self):
     for svc in get_supported_services():
         service = get_service(svc)
         self.assertTrue(issubclass(service, Service))
         self.assertIsNotNone(service)