Skip to content

Commit 1ea642e

Browse files
committed
tpm2_ptool: add objpol command for object policies
Policies are expected to be specified in JSON format. The command allows reading, writing or deleting policy set on an object. Signed-off-by: Sergii Dmytruk <[email protected]>
1 parent 81bb0f0 commit 1ea642e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

tools/tpm2_pkcs11/commandlets_keys.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from .utils import dump_blobs
2929
from .utils import dump_tsspem
3030
from .utils import dump_pubpem
31+
from .utils import validate_policy
3132

3233
from .tpm2 import Tpm2
3334

@@ -551,6 +552,55 @@ def __call__(self, args):
551552

552553
ObjDel.delete(path, args['id'])
553554

555+
@commandlet("objpol")
556+
class ObjPol(Command):
557+
'''
558+
Gets/sets/removes object's policy.
559+
'''
560+
561+
@classmethod
562+
def objpol(cls, path, tid, policy):
563+
564+
with Db(path) as db:
565+
obj = db.getobject(tid)
566+
if obj is None:
567+
sys.exit('Not found, object with id: {}'.format(tid))
568+
s = obj['attrs']
569+
obj_attrs = yaml.safe_load(s)
570+
571+
# print policy when --policy is not specified
572+
if policy is None:
573+
if CKA_TPM2_POLICY_JSON not in obj_attrs:
574+
sys.exit('The object has no policy set')
575+
576+
print(obj_attrs[CKA_TPM2_POLICY_JSON])
577+
sys.exit()
578+
579+
if not policy:
580+
# delete policy when --policy is empty
581+
obj_attrs.pop(CKA_TPM2_POLICY_JSON, None)
582+
else:
583+
# set policy when --policy is a well-formed JSON
584+
validate_policy(policy)
585+
obj_attrs[CKA_TPM2_POLICY_JSON] = policy
586+
587+
with Db(path) as db:
588+
db.updatetertiary(obj['id'], obj_attrs)
589+
590+
# adhere to an interface
591+
def generate_options(self, group_parser):
592+
593+
group_parser.add_argument(
594+
'--id', help='The id of the object to use.\n', required=True)
595+
group_parser.add_argument(
596+
'--policy', help='New policy value as JSON (empty value removes policy).\n')
597+
598+
def __call__(self, args):
599+
600+
path = args['path']
601+
602+
ObjPol.objpol(path, args['id'], args['policy'])
603+
554604
@commandlet("link")
555605
class LinkCommand(NewKeyCommandBase):
556606
'''

tools/tpm2_pkcs11/utils.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import binascii
33
import hashlib
44
import io
5+
import json
56
import os
67
import argparse
78
import sys
@@ -555,3 +556,9 @@ def dump_pubpem(db, obj, pin, is_sopin, output_prefix):
555556
with open(output_prefix + ".pem", "wb") as f:
556557
f.write(pub_blob.to_pem())
557558

559+
def validate_policy(policy):
560+
try:
561+
# discarding result as this is just a JSON sanity check
562+
json.loads(policy)
563+
except json.JSONDecodeError:
564+
sys.exit('Object policy must be a valid JSON')

0 commit comments

Comments
 (0)