Skip to content

Commit be2d7a4

Browse files
Micah N GorrellMatthiasValvekens
authored andcommitted
Corrected logic for handling CK_UNAVAILABLE_INFORMATION to properly check the length returned
1 parent 3c03b85 commit be2d7a4

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

pkcs11/_pkcs11.pyx

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -938,8 +938,14 @@ class Object(types.Object):
938938
# Find out the attribute size
939939
with nogil:
940940
retval = _funclist.C_GetAttributeValue(handle, obj, &template, 1)
941-
if retval == CK_UNAVAILABLE_INFORMATION:
942-
return None
941+
if retval == CKR_OK and \
942+
template.ulValueLen == CK_UNAVAILABLE_INFORMATION:
943+
# The spec prohibits returning CK_UNAVAILABLE_INFORMATION
944+
# together with CKR_OK, but some tokens do that anyway.
945+
# Let's be defensive and map that to a proper error,
946+
# otherwise CK_UNAVAILABLE_INFORMATION will be treated
947+
# as a length value, which causes issues.
948+
retval = CKR_FUNCTION_FAILED
943949
assertRV(retval)
944950

945951
if template.ulValueLen == 0:
@@ -952,8 +958,6 @@ class Object(types.Object):
952958
# Request the value
953959
with nogil:
954960
retval = _funclist.C_GetAttributeValue(handle, obj, &template, 1)
955-
if retval == CK_UNAVAILABLE_INFORMATION:
956-
return None
957961
assertRV(retval)
958962

959963
return _unpack_attributes(key, value)

tests/test_sessions.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import pkcs11
6+
from pkcs11 import Attribute, AttributeSensitive, AttributeTypeInvalid
67

78
from . import FIXME, TOKEN_PIN, TOKEN_SO_PIN, Not, Only, TestCase, requires
89

@@ -157,3 +158,17 @@ def test_generate_random(self):
157158
self.assertEqual(len(random), 16)
158159
# Ensure we didn't get 16 bytes of zeros
159160
self.assertTrue(all(c != "\0" for c in random))
161+
162+
def test_attribute_reading_failures(self):
163+
with self.token.open(user_pin=TOKEN_PIN) as session:
164+
key = session.generate_key(pkcs11.KeyType.AES, 128, label="SAMPLE KEY")
165+
166+
def try_read_value():
167+
return key[Attribute.VALUE]
168+
169+
self.assertRaises(AttributeSensitive, try_read_value)
170+
171+
def try_read_irrelevant():
172+
return key[Attribute.CERTIFICATE_TYPE]
173+
174+
self.assertRaises(AttributeTypeInvalid, try_read_irrelevant)

0 commit comments

Comments
 (0)