API examples
The following examples are indicative only and are provided as a general guide. Before using them in production, you should update the code to more fully suit your environment and needs, for example, adding better error handling.
nShield HSM feature management
Steps
-
Upload feature file:
POST /mgmt/v1/feature-certificates -
Enable feature:
PATCH /mgmt/v1/feature-certificates/<featureid> -
Clear the HSM if necessary:
PUT /mgmt/v1/hsms/<hsmid>/clear
Python code example
import sys
import base64
import requests
server = "https://192.0.2.1"
# STEP 1 Upload feature file as provided by order or support
with open(sys.argv[1], "rb") as file:
# Read in feature file and convert to base64 url string
file_content = base64.urlsafe_b64encode(file.read()).decode()
# Remove the padding
file_content = file_content.rstrip("=")
# Post feature file to KeySafe 5
response = requests.post(
server + "/mgmt/v1/feature-certificates",
json={"file": file_content},
verify=False,
)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# Location of created resource is in the Location header but can also be deduced from the response body
featureURI = server + response.headers["Location"]
clearRequired = response.json()["clearRequired"]
# STEP 2 Enable feature
response = requests.patch(featureURI, json={"operation": "enable"}, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# STEP 3 Clear HSM if necessary
if clearRequired:
clearURI = server + response.json()["meta"]["clear"]
response = requests.put(clearURI, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
print("Feature applied")
nShield HSM firmware management
Steps
-
Get the HSM information:
GET /mgmt/v1/hsms/<hsmid> -
Search for a suitable firmware image:
GET /mgmt/v1/upgrade-images -
Upgrade the firmware:
POST /mgmt/v1/hsms/<hsmid>/firmware -
(Optional) Monitor the operation to see when the upgrade is finished.
Python code example
import time
import requests
server = "https://192.0.2.1"
hsmURI = "/mgmt/v1/hsms/7cfd8df2-5e88-420e-98c6-e5408ce828d5"
imagesURI = "/mgmt/v1/upgrade-images"
# STEP 1 Get HSM Information
response = requests.get(server + hsmURI, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
hsmdata = response.json()["data"]["hsm"]
# STEP 2 Search for a suitable platform upgrade image
params = {}
params["type"] = "upgrade-platform"
params["model"] = hsmdata["productModel"].replace("/", ",")
if "hardwareRevision" in hsmdata:
params["hardwareRevision"] = hsmdata["hardwareRevision"]
params["filter"] = 'version >= "{0}"'.format(hsmdata["versionInfo"]["versionString"])
params["filter"] += " AND moduleInfo.vsn >= {0}".format(hsmdata["vsn"])
if "remoteModuleinfo" in hsmdata:
params["filter"] += " AND remoteModuleInfo.vsn >= {0}".format(
hsmdata["remoteModuleInfo"]["vsn"]
)
response = requests.get(server + imagesURI, params=params, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# STEP 3 if we got a suitable image then upgrade to it
images = response.json()["data"]["images"]
# Upgrade to the first suitable image
if len(images) > 0:
response = requests.post(
server + hsmURI + "/firmware",
json={"dryRun": True, "image": imagesURI + "/" + images[0]["id"]},
verify=False,
)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# STEP 4 (Optional) Monitor the operation to see when the upgrade is finished.
# Location of created operation is in the Location header
operationURI = response.headers["Location"]
while True:
response = requests.get(server + operationURI, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
operationStatus = response.json()["data"]["operation"]["state"]
if operationStatus != "Requested":
break
# sleep for a while before retrying
time.sleep(10)
print("Status: " + operationStatus)
else:
print("No upgrade possible")
nShield HSM management
Scenario
As an nShield HSM manager, I want to select a number of HSMs and output information about them in a csv file.
Steps
-
Select HSMs (in a pool, by label) and get data about them:
GET /mgmt/v1/hsms
Python code example
import csv
import sys
import requests
server = "https://192.0.2.1"
# STEP 1 Get a list of HSMs which ...
params = {} # would get all HSMs
params["pool"] = "44820fb6-bace-4dcd-ad97-7b6e0a5e4138" # HSMs in this pool
params["labels"] = ["test1", "test2"] # and HSMs with labels test1 AND test2
params["limit"] = (
"5" # Optionally choose the amount to fetch (otherwise get the default)
)
# Write output to a csv file
with open(sys.argv[1], "w") as file:
wr = csv.writer(file)
wr.writerow(["id", "type", "esn", "vcm", "version"])
cursor = None
# while there are more HSM records
while cursor is None or cursor != "":
# Read a page of records
response = requests.get(server + "/mgmt/v1/hsms", params=params, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# use the cursor to get the next page of records
cursor = response.json()["meta"]["page"]["next"]
params["cursor"] = cursor
hsms = response.json()["data"]["hsms"]
for hsm in hsms:
# write out some information to the file
wr.writerow(
[
hsm["id"],
hsm["hsmType"],
hsm["esn"],
hsm["vcm"] if "vcm" in hsm else "",
hsm["versionInfo"]["versionNumber"],
]
)
nShield Security World management
Steps
-
Create a new softcard:
POST /mgmt/v1/worlds/<worldid>/softcards -
Get the authorisations needed:
GET /mgmt/v1/worlds/<worldid>/operations/<operationid> -
Authorise the creation with a new passphrase:
POST /mgmt/v1/worlds/<worldid>/operations/<operationid>/actions -
(Optional) Check the operation is now authorised:
GET /mgmt/v1/worlds/<worldid>/operations/<operationid>
Python code example
import requests
server = "https://192.0.2.1"
# STEP 1 Create a new softcard
response = requests.post(
server + "/mgmt/v1/worlds/be94c849-3a73-4ace-b493-a30b5b2243da/softcards",
json={"name": "NewSoftcardName", "pprecovery": False},
verify=False,
)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# Location of created operation is in the Location header
operationURI = response.headers["Location"]
# STEP 2 Get the authorisations needed
response = requests.get(server + operationURI, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
authorisations = response.json()["data"]["operation"]["authorizations"]
# STEP 3 Authorise the creation with a new passphrase
for auth in authorisations:
# If it is a passphrase authorisation in requested state (there will actually only be one of these)
if auth["authorizationType"] == "Passphrase" and auth["state"] == "Requested":
response = requests.post(
server + operationURI + "/actions",
json={
"actionType": "authorization",
"resourceURI": operationURI + "/authorizations/" + auth["id"],
"passphrase": "NewPassphrase",
},
verify=False,
)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
# STEP 4 (Optional) Check the operation is now authorised
response = requests.get(server + operationURI, verify=False)
if not response:
raise Exception(f"Non-success status code: {response.status_code}")
print(response.json()["data"]["operation"]["state"] == "Authorized")