Unable to activate the AWS IoT security audit using CDK

I'm trying to activate the AWS IoT security audit using a CDK stack, but I'm encountering some issues.

Initially, I referred to this documentation for the interfaceAuditCheckConfigurationProperty and implemented the following CDK code to enable the IoT security audit:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { aws_iot as iot } from 'aws-cdk-lib';

export class CdkIotDeviceDefenderStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const auditCheckConfigurationProperty: iot.CfnAccountAuditConfiguration.AuditCheckConfigurationProperty = {
      enabled: true,
    };

    //https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iot.CfnAccountAuditConfiguration.AuditCheckConfigurationsProperty.html
    const auditCheckConfigurationsProperty: iot.CfnAccountAuditConfiguration.AuditCheckConfigurationsProperty = {
        deviceCertificateExpiringCheck: {
            enabled: true,
        }
    };

  }
}

However, this approach did not yield the desired results. Subsequently, I attempted another method by integrating the AWS SDK within the CDK to create resources in cloudformation. Here is the complete code:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

import { IoTClient, UpdateAccountAuditConfigurationCommand } from " @aws-sdk/client-iot ";

import * as sns from 'aws-cdk-lib/aws-sns';
import * as subscriptions from 'aws-cdk-lib/aws-sns-subscriptions';

export class CdkIotDeviceDefenderStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const expiredDeviceCertificateSNTopic = new sns.Topic(this, "SNSDeviceDefender", {
      displayName: 'Device Defender Expired Certificate SNS',
      fifo: false
    });

    const clientIoT = new IoTClient({ region: "us-west-2" });
    
    const auditCheckConfigParams: any = {
        roleArn: "arn:aws:iam::996242555412:role/Role_AWSIoTDeviceDefenderAudit",
        auditNotificationTargetConfigurations: {
            "SNS": {
                "targetArn": expiredDeviceCertificateSNTopic.topicArn,
                "roleArn": "arn:aws:iam::996242555412:role/Role_AWSIoTDeviceDefenderAudit",
                "enabled": true
            }
        },
        auditCheckConfigurations: {
            "DEVICE_CERTIFICATE_EXPIRING_CHECK": {
              enabled: true,
            }
        }
    };
    (async () => {
        try {
            const iotUpdateCmd = new UpdateAccountAuditConfigurationCommand(auditCheckConfigParams);
            const iotUpdateResponse = await clientIoT.send(iotUpdateCmd);
        } catch { }
    })();

  }
}

In this approach, I set up an SNS topic to receive the device defender audit results.

Despite these efforts, I have not been able to achieve the desired outcome. When running the CDK, the expected result should show both the Device Defender audit settings and Device certificate expiring as enabled (as seen here: https://i.stack.imgur.com/lPgei.png). However, what I am currently experiencing with both methods is that the Device Defender audit settings remain disabled - indicating that the IoT security audit is off (https://i.stack.imgur.com/iubm0.png).

I am at a loss and would appreciate any insights or suggestions on what might be missing in my implementation.

Answer №1

Below is the custom CDK stack created in Python to implement Device Defender, generate audits, and send notifications via SNS:

class CustomDeviceDefenderStack(Stack):
    def __init__(
        self,
        scope: Construct,
        construct_id: str,
        env: Environment,
        env_params: dict,
        **kwargs
    ) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # IAM Role Creation for Device Defender
        device_defender_account_audit_role = iam.Role(
            self,
            "DeviceDefenderAccountAuditRole",
            assumed_by=iam.ServicePrincipal("iot.amazonaws.com"),
        )

        device_defender_account_audit_role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name(
                "service-role/AWSIoTDeviceDefenderAudit"
            )
        )

        topic = sns.Topic(
            self,
            "DeviceDefenderSnsTopic",
            topic_name="device-defender-audit-topic",
            display_name="IoT Defender audit notifications",
        )

        iot_allow_sns_role = iam.Role(
            self,
            "IoTAllowSNSRole",
            assumed_by=iam.ServicePrincipal("iot.amazonaws.com"),
            path="/",
        )

        # Attaching Policy to IAM Role
        policy_attachment = iam.Policy(
            self,
            "SnsPolicyAttachment",
            policy_name="IotDeviceDefenderSnsPolicy",
            statements=[
                iam.PolicyStatement(
                    actions=["sns:Publish"], resources=[topic.topic_arn]
                )
            ],
        )

        iot_allow_sns_role.attach_inline_policy(policy_attachment)

        cfn_account_audit_configuration = iot.CfnAccountAuditConfiguration(
            self,
            "AccountAuditConfiguration",
            account_id=env.account,
            audit_check_configurations=iot.CfnAccountAuditConfiguration.AuditCheckConfigurationsProperty(
                authenticated_cognito_role_overly_permissive_check=iot.CfnAccountAuditConfiguration.AuditCheckConfigurationProperty(
                    enabled=True
                ),
                ca_certificate_expiring_check=iot.CfnAccountAuditConfiguration.AuditCheckConfigurationProperty(
                    enabled=True
                ),
                
             /* The rest of the code remains unchanged */
         
        )

        dd_scheduled_audit.add_depends_on(cfn_account_audit_configuration)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error thrown due to missing property in type '{}' when using TypeScript arrow function parameter

As outlined in the documentation for interfaces in TypeScript, An interface declaration serves as an alternative way to define an object type. I'm puzzled by the error I encounter in the following code snippet. My attempt is to restrict the object ...

"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript: // inquiry.ts ...

Inconsistency with Angular 4 instance variables causes ambiguity within a function

Here is the code snippet: @Component({ selector: 'unb-navbar', templateUrl: './navbar.html' }) export class NavbarComponent implements OnInit { @Input() brand: string; controlador:boolean=false; overlay:string=""; @Input() menu ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

The parameter type must be a string, but the argument can be a string, an array of strings, a ParsedQs object, or an array of ParsedQs objects

Still learning when it comes to handling errors. I encountered a (Type 'undefined' is not assignable to type 'string') error in my code Update: I added the entire page of code for better understanding of the issue. type AuthClient = C ...

Is it possible to implement lazy loading for data in TypeScript classes?

Looking to optimize my Angular application's data structure when consuming a RESTful API. My goal is to only load necessary data from the server on demand. For instance, if I have a collection of Building objects each with a set of tenant IDs in an a ...

Typescript interface requiring both properties or none at all

I possess key-value pairs that must always be presented together in a set. Essentially, if I have one key with its value A:B, then there should also be another key with its value C:D. It is permissible for the object to contain neither pair as well. (An ex ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

Using subscribe method to return an observable within a function

Looking to develop a service that interacts with the Spotify API, I require an authorization bearer token. The token is obtained from another service, which returns an observable. How can these two components be integrated together? Initial attempt: getS ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Methods in Ionic to call an external JavaScript file from TypeScript

Having a JSON list stored in a JavaScript file, my objective is to filter it using TypeScript before sending the filtered results to the HTML homepage. However, I encountered an issue within the HTML file. It's worth mentioning that when running the ...

How can we pass an optional boolean prop in Vue 3?

Currently, I am in the process of developing an application using Vue 3 and TypeScript 4.4, bundled with Vite 2. Within my project, there exists a file named LoginPage.vue containing the following code: <script lang="ts" setup> const props ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

Typescript - ensure only one specific value is in an array of length N

Is there a way to require the 'foo' literal, while allowing the array to have any shape (i.e. not using an X-length tuple with pre-defined positions)? type requireFoo = ??? const works: requireFoo = ['bar','foo'] //This shoul ...

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...