コード例 #1
0
def list_current_configuration():
    subProcessOut = sys_helper.run_subprocess_cmd(
        cmd=["aws", "configure", "list"], sys_shell=True)
    if subProcessOut.returncode == 0:
        print(subProcessOut.stdout)
    else:
        print("Getting the current configuration failed")
        return 'danger'

    print("\nGetting aws endpoint...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(
        cmd=["aws", "iot", "describe-endpoint"], sys_shell=True)
    if subProcessOut.returncode == 0:
        if subProcessOut.stdout is not None:
            print(subProcessOut.stdout.replace('\n', "").replace("    ", ""))
        else:
            print(
                "No endpoint returned, check under AWS account -> IoT core -> Settings"
            )
    else:
        print(
            "Verify account csv file contents, region and do Config AWS CLI!")
        return 'danger'

    return 'success'
コード例 #2
0
def configure_aws_cli(selected_region):
    try:
        with open(ACCOUNT_CREDENTIALS, mode='r') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            for row in csv_reader:
                access_key_id = row["Access key ID"]
                secret_key_access = row["Secret access key"]

            #Setting the aws cli for the access key
            print("Setting aws access key...", end='')
            subProcessOut = sys_helper.run_subprocess_cmd(cmd=["aws", "configure", "set", "aws_access_key_id", access_key_id], sys_shell=True)
            if subProcessOut.returncode != 0:
                print("Setting AWS access key failed\r\n")
                return 'danger'
            print('OK')

            print("Setting aws secret access key...", end='')
            subProcessOut = sys_helper.run_subprocess_cmd(cmd=["aws", "configure", "set", "aws_secret_access_key", secret_key_access], sys_shell=True)
            if subProcessOut.returncode != 0:
                print("Setting AWS secret key failed\r\n")
                return 'danger'
            print('OK')

            print("Setting aws region...", end='')
            subProcessOut = sys_helper.run_subprocess_cmd(cmd=["aws", "configure", "set", "region", selected_region], sys_shell=True)
            if subProcessOut.returncode != 0:
                print("Setting AWS region failed\r\n")
                return 'danger'
            print('OK')

        return list_current_configuration()
    except:
        print("Verify account csv file existence and its content!")
        return 'danger'
コード例 #3
0
def register_device(manifest_data, validation_cert):
    print("\nRegistering DeviceID started....")
    #Extrat device ID and Finger print to register
    verification_cert = x509.load_pem_x509_certificate(
        data=validation_cert, backend=default_backend())
    device_cert_list = get_device_cert_from_manifest(manifest_data, 0,
                                                     validation_cert)

    ## Checking if the Device ID is already uploaded to the azure iot hub ##
    print("\tFetching list of device registered....", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "device-identity", "list", "--hub-name", hub_name,
        "--query", "[].deviceId"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting device identity failed\r\n")
        return 'danger'
    device_check = subProcessOut.stdout
    device_check_id = re.findall(r'"(.*?)"', device_check)
    print('OK')

    for device_cert in device_cert_list:
        device_id = device_cert.subject.get_attributes_for_oid(
            x509.oid.NameOID.COMMON_NAME)[0].value
        print("\tRegistering Device ID {}...".format(device_id), end='')
        if device_id in device_check_id:
            print("already registered.")
            continue

        ## Registring the Device ID to the azure iot hub ##
        primary_thumbprint = str(
            binascii.hexlify(device_cert.fingerprint(hashes.SHA1())),
            'utf-8').upper()
        secondary_thumbprint = primary_thumbprint

        subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
            "az", "iot", "hub", "device-identity", "create", "-n", hub_name,
            "-d", device_id, "--am", "x509_thumbprint", "--ptp",
            primary_thumbprint, "--stp", secondary_thumbprint
        ],
                                                      sys_newlines=True,
                                                      sys_shell=True)

        if subProcessOut.returncode != 0:
            print("Registering device identity failed\r\n")
            return 'danger'
        print('OK')
    print('Completed registering device.')

    return 'success'
コード例 #4
0
def list_current_configuration():
    subProcessOut = sys_helper.run_subprocess_cmd(
        cmd=["aws", "configure", "list"], sys_shell=True)
    if subProcessOut.returncode == 0:
        print(subProcessOut.stdout)
    else:
        print("Getting the current configuration failed\r\n")
コード例 #5
0
def azure_account_login():
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=["az", "login"],
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Login failed")
        return 'danger'

    print('Extract credentials from csv file...', end='')
    with open(AZURE_HUB_DETAILS, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            global hub_name, sub_id
            hub_name = row["IoT Hub"]
            sub_id = row["Subscription ID"]
    print('OK')
    print('Azure Hostname: {}.azure-devices.net'.format(hub_name))
    print('Azure Subscription ID: {}'.format(sub_id.upper()))

    ## Checking if the azure iot hub name is proper in the credentials file ##
    if hub_name == 'replace_your_host_name_here':
        print(
            'Configure the file {} in docs folder with your azure iot hub name before proceeding\r\n'
            .format(azure_hub_CSV))
        return 'danger'

    ## Checking if the azure iot hub Subscription id is proper in the credentials file ##
    if sub_id == 'replace_your_subscription_id_here':
        print(
            'Configure the file {} in docs folder with your azure iot hub Subscription ID before proceeding\r\n'
            .format(azure_hub_CSV))
        return 'danger'

    print("Setting the Subscription ID....", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(
        cmd=["az", "account", "set", "--subscription", sub_id],
        sys_newlines=True,
        sys_shell=True)
    if subProcessOut.returncode != 0:
        print(
            "Invalid Subscription ID. Make sure the Subscription ID in {} is same as in Azure iot hub"
            .format(azure_hub_CSV))
        return 'danger'
    print('OK')
    return 'success'
コード例 #6
0
def register_device(device_id):
    print("\nRegistering DeviceID started....")

    ## Checking if the Device ID is already uploaded to the azure iot hub ##
    print("Check if the Device is already registered...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "device-identity", "list", "--hub-name", hub_name,
        "--query", "[].deviceId"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting device identity failed\r\n")
        return 'danger'

    device_check = subProcessOut.stdout
    device_check_id = re.findall(r'"(.*?)"', device_check)
    for x in device_check_id:
        if (x == device_id):
            print("Device ID {} already registered.\r\n".format(device_id))
            return 'success'
    print('Proceed to Device registration')

    ## Registring the Device ID to the azure iot hub ##
    print('Register DeviceID...', end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "device-identity", "create", "-n", hub_name, "-d",
        device_id, "--am", "x509_ca"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Registering device identity failed\r\n")
        return 'danger'
    print('OK')

    print("Device ID {} registered.\r\n".format(device_id))
    return 'success'
コード例 #7
0
def register_azure_signer():
    print("\nRegistering Signer started....")
    signer_cer_path = SIGNER_CA_FILENAME_BASE + '.cer'
    with open(signer_cer_path, 'wb') as cer:
        with open(signer_cert_path, 'rb') as crt:
            cer.write(crt.read())

    if not os.path.isfile(signer_cer_path):
        print(
            "No signer certificate found...TrustFLEX resource_generation notebook has to be run with Customer Cert option before running this notebook\r\n"
        )
        return 'danger'

    #Checking if the signer certificate is already uploaded to the Azure iot hub
    print("Check if the Signer is already registered...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "list", "--hub-name", hub_name,
        "--query", "value[].properties[].thumbprint"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting signer list from azure failed")
        return 'danger'
    cert_check = subProcessOut.stdout
    signer_cert_finger = re.findall(r'"(.*?)"', cert_check)
    with open(signer_cer_path, 'rb') as f:
        cert = x509.load_pem_x509_certificate(f.read(), crypto_be)
        fingerprint = binascii.hexlify(cert.fingerprint(
            hashes.SHA1())).decode().upper()
    for x in signer_cert_finger:
        if (x == fingerprint):
            print(
                "Signer already registered....Proceed to Register device step\r\n"
            )
            return 'success'
    print('Proceed to Signer registration')

    ## Getting signer org name from the signer certificate
    signer_org_name = get_org_name(cert.subject).strip().replace(" ", "_")
    print("Signer ca uploading to the hub started...", end='')
    signer_name = SIGNER_CA_FILENAME_BASE + '_' + signer_org_name + '_' + datetime.now(
    ).strftime("%Y-%m-%d-%H-%M-%S")

    ## Signer Certificate Upload to the azure iot hub  ##
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "create", "--hub-name", hub_name,
        "--name", signer_name, "--path", signer_cer_path
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)

    if subProcessOut.returncode != 0:
        print("signer certificate upload to azure iot hub failed\r\n")
        return 'danger'
    print('OK')

    # Get the etag for the signer certificate ##
    print("Getting the verification code from the iot hub...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "show", "--hub-name", hub_name,
        "--name", signer_name, "--query", "etag"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print(
            "Getting etag for signer certificate from azure iot hub failed\r\n"
        )
        return 'danger'
    etag_id = subProcessOut.stdout
    print('OK')

    ##Generate the verification code for the signer cerificate ##
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "generate-verification-code",
        "--hub-name", hub_name, "--name", signer_name, "--etag", etag_id
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting verificateion code from azure iot hub failed\r\n")
        return 'danger'
    data = subProcessOut.stdout
    json_data = json.loads(data)
    registration_code = json_data['properties']['verificationCode']

    ##Generate the verification certificate with the verification code##
    print("Generating the verification certificate with verification code...",
          end='')
    generate_verification_cert(registration_code, SIGNER_CA_KEY_FILENAME,
                               SIGNER_CA_CERT_FILENAME,
                               SIGNER_CA_VER_CERT_FILENAME)
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "show", "--hub-name", hub_name,
        "--name", signer_name, "--query", "etag"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print(
            "Getting etag for signer certificate from azure iot hub failed\r\n"
        )
        return 'danger'
    etag_id = subProcessOut.stdout
    print('OK')

    ## Upload the Verification certificate to azure iot hub ##
    print("Uploading the verification certificate to iot hub...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "verify", "--hub-name", hub_name,
        "--name", signer_name, "--path", verification_cert_path, "--etag",
        etag_id
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("uploading verification certificate to azure iot hub failed\r\n")
        return 'danger'
    print('OK')
    print("Signer ca {} uploaded and verified in azure hub\r\n".format(
        signer_name))
    return 'success'