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

Translate Typescript into Javascript for use in React applications

Can anyone assist me in converting this Typescript code to Javascript? function ImageMagnifier({ src, width, height, magnifierHeight = 100, magnifieWidth = 100, zoomLevel = 1.5 }: { src: string; width?: string; height?: string; magnifie ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

Unable to locate module, encountered a webpack alias issue while using typescript and react

I'm currently in the process of setting up aliases in webpack. My goal is to make importing components in App.js easier by replacing: ./components/layout/Header/Header with: @components/layout/Header/Header This way, I can avoid potential issues w ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...

Using TypeScript with React Bootstrap's <Col> component and setting the align attribute to 'center' can trigger a TS2322 warning

The React app I'm working on includes the code below. The Col component is imported from React-bootstrap <Col md={5} align="center"> This is a column </Col> When using Typescript, I received the following warning: ...

Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code export class CodeLib { private static _instance: CodeLib; constructor() { } static get instance(): CodeLib { if(!this._instance){ ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

"Error: Variable becomes undefined due to the implementation of async-await in TypeScript

There has been a persistent issue I've been dealing with for some time now. The problem lies in the fact that vm_res is undefined within the async update_vm_raw_device function despite the function running smoothly. As a result, the value being update ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

Retrieve information from an axios fetch call

Having an issue with the response interface when handling data from my server. It seems that response.data.data is empty, but response.data actually contains the data I need. Interestingly, when checking the type of the last data in response.data.data, it ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

When TypeScript error "ts(18004)" occurs, it is because of the object properties within all Prisma DB

I am currently in the process of verifying if a user's email already exists. To achieve this, I am utilizing Prisma Client's findUnique method. Below is the code snippet I have implemented: const userWithEmail = await prisma.user.findUnique({ ...