Giter VIP home page Giter VIP logo

aws-iot-fleet-provisioning's Introduction

Device Fleet Provisioning with AWS IoTCore

Updates:

  • Now with the ability to respond to cert rotation requests. When the device has been informed it needs to rotate certificates, simply set an additional (optional) attribute isRotation = True. This update is used in conjunction with a cert_rotation policy specified below. This solution relies on setting a cert_issuance date in the registry when the certificate is registered. This is handled by the provisioning template. Once the device is notified, it can process the rotation through setting the flag below.
provisioner.get_official_certs(callback, isRotation=True)

It can often be difficult to manage the secure provisioning of myriad IoT devices in the field. This process can often involve invasive workflow measures, qualified personnel, secure handling of sensitive information, and management of dispensed credentials. Through IoT Core, AWS Fleet Provisioning provides a service oriented, api approach to managing credentials. To learn more about these rich capabilities, read here: https://docs.aws.amazon.com/iot/latest/developerguide/iot-provision.html

To aid in the adoption and utilization of the functionality mentioned above, this repo provides a reference client to illustrate how device(s) might interact with the provided services to deliver the desired experience. Specifically, the client demonstrates how a common "bootstrap" certificate (placed on n devices) can, upon a first-run experience:

  1. Connect to IoTCore with stringent bootstrap credentials
  2. Obtain a unique private key and "production" certificate
  3. Present proof of ownership of the production credentials
  4. Prompt the execution of a provisioning template (custom provisioning logic)
  5. Rotate the certificates (decommission bootstrap, promote new cert)
  6. Test the rights of the newly acquired certificate.

Dependencies of the solution

  • Intended to be compatible with AWS Greengrass ... this solution depends on a python library (asyncio) which is only available w/ python 3.7 and above. Please ensure your solution has at least this version.

  • A .NET Core port of the reference client application is available within the dotnet-core folder - this does not currently support certificate rotation feature available on the Python version.

  • With any connection to IoT Core, you will require the addition of a root CA. We have included a root ca in the repo for convenience but we can't guarantee it will remain current. You can download/replace the contents from the latest contents here: https://www.amazontrust.com/repository/AmazonRootCA1.pem

  • It is recommended to use the general sample provisioning template below if you want the provisioning template to create a thing in IoT Core, Activate the cert, etc. Specifically, ensure the THING node attributes are included in YOUR template if you don't use it verbatim.

In order to run the client solution seamlessly you must configure dependencies in 2 dimensions: AWS Console / Edge Device

On the AWS Console:

Create a common bootstrap certificate.

  1. Go to the IoT Core Service, and in the menu on the left select Secure and finally, Certificates.
  2. Select Create to create your common bootstrap certificates.
  3. Choose One Click Certificate Creation (This will create your bootstrap cert to be placed on all devices)
  4. Download and store certificates.
  5. ! Don't forget to download a root.ca.pem and select the button to ACTIVATE your certificate on the same screen.

Create Provisioning Template / Attach Policies

  1. In console, select Onboard and then Fleet Provisioning Templates and finally, Create.
  2. Name your provisioning template (e.g. - birthing_template). Remember this name!
  3. Create or associate a basic IoT Role with this template. (at least - AWSIoTThingsRegistration)
  4. Select "Use the AWS IoT registry ..." to ensure the sample code works appropriately as it creates things here.
  5. Select Next
  6. Create or select the policy that you wish fully provisioned devices to have. (see sample open policy below)
  7. Select Next
  8. Enter a Thing name prefix (e.g. MyDevices_) and optionally type, groups or attributes for fully provisioned devices.
  9. Select Create Template
  10. Select the bootstrap certificate you created above and click the Attach Policy button.
  11. Ignore the section on Create IAM role to Provision devices, and select Enable template.
  12. Now select close to return to the console.

On the Edge device

Basic python hygiene

  1. Clone the aws-iot-fleet-provisioning repo to your edge device.
  2. Consider running the solution in a python virtual environment.
  3. Install python dependencies: pip3 install -r requirements.txt (requirements.txt located in solution root)

Solution setup

  1. Take your downloaded bootstrap credentials (including root.ca.pem) and securely store them on your device.
  2. Find config.ini within the solution and configure the below parameters:
SECURE_CERT_PATH = PATH/TO/YOUR/CERTS
ROOT_CERT = root.ca.pem
CLAIM_CERT = xxxxxxxxxx-certificate.pem.crt
SECURE_KEY = xxxxxxxxxx-private.pem.key
IOT_ENDPOINT = xxxxxxxxxx-ats.iot.us-east-1.amazonaws.com
PRODUCTION_TEMPLATE = my_template (e.g. - birthing_template)
CERT_ROTATION_TEMPLATE = my_certrotation_template

Run solution (may need to use sudo if storing certificates in a protected dir)

  1. python3 main.py

##### CONNECTING WITH PROVISIONING CLAIM CERT #####
##### SUCCESS. SAVING KEYS TO DEVICE! #####
##### CREATING THING ACTIVATING CERT #####
##### CERT ACTIVATED AND THING birth_1234567-abcde-fghij-klmno-1234567abc-TLS350 CREATED #####
##### CONNECTING WITH OFFICIAL CERT #####
##### ACTIVATED AND TESTED CREDENTIALS (xxxxxxxxxx-private.pem.key, xxxxxxxxxx-certificate.pem.crt). #####
##### FILES SAVED TO PATH/TO/YOUR/CERTS #####

If the solution runs without error, you should notice the new certificates saved in the same directory as the bootstrap certs. You will also notice the creation of THINGS in the IoT Registry that are activated. As this solution is only meant to demo the solution, each subsequent run will use the original bootstrap cert to request new credentials, and therefore also create another thing. Thing names are created based on a hardcoded GUID-Like string (name however you'd like), alternatively, a randomly generated serial number is also shown (commented out) in the code.

See below for examples of necessary artifacts as part of this solution:

Sample "birth_policy" applied to a bootstrap certificate with permissions limited only to provisioning api's.

Note: If using the fleet provisioning feature in the console, this policy will be applied to the certificate automatically. Also, if you intend to copy/paste the below policy note the arn's and change the region/account number as appropriate.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": "<PUT DESIRED RESOURCE ARN(s) HERE.'*' may be used to showcase features but not recommended for real implementations>"
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:us-east-1:XXXXXXXXXXXX:topic/$aws/certificates/create/*",
        "arn:aws:iot:us-east-1:XXXXXXXXXXXX:topic/$aws/provisioning-templates/birthing_template/provision/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "iot:Subscribe",
      "Resource": [
        "arn:aws:iot:us-east-1:XXXXXXXXXXXX:topicfilter/$aws/certificates/create/*",
        "arn:aws:iot:us-east-1:XXXXXXXXXXXX:topicfilter/$aws/provisioning-templates/birthing_template/provision/*"
      ]
    }
  ]
}

Sample Policy for fully provisioned devices - aptly named 'full_citizen_role'

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Subscribe",
        "iot:Connect",
        "iot:Receive"
      ],
      "Resource": [
        "<PUT DESIRED RESOURCE ARN(s) HERE.'*' may be used to showcase features but not recommended for real implementations>"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:GetThingShadow",
        "iot:UpdateThingShadow",
        "iot:DeleteThingShadow"
      ],
      "Resource": [
        "<PUT DESIRED RESOURCE ARN(s) HERE.'*' may be used to showcase features but not recommended for real implementations>"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "greengrass:*"
      ],
      "Resource": [
        "<PUT DESIRED RESOURCE ARN(s) HERE.'*' may be used to showcase features but not recommended for real implementations>"
      ]
    }
  ]
}

Sample provisioning hook where you validate the request before activating a certificate

import json
from datetime import date

provision_response = {
    'allowProvisioning': False,
    "parameterOverrides": {"CertDate": date.today().strftime("%m/%d/%y")}
}


def handler(event, context):

    ########################
    ## Stringent validation against internal API's/DB etc to validate the request before proceeding
    ##
    ## if event['parameters']['SerialNumber'] = "approved by company CSO":
    ##     provision_response["allowProvisioning"] = True
    #####################
    
  
    return provision_response

Sample provisioning template JSON

{
  "Parameters": {
    "CertDate": {
      "Type": "String"
    },
    "deviceId": {
      "Type": "String"
    },
    "AWS::IoT::Certificate::Id": {
      "Type": "String"
    }
  },
  "Resources": {
    "certificate": {
      "Properties": {
        "CertificateId": {
          "Ref": "AWS::IoT::Certificate::Id"
        },
        "Status": "Active"
      },
      "Type": "AWS::IoT::Certificate"
    },
    "policy": {
      "Properties": {
        "PolicyName": "fleetprov_prod_template"
      },
      "Type": "AWS::IoT::Policy"
    },
    "thing": {
      "OverrideSettings": {
        "AttributePayload": "MERGE",
        "ThingGroups": "DO_NOTHING",
        "ThingTypeName": "REPLACE"
      },
      "Properties": {
        "AttributePayload": {
          "cert_issuance": {
            "Ref": "CertDate"
          }
        },
        "ThingGroups": [],
        "ThingName": {
          "Ref": "deviceId"
        }
      },
      "Type": "AWS::IoT::Thing"
    }
  },
  "DeviceConfiguration": {
  }
}

Sample Cert Rotation Provisioning Template. Used to activate a new AWS IoT Certificate, and update the cert_issuance attribute in the registry.

{
  "Parameters": {
    "SerialNumber": {
      "Type": "String"
    },
    "CertDate": {
      "Type": "String"
    },
    "AWS::IoT::Certificate::Id": {
      "Type": "String"
    }
  },
  "Resources": {
    "certificate": {
      "Properties": {
        "CertificateId": {
          "Ref": "AWS::IoT::Certificate::Id"
        },
        "Status": "Active"
      },
      "Type": "AWS::IoT::Certificate"
    },
    "policy": {
      "Properties": {
        "PolicyName": "fleetprov_prod_template"
      },
      "Type": "AWS::IoT::Policy"
    },
    "thing": {
      "OverrideSettings": {
        "AttributePayload": "REPLACE",
        "ThingGroups": "REPLACE",
        "ThingTypeName": "REPLACE"
      },
      "Properties": {
        "AttributePayload": {
          "cert_issuance": {
            "Ref": "CertDate"
          }
        },
        "ThingGroups": [],
        "ThingName": {
          "Ref": "SerialNumber"
        }
      },
      "Type": "AWS::IoT::Thing"
    }
  }
}

Sample AWS Lambda function used as a provisioning hook for cert rotation requests.

import json
import boto3
from datetime import date, timedelta

client = boto3.client('iot')
endpoint = boto3.client('iot-data')

#used to validate device actually needs a new cert
CERT_ROTATION_DAYS = 360

#validation check date for registry query
target_date = date.today()-timedelta(days=CERT_ROTATION_DAYS)
target_date = target_date.strftime("%Y%m%d")

#Set up payload with new cert issuance date
provision_response = {'allowProvisioning': False, "parameterOverrides": {
    "CertDate": date.today().strftime("%Y%m%d")}}


def handler(event, context):

    # Future log Cloudwatch logs
    print("Received event: " + json.dumps(event, indent=2))

    thing_name = event['parameters']['SerialNumber']
    response = client.describe_thing(
    thingName=thing_name)
 
    try:
      #Cross reference ID of requester with entry in registry to ensure device needs a rotation.
      if int(response['attributes']['cert_issuance']) < int(target_date):
        provision_response["allowProvisioning"] = True
    except:
      provision_response["allowProvisioning"] = False

    return provision_response

Sample Lambda used by Cloudwatch as a monitoring agent to notify devices when they're due for a cert rotation

import json
import boto3
from datetime import date, timedelta

client = boto3.client('iot')
endpoint = boto3.client('iot-data')

#Set Cert Rotation Interval
CERT_ROTATION_DAYS = 360

#Check for certificate expiry due in next 2 weeks.
target_date = date.today()-timedelta(days=CERT_ROTATION_DAYS)

#Convert to numeric format
target_date = target_date.strftime("%Y%m%d")


def lambda_handler(event, context):
  
  response = client.search_index(
    queryString='attributes.cert_issuance<{}'.format(target_date),
    maxResults=100)
 
  for thing in response['things']:
    endpoint.publish(
      topic='cmd/{}'.format(thing['thingName']),
      payload='{"msg":"rotate_cert"}'
      )
  
  return {
    'things': response['things']
  }

License

This library is licensed under the MIT-0 License. See the LICENSE file.

aws-iot-fleet-provisioning's People

Contributors

amazon-auto avatar esimonov avatar floydpink avatar moritalous avatar raleighsf avatar rrangnekar-aws avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-iot-fleet-provisioning's Issues

Missing subscribe for the /accepted response topics?

I can’t find anywhere that the /accepted topics are subscribed to. It has the /rejected topics subscribed for the errors, but doesn’t have the /accepted topics for the success. Is this a bug or does the broker handle these provisioning call responses special?

RuntimeError: 1033 (AWS_IO_TLS_CTX_ERROR): Failed to create tls context

Having a problem getting the Python reference client working.

OS: Linux
SSL Libs: openssl 1.1.1.k-1, python-pyopenssl 20.0.1-1
Python Version: 3.8

Traceback (most recent call last):
File "main.py", line 79, in
run_provisioning(isRotation=False)
File "main.py", line 73, in run_provisioning
provisioner.get_official_certs(callback)
File "/home/apachler/Development/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 160, in get_official_certs
return asyncio.run(self.orchestrate_provisioning_flow(callback))
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/apachler/Development/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 164, in orchestrate_provisioning_flow
self.core_connect()
File "/home/apachler/Development/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 86, in core_connect
self.primary_MQTTClient = mqtt_connection_builder.mtls_from_path(
File "/home/apachler/.local/lib/python3.8/site-packages/awscrt/awsiot_mqtt_connection_builder.py", line 201, in mtls_from_path
return _builder(tls_ctx_options, **kwargs)
File "/home/apachler/.local/lib/python3.8/site-packages/awscrt/awsiot_mqtt_connection_builder.py", line 162, in _builder
tls_ctx = awscrt.io.ClientTlsContext(tls_ctx_options)
File "/home/apachler/.local/lib/python3.8/site-packages/awscrt/io.py", line 410, in init
self._binding = _awscrt.client_tls_ctx_new(
RuntimeError: 1033 (AWS_IO_TLS_CTX_ERROR): Failed to create tls context

Rotation Template

Hi there, I'm interested in using AWS IoT Fleet Provisioning. Your sample helps a lot!
I see that recently you've made an update regarding certificate rotation, and somehow one has to have a "rotation template", may I know how to create such a template? I'm just a beginner in AWS, so I'm looking for a way to do it with AWS console. I'd also like to know if there's a way to create "rotation template" with CloudFormation.

thanks a lot!

Risk: over-authorization of AWS IoT policy

We are a security research team and we recently discovered that there is an over-authorization security issue with this project's IoT policy.
The affected file is as following:

1. aws-iot-fleet-provisioning/README.md

Does not build on ARM64. Requires dependency update.

This project does not currently build on ARM64 due to awslabs/aws-crt-python#228
This has already been fixed in awscrt which is a dependency of awsiotsdk.
Updating to the latest version of awsiotsdk in requirements.txt will resolve this build problem on arm64.
Updating awscrt seems to cause a small change in behaviour. Only the root CA cert must be provided in DER instead of PEM format or else the TLS context can't be set up.
If you run into any other problems then io.init_logging(awscrt.io.LogLevel.Trace, 'stdout') is your friend.

Serial number is hardcoded opposed to a wording on README.md

README.md says "Thing names are based on a dynamically generated serial number presented in the code."

Code says:

# Sample Provisioning Template requests a serial number as a 
# seed to generate Thing names in IoTCore. Simulating here.
#self.unique_id = str(int(round(time.time() * 1000)))
        self.unique_id = "1234567-abcde-fghij-klmno-1234567abc-TLS350" 

Either code or doc needs to be updated

AWS generated certificates expiry clarifications

We are using device provisioning workflow provided by AWS i.e., provisioning by claim method. Regarding certificate expiry , we would like to understand whether it is possible to set other than default expiry i.e., year 2049 ...because we have requirement to keep it short life span for certificates used by IotDevices

Appreciate your help and response on this clarification

AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE when trying Fleet Provisioning

Hi,
I am trying Fleet Provisioning on Cloud 9 (Amazon Linux) and need your help, since I have an error as below.
I've installed all python dependencies (pip3 install -r requirements.txt).
I've made Fleet provisioning template and bootstrap certificate, and updated config.ini accordingly.

I am using awsiotsdk as below.
awsiotsdk in /home/linuxbrew/.linuxbrew/lib/python3.8/site-packages (1.5.2)
awscrt==0.9.10 in /home/linuxbrew/.linuxbrew/lib/python3.8/site-packages (from awsiotsdk) (0.9.10)

But, I have below error:
awscrt.exceptions.AwsCrtError: AwsCrtError(name='AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE', message='TLS (SSL) negotiation failed', code=1029)

Could you please let me know if there is any solution for this error?

sa:~/environment/aws-iot-fleet-provisioning (master) $ python3 main.py
______ __ __
/ / / / ___ ___ / /
/ /
/ / / _ \ / _ \ / __/
/ __/ / / / __/ / _/ / /
/
/ /
/ _/ _/ __/

____                  _      _             _            

/ __ _________ _ ()() ____ ()_ ____ _
/ // / / __ \ | / / / / / __ / __ / / __ / __ `/
/ / / / // / |/ / ( ) / // / / / / / / / / /
/ /
/
/ /
/ _
/|
////_// //// //_, /
/
___/


///////////

CONNECTING WITH PROVISIONING CLAIM CERT

Connecting to a9y1ao0iqy0he.iot.us-east-1.amazonaws.com with client ID '1234567-abcde-fghij-klmno-1234567abc-TLS350'...
Traceback (most recent call last):
File "main.py", line 79, in
run_provisioning(isRotation=False)
File "main.py", line 73, in run_provisioning
provisioner.get_official_certs(callback)
File "/home/ec2-user/environment/aws-iot-fleet-provisioning/provisioning_handler.py", line 160, in get_official_certs
return asyncio.run(self.orchestrate_provisioning_flow(callback))
File "/home/linuxbrew/.linuxbrew/Cellar/[email protected]/3.8.6/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/home/linuxbrew/.linuxbrew/Cellar/[email protected]/3.8.6/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/ec2-user/environment/aws-iot-fleet-provisioning/provisioning_handler.py", line 164, in orchestrate_provisioning_flow
self.core_connect()
File "/home/ec2-user/environment/aws-iot-fleet-provisioning/provisioning_handler.py", line 101, in core_connect
connect_future.result()
File "/home/linuxbrew/.linuxbrew/Cellar/[email protected]/3.8.6/lib/python3.8/concurrent/futures/_base.py", line 439, in result
return self.__get_result()
File "/home/linuxbrew/.linuxbrew/Cellar/[email protected]/3.8.6/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result
raise self._exception
awscrt.exceptions.AwsCrtError: AwsCrtError(name='AWS_IO_TLS_ERROR_NEGOTIATION_FAILURE', message='TLS (SSL) negotiation failed', code=1029)

provisioner.get_official_certs(callback) gives error: [Errno -2] Name or service not known

Hello Sir,
While starting main.py I`m getting error: [Errno -2] Name or service not known
Could you help me with this?
Maybe my config.ini not correct....(if possible expand README.md for howto fill config.ini)
What should I point in IOT_ENDPOINT?
IOT_ENDPOINT = ( ? )-ats.iot.eu-north-1.amazonaws.com

Certificate is active.

Files in cert folder:

d2b2c2522a-certificate.pem.crt
d2b2c2522a-private.pem.key
d2b2c2522a-public.pem.key
root.ca.pem

config.ini file:

[SETTINGS]
# Set the path to the location containing your certificates (root, private, claim certificate)
SECURE_CERT_PATH = /home/user/Documents/aws-iot-fleet-provisioning/certs

# Specify the names for the root cert, provisioning claim cert, and the private key.
ROOT_CERT = root.ca.pem
CLAIM_CERT = d2b2c2522a-certificate.pem.crt
SECURE_KEY = d2b2c2522a-private.pem.key

# Set the name of your IoT Endpoint
IOT_ENDPOINT = MyDevices_-ats.iot.eu-north-1.amazonaws.com

# Include the name for the provisioning template that was created in IoT Core
PRODUCTION_TEMPLATE = birthing_template
CERT_ROTATION_TEMPLATE = cert_rotation

Attached policy
(region&id are correct):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:eu-north-1:592957381234:topic/$aws/certificates/create/*",
        "arn:aws:iot:eu-north-1:592957381234:topic/$aws/provisioning-templates/birthing_template/provision/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe"
      ],
      "Resource": [
        "arn:aws:iot:eu-north-1:592957381234:topicfilter/$aws/certificates/create/*",
        "arn:aws:iot:eu-north-1:592957381234:topicfilter/$aws/provisioning-templates/birthing_template/provision/*"
      ]
    }
  ]
}

regarding cert rotation policy

this article helps to create workflow for device provisioning....i have one question regarding cert rotation.
do we need to create two polices AWS cloud one for initial provisioning template and other for cert rotation template ...

On device side, to subscribe for cert rotation topic command , once it receives notification, it initiates with cert rotation template ...is this correct?

Also, execution time limitation on pre-validation lambda hook , it is mentioned as 5 sec as per document, Is it possible to increase this ?

AwsCrtError: AWS_ERROR_MQTT_UNEXPECTED_HANGUP

I clone this repo on my jetson nano board, and successfully install dependencies.
I checked openssl connection to my iot endpoint, and it also success.
But when I run python3 main.py I get this error

Traceback (most recent call last):
  File "main.py", line 81, in <module>
    run_provisioning(isRotation=False)
  File "main.py", line 74, in run_provisioning
    provisioner.get_official_certs(callback)
  File "/home/li/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 161, in get_official_certs
    return asyncio.run(self.orchestrate_provisioning_flow(callback))
  File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
    return future.result()
  File "/home/li/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 165, in orchestrate_provisioning_flow
    self.core_connect()
  File "/home/li/IOT/aws-iot-fleet-provisioning/provisioning_handler.py", line 102, in core_connect
    connect_future.result()
  File "/usr/lib/python3.7/concurrent/futures/_base.py", line 435, in result
    return self.__get_result()
  File "/usr/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
awscrt.exceptions.AwsCrtError: AwsCrtError(name='AWS_ERROR_MQTT_UNEXPECTED_HANGUP', message='The connection was closed unexpectedly.', code=5134)

I checked policy as well, and it looks correct.

"statusCode":403 error

pi@raspberrypi:~/다운로드/aws-iot-fleet-provisioning-master $ python3 main.py
                 ______   __                   __
                / ____/  / /  ___     ___     / /_
               / /_     / /  / _ \   / _ \   / __/
              / __/    / /  /  __/  /  __/  / /_
             /_/      /_/   \___/   \___/   \__/


    ____                  _      _             _
   / __ \_________ _   __(_)____(_)___  ____  (_)___  ____ _
  / /_/ / ___/ __ \ | / / / ___/ / __ \/ __ \/ / __ \/ __ `/
 / ____/ /  / /_/ / |/ / (__  ) / /_/ / / / / / / / / /_/ /
/_/   /_/   \____/|___/_/____/_/\____/_/ /_/_/_/ /_/\__, /
                                                   /____/



 ____________________________________________________________
/_____/_____/_____/_____/_____/_____/_____/_____/_____/_____/



##### CONNECTING WITH PROVISIONING CLAIM CERT #####
Connecting to ahfuh237qj0y0-ats.iot.ap-northeast-2.amazonaws.com with client ID 'test-0726-hiq'...
Connected!
Subscribing to topic '$aws/provisioning-templates/test-0726-fleet/provision/json/rejected'...
Subscribed with QoS.AT_LEAST_ONCE
Subscribing to topic '$aws/certificates/create/json/rejected'...
Subscribed with QoS.AT_LEAST_ONCE
Subscribing to topic '$aws/provisioning-templates/test-0726-fleet/provision/json/accepted'...
Subscribed with QoS.AT_LEAST_ONCE
Subscribing to topic '$aws/certificates/create/json/accepted'...
Subscribed with QoS.AT_LEAST_ONCE
Received message from topic '$aws/certificates/create/json/accepted': b'{"certificateId":"8311895ab97f4dbde42308f12ddb0394d923cd1d4f1922729f87c86afe0d0a27","certificatePem":"-----BEGIN CERTIFICATE-----\\nMIID~~\n-----END CERTIFICATE-----\\n","privateKey":"-----BEGIN RSA PRIVATE KEY-----\\nMIIE~~\\n-----END RSA PRIVATE KEY-----\\n","certificateOwnershipToken":"eyJ~~"}'
##### SUCCESS. SAVING KEYS TO DEVICE! #####
##### CREATING THING ACTIVATING CERT #####
Received message from topic '$aws/provisioning-templates/test-0726-fleet/provision/json/rejected': b'{"statusCode":403,"errorCode":"AccessDenied","errorMessage":"Access Denied"}'
Failed provisioning
b'{"statusCode":403,"errorCode":"AccessDenied","errorMessage":"Access Denied"}'
//provisioning template
{
  "Parameters": {
    "SerialNumber": {
      "Type": "String"
    },
    "AWS::IoT::Certificate::Id": {
      "Type": "String"
    }
  },
  "Resources": {
    "policy_Greengrass-jetson-nano-core-device-Policy": {
      "Type": "AWS::IoT::Policy",
      "Properties": {
        "PolicyName": "Greengrass-jetson-nano-core-device-Policy"
      }
    },
    "certificate": {
      "Type": "AWS::IoT::Certificate",
      "Properties": {
        "CertificateId": {
          "Ref": "AWS::IoT::Certificate::Id"
        },
        "Status": "Active"
      }
    },
    "thing": {
      "Type": "AWS::IoT::Thing",
      "OverrideSettings": {
        "AttributePayload": "MERGE",
        "ThingGroups": "DO_NOTHING",
        "ThingTypeName": "REPLACE"
      },
      "Properties": {
        "AttributePayload": {},
        "ThingGroups": [],
        "ThingName": {
          "Fn::Join": [
            "",
            [
              "",
              {
                "Ref": "SerialNumber"
              }
            ]
          ]
        }
      }
    }
  }
}

Greengrass-jetson-nano-core-device-Policy : Allow * *

When I run the code, things and certificates are generated, but the certificate says "pending activation".
And the code shows a 403 error.
I left everything in the policy open, but I couldn't find a solution.
How can I solve this problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.