Exemple #1
0
def __register_auth_system(auth_system):
    """Register a given authentication system with the framework. Returns `True` if the `auth_system` is registered
    as the active auth system, else `False`

    Args:
        auth_system (:obj:`BaseAuthPlugin`): A subclass of the `BaseAuthPlugin` class to register

    Returns:
        `bool`
    """
    auth_system_settings = dbconfig.get('auth_system')

    if auth_system.name not in auth_system_settings['available']:
        auth_system_settings['available'].append(auth_system.name)
        dbconfig.set('default', 'auth_system', DBCChoice(auth_system_settings))

    if auth_system.name == auth_system_settings['enabled'][0]:
        app.active_auth_system = auth_system
        auth_system().bootstrap()
        logger.debug('Registered {} as the active auth system'.format(
            auth_system.name))
        return True

    else:
        logger.debug(
            'Not trying to load the {} auth system as it is disabled by config'
            .format(auth_system.name))
        return False
Exemple #2
0
def prep_s3_testing(cinq_test_service, collect_only=False):
    set_audit_scope('aws_s3_bucket')
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'collect_only', collect_only)
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'alert_settings',
                 DBCJSON(STANDARD_ALERT_SETTINGS))

    cinq_test_service.start_mocking_services('cloudwatch', 's3')
Exemple #3
0
def test_audit(cinq_test_service):
    """

    :return:
    """

    # Prep
    recipient = NotificationContact(
        type='email',
        value=dbconfig.get('test_email', NS_CINQ_TEST)
    )
    cinq_test_service.start_mocking_services('ec2')
    account = cinq_test_service.add_test_account(
        account_type='AWS',
        account_name=CINQ_TEST_ACCOUNT_NAME,
        contacts=[{'type': 'email', 'value': dbconfig.get('test_email', NS_CINQ_TEST)}],
        properties={
            'account_number': CINQ_TEST_ACCOUNT_NO
        }
    )

    db_setting = dbconfig.get('audit_scope', NS_AUDITOR_REQUIRED_TAGS)
    db_setting['enabled'] = ['aws_ec2_instance']
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'audit_scope', DBCJSON(db_setting))

    # Add resources
    client = aws_get_client('ec2')
    resource = client.run_instances(ImageId='i-10000', MinCount=1, MaxCount=1)

    # Collect resource
    run_aws_collector(account)

    # Start auditor
    auditor = MockRequiredTagsAuditor()

    # Test 1 --- Test if auditor will pick up non-compliant instances which is still in grace period
    auditor.run()
    assert auditor._cinq_test_notices == {}

    # Test 2 --- Test if auditor will pick up non-compliant instances correctly
    ''' Modify resource property'''
    assert cinq_test_service.modify_resource(
        resource['Instances'][0]['InstanceId'],
        'launch_date',
        '2000-01-01T00:00:00'
    ) is True

    auditor.run()
    notices = auditor._cinq_test_notices

    assert recipient in notices
    assert notices[recipient]['not_fixed'][0]['resource'].resource_id == resource['Instances'][0]['InstanceId']
def test_basic_ops(cinq_test_service):
    """
    Test will pass if:
    1. Auditor can detect non-compliant EC2 instances
    2. Auditor respect grace period settings
    """

    # Prep
    cinq_test_service.start_mocking_services('ec2')

    setup_info = setup_test_aws(cinq_test_service)
    recipient = setup_info['recipient']
    account = setup_info['account']

    db_setting = dbconfig.get('audit_scope', NS_AUDITOR_REQUIRED_TAGS)
    db_setting['enabled'] = ['aws_ec2_instance']
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'audit_scope', DBCJSON(db_setting))
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'collect_only', False)

    # Add resources
    client = aws_get_client('ec2')
    resource = client.run_instances(ImageId='i-10000', MinCount=1, MaxCount=1)

    # Collect resources
    collect_resources(account=account, resource_types=['ec2'])

    # Initialize auditor
    auditor = MockRequiredTagsAuditor()

    # Test 1 --- Test if auditor respect grace period settings
    cinq_test_service.modify_resource(resource['Instances'][0]['InstanceId'],
                                      'launch_date',
                                      datetime.datetime.utcnow().isoformat())
    auditor.run()
    assert auditor._cinq_test_notices == {}

    # Test 2 --- Test if auditor can pick up non-compliant resources correctly
    ''' Modify resource property'''
    assert cinq_test_service.modify_resource(
        resource['Instances'][0]['InstanceId'], 'launch_date',
        '2000-01-01T00:00:00') is True

    auditor.run()
    notices = auditor._cinq_test_notices

    assert recipient in notices
    assert notices[recipient]['not_fixed'][0][
        'resource'].resource_id == resource['Instances'][0]['InstanceId']
Exemple #5
0
def test_audit(cinq_test_service):
    """

    :return:
    """

    # Prep
    cinq_test_service.start_mocking_services('ec2')

    setup_info = setup_test_aws(cinq_test_service)
    recipient = setup_info['recipient']
    account = setup_info['account']

    db_setting = dbconfig.get('audit_scope', NS_AUDITOR_REQUIRED_TAGS)
    db_setting['enabled'] = ['aws_ec2_instance']
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'audit_scope', DBCJSON(db_setting))

    # Tests
    case_1(cinq_test_service, account, recipient)
Exemple #6
0
def set_test_user_role(role):
    dbconfig.set(NS_CINQ_TEST, 'user_role', role)
def prep_s3_testing(cinq_test_service, collect_only=False):
    set_audit_scope('aws_s3_bucket')
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'collect_only', collect_only)

    cinq_test_service.start_mocking_services('cloudwatch', 's3')
def set_audit_scope(*args):
    db_setting = dbconfig.get('audit_scope', NS_AUDITOR_REQUIRED_TAGS)
    db_setting['enabled'] = args
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'audit_scope', DBCJSON(db_setting))
Exemple #9
0
def test_volume_ec2_s3(cinq_test_service):
    """

    :return:
    """
    # Prep
    setup_info = setup_test_aws(cinq_test_service)
    recipient = setup_info['recipient']
    account = setup_info['account']

    set_audit_scope('aws_ec2_instance', 'aws_s3_bucket')
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'collect_only', False)
    cinq_test_service.start_mocking_services('cloudwatch', 'ec2', 's3')

    num_resources = 100
    compliant_buckets = []
    non_compliant_buckets = []
    compliant_ec2 = []
    non_compliant_ec2 = []

    client_s3 = aws_get_client('s3')
    client_ec2 = aws_get_client('ec2')
    regions = get_aws_regions('s3')

    # Workaround for a moto cloudwatch KeyError bug
    regions.remove('eu-west-3')

    # Setup resources
    for i in range(0, num_resources):
        bucket_name = uuid.uuid4().hex
        client_s3.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={'LocationConstraint': random.choice(regions)}
        )
        compliant_buckets.append(bucket_name) if random.randint(0, 1) else non_compliant_buckets.append(bucket_name)

        resource = client_ec2.run_instances(ImageId='i-{}'.format(i), MinCount=1, MaxCount=1)
        instance_id = resource['Instances'][0]['InstanceId']
        compliant_ec2.append(instance_id) if random.randint(0, 1) else non_compliant_ec2.append(instance_id)

    for instance_id in compliant_ec2:
        client_ec2.create_tags(
            Resources=[instance_id],
            Tags=VALID_TAGSET
        )

    for item in compliant_buckets:
        client_s3.put_bucket_tagging(
            Bucket=item,
            Tagging={'TagSet': VALID_TAGSET}
        )

    # collection
    collect_resources(account=account, resource_types=['ec2', 's3'])

    for item in compliant_buckets + non_compliant_buckets:
        cinq_test_service.modify_resource(
            item,
            'creation_date',
            '2000-01-01T00:00:00'
        )

    for instance_id in compliant_ec2 + non_compliant_ec2:
        cinq_test_service.modify_resource(
            instance_id,
            'launch_date',
            '2000-01-01T00:00:00'
        )

    auditor = MockRequiredTagsAuditor()
    auditor.run()

    compliant_resources = compliant_buckets + compliant_ec2
    non_compliant_resources = non_compliant_buckets + non_compliant_ec2
    for item in auditor._cinq_test_notices[recipient]['not_fixed']:
        assert item['resource'].id not in compliant_resources
        assert item['resource'].id in non_compliant_resources

    assert len(non_compliant_resources) == len(auditor._cinq_test_notices[recipient]['not_fixed'])
Exemple #10
0
    def run(self, **kwargs):
        for ep in CINQ_PLUGINS['cloud_inquisitor.plugins.auth']['plugins']:
            if ep.module_name == 'cinq_auth_onelogin_saml':
                cls = ep.load()
                config_namespace = cls.ns
                break
        else:
            self.log.error('The SAML authentication plugin is not installed')
            return

        try:
            ns = {
                'ds': 'http://www.w3.org/2000/09/xmldsig#',
                'saml': 'urn:oasis:names:tc:SAML:2.0:metadata'
            }

            xml = etree.parse(kwargs['metadata'])
            root = xml.getroot()

            idp_entity_id = root.attrib['entityID']
            idp_cert = root.find('.//ds:X509Certificate', ns).text
            idp_sls = root.find('.//saml:SingleLogoutService',
                                ns).attrib['Location']
            idp_ssos = root.find(
                './/saml:SingleSignOnService[@Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"]',
                ns).attrib['Location']

            sp_acs = 'https://{}/saml/login/consumer'.format(kwargs['fqdn'])
            sp_sls = 'https://{}/saml/logout/consumer'.format(kwargs['fqdn'])
            sp_entity_id = kwargs['fqdn']

            dbconfig.set(config_namespace, 'idp_entity_id',
                         DBCString(idp_entity_id))
            dbconfig.set(config_namespace, 'idp_sls', DBCString(idp_sls))
            dbconfig.set(config_namespace, 'idp_ssos', DBCString(idp_ssos))
            dbconfig.set(config_namespace, 'idp_x509cert',
                         DBCString(idp_cert.replace('\n', '')))
            dbconfig.set(config_namespace, 'sp_entity_id',
                         DBCString(sp_entity_id))
            dbconfig.set(config_namespace, 'sp_acs', DBCString(sp_acs))
            dbconfig.set(config_namespace, 'sp_sls', DBCString(sp_sls))

            self.log.info('Updated SAML configuration from {}'.format(
                kwargs['metadata']))

        except OSError as ex:
            self.log.error('Unable to load metadata file {}: {}'.format(
                kwargs['metadata'], ex))
            return 1

        except etree.ParseError as ex:
            self.log.error('Failed reading metadata XML file: {}'.format(ex))
            return 2

        except Exception as ex:
            self.log.error('Error while updating configuration: {}'.format(ex))
            return 3
Exemple #11
0
def prep_rds_testing(cinq_test_service, collect_only=False):
    set_audit_scope('aws_rds_instance')
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'collect_only', collect_only)
    dbconfig.set(NS_AUDITOR_REQUIRED_TAGS, 'alert_settings', DBCJSON(STANDARD_ALERT_SETTINGS))