From ee938a3aa6d66d3705ab0a513930a0e24c22ac91 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Wed, 4 Sep 2024 20:17:11 +0200 Subject: [PATCH] Encode JWT --- python_device/README.md | 5 +++++ python_device/src/api.py | 21 +++++++++++++++++++++ python_device/src/main.py | 9 +++++++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/python_device/README.md b/python_device/README.md index 99920e2..8f5b1b9 100644 --- a/python_device/README.md +++ b/python_device/README.md @@ -1,5 +1,10 @@ # Python client +Dependencies: +```bash +apt install python3-jwt +``` + Reformat code: ```bash diff --git a/python_device/src/api.py b/python_device/src/api.py index 7c88285..6c66057 100644 --- a/python_device/src/api.py +++ b/python_device/src/api.py @@ -1,6 +1,9 @@ import requests from src.args import args import src.constants as constants +from cryptography.x509 import load_pem_x509_certificate +from cryptography import utils +import jwt def get_secure_origin() -> str: @@ -70,3 +73,21 @@ def device_certificate() -> str: print(res.text) raise Exception(f"Failed to check enrollment with status {res.status_code}") return res.text + + +def sync_device(dev_id: str, privkey): + """ + Synchronize device with backend + """ + encoded = jwt.encode( + {"info": device_info()}, privkey, algorithm="RS256", headers={"kid": dev_id} + ) + + res = requests.post( + f"{args.secure_origin}/devices_api/mgmt/sync", + json={"payload": encoded}, + verify=args.root_ca_path, + ) + + print(encoded) + print(res) diff --git a/python_device/src/main.py b/python_device/src/main.py index c066e7b..063bed3 100644 --- a/python_device/src/main.py +++ b/python_device/src/main.py @@ -43,6 +43,10 @@ if not os.path.isfile(args.dev_priv_key_path): with open(args.dev_priv_key_path, "w") as f: f.write(key) +with open(args.dev_priv_key_path, "r") as f: + args.priv_key = f.read() + + print("Check CSR") if not os.path.isfile(args.dev_csr_path): print("Generate CSR...") @@ -63,8 +67,7 @@ if status != "Validated": if status == "Unknown": print("Device is unknown on the system, need to submit a CSR...") with open(args.dev_csr_path, "r") as f: - csr = "".join(f.read()) - + csr = "".utils print("Enrolling device...") api.enroll_device(csr) print("Done. Please accept the device on central system web UI") @@ -85,4 +88,6 @@ if not os.path.isfile(args.dev_crt_path): with open(args.dev_crt_path, "w") as f: f.write(cert) + print("Done. ready to operate.") +api.sync_device(args.dev_id, args.priv_key)