aboutsummaryrefslogtreecommitdiff
path: root/scripts/py11-test.py
blob: a5e9c880fd8b0a50d0021dbcee15923f1c06898f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# Initial test script using py11.  About 2/3 testing PKCS #11, 1/3
# doodles figuring out what else py11 should be automating for us.

from py11 import *
from struct import pack, unpack

def show_token(i, t, strip = True):
  print "Token in slot #%d:" % i
  fw = max(len(fn) for fn, ft in t.__class__._fields_)
  for fn, ft in t.__class__._fields_:
    fv = getattr(t, fn)
    fn = "%-*s :" % (fw, fn)
    if isinstance(fv, CK_VERSION):
      print " ", fn, "%d.%d" % (fv.major, fv.minor)
    elif isinstance(fv, (int, long)):
      print " ", fn, fv
    else:
      print " ", fn, repr(str(fv).rstrip(" ") if strip else str(fv))


def genkeypair_templates(name = "foo", **kwargs):
  label_id = ((CKA_LABEL, name), (CKA_ID, name))
  return (
    # Public template
    label_id + tuple(kwargs.iteritems()) +
    ((CKA_VERIFY,             True),
     (CKA_ENCRYPT,            False),
     (CKA_WRAP,               False),
     (CKA_TOKEN,              False)),
    # Private template
    label_id +
    ((CKA_SIGN,               True),
     (CKA_DECRYPT,            False),
     (CKA_UNWRAP,             False),
     (CKA_SENSITIVE,          True),
     (CKA_TOKEN,              False),
     (CKA_PRIVATE,            True),
     (CKA_EXTRACTABLE,        False)))


def show_keys(session, key_class, *attributes):
  p11.C_FindObjectsInit(session, {CKA_CLASS: key_class})
  for o in p11.C_FindObjects(session):
    a = p11.C_GetAttributeValue(session, o, attributes + (CKA_CLASS, CKA_KEY_TYPE, CKA_LABEL, CKA_ID, CKA_TOKEN,
                                                          CKA_PRIVATE, CKA_LOCAL, CKA_KEY_GEN_MECHANISM))
    w = max(len(p11.adb.attribute_name(k)) for k in a)
    print "Object:", o
    for k, v in a.iteritems():
      print " %*s (0x%08x): %r" % (w, p11.adb.attribute_name(k), k, v)
  p11.C_FindObjectsFinal(session)


def build_ecpoint(x, y):
  h = (max(x.bit_length(), y.bit_length()) + 15) / 16
  d = chr(0x04) + ("%0*x%0*x" % (h, x, h, y)).decode("hex")
  if len(d) < 128:
    h = "%c%c" % (0x04, len(d))
  else:
    n = len(d).bit_length()
    h = ("%c%c" % (0x04, (n + 7) / 8)) + ("%0*x" % ((n + 15) / 16, len(d))).decode("hex")
  return h + d


ec_curve_oid_p256 = "".join(chr(i) for i in (0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07))
ec_curve_oid_p384 = "".join(chr(i) for i in (0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22))
ec_curve_oid_p521 = "".join(chr(i) for i in (0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23))

p11 = PKCS11("./libpkcs11.so")

if False:
  print "Not using MUTEXes at all"
  p11.C_Initialize()

elif True:
  print "Using OS MUTEXes"
  p11.C_Initialize(CKF_OS_LOCKING_OK)

else:
  print "Using our own pseudo-MUTEXes"

  # This class probably belongs in the library.

  class Mutexes(object):

    format = "=L"
    length = len(pack(format, 0))

    def __init__(self, verbose = True, flags = 0):
      self.init_args = (flags, self.create, self.destroy, self.lock, self.unlock)
      self.next_mutex = 0
      self.mutexes = {}
      self.verbose = verbose

    def find(self):
      if len(self.mutexes) > 0xFFFFFFFF:
        raise RuntimeError
      while self.next_mutex in self.mutexes:
        self.next_mutex = (self.next_mutex + 1) & 0xFFFFFFFF

    def encode(self, n):
      return (CK_BYTE * self.length)(*pack(self.format, n))

    def decode(self, m):
      return unpack(self.format, m[:self.length])[0]

    def create(self, mm):
      self.find()
      if self.verbose:
        print "Creating mutex", self.next_mutex
      m = self.encode(self.next_mutex)
      self.mutexes[self.next_mutex] = [False, m]
      mm[0] = m
      return CKR_OK

    def destroy(self, m):
      mutex = self.decode(m)
      if self.verbose:
        print "Destroying mutex", mutex
      del self.mutexes[mutex]
      return CKR_OK

    def lock(self, m):
      mutex = self.decode(m)
      if self.verbose:
        print "Locking mutex", mutex
      self.mutexes[mutex][0] = True
      return CKR_OK

    def unlock(self, m):
      mutex = self.decode(m)
      if self.verbose:
        print "Unlocking mutex", mutex
      self.mutexes[mutex][0] = False
      return CKR_OK

  mutexes = Mutexes()
  p11.C_Initialize(*mutexes.init_args)

# Dun with MUTEX insanit and C_Initialize() call

slots = p11.C_GetSlotList()

print
print "Listing slots and tokens"
for i in slots:
  show_token(i, p11.C_GetTokenInfo(i))

slot = slots[0]

print
print "Generating some random data"
session = p11.C_OpenSession(slot)
random  = p11.C_GenerateRandom(session, 33)
print len(random), "".join("%02x" % ord(i) for i in random)

print
print "Logging in"
p11.C_Login(session, CKU_USER, "fnord")

if False:
  print
  print "Generating RSA keypair"
  rsa_templates = genkeypair_templates("RSA", CKA_MODULUS_BITS = 1024)
  rsa_keypair   = p11.C_GenerateKeyPair(session, CKM_RSA_PKCS_KEY_PAIR_GEN, rsa_templates[0], rsa_templates[1])
  print rsa_keypair

print
print "Generating EC P256 keypair"
ec_templates = genkeypair_templates("EC-P256", CKA_EC_PARAMS = ec_curve_oid_p256)
ec_p256_keypair   = p11.C_GenerateKeyPair(session, CKM_EC_KEY_PAIR_GEN, ec_templates[0], ec_templates[1])
print ec_p256_keypair
                      
print
print "Generating EC P384 keypair"
ec_templates = genkeypair_templates("EC-P384", CKA_EC_PARAMS = ec_curve_oid_p384)
ec_p384_keypair   = p11.C_GenerateKeyPair(session, CKM_EC_KEY_PAIR_GEN, ec_templates[0], ec_templates[1])
print ec_p384_keypair
                      
print
print "Generating EC P521 keypair"
ec_templates = genkeypair_templates("EC-P521", CKA_EC_PARAMS = ec_curve_oid_p521)
ec_p521_keypair   = p11.C_GenerateKeyPair(session, CKM_EC_KEY_PAIR_GEN, ec_templates[0], ec_templates[1])
print ec_p521_keypair
                      
print
print "Listing keys"
show_keys(session, CKO_PUBLIC_KEY,  CKA_VERIFY, CKA_ENCRYPT, CKA_WRAP)
show_keys(session, CKO_PRIVATE_KEY, CKA_SIGN,   CKA_DECRYPT, CKA_UNWRAP)

hamster = "Your mother was a hamster"

print
print "Testing P-256 signature"
p11.C_SignInit(session, CKM_ECDSA_SHA256, ec_p256_keypair[1])
sig_p256 = p11.C_Sign(session, hamster)
print "Signature:", sig_p256.encode("hex")

print
print "Testing P256 verification"
p11.C_VerifyInit(session, CKM_ECDSA_SHA256, ec_p256_keypair[0])
p11.C_Verify(session, hamster, sig_p256)
print "OK"                      # Verification failure throws an exception

print
print "Testing C_CreateObject()"
handle = p11.C_CreateObject(session, dict(
    CKA_CLASS           = CKO_PUBLIC_KEY,
    CKA_KEY_TYPE        = CKK_EC,
    CKA_LABEL           = "EC-P-256 test case from \"Suite B Implementer's Guide to FIPS 186-3\"",
    CKA_ID              = "TC-P-256",
    CKA_VERIFY          = True,
    CKA_ENCRYPT         = False,
    CKA_WRAP            = False,
    CKA_TOKEN           = False,
    CKA_EC_POINT        = build_ecpoint(0x8101ece47464a6ead70cf69a6e2bd3d88691a3262d22cba4f7635eaff26680a8,
                                        0xd8a12ba61d599235f67d9cb4d58f1783d3ca43e78f0a5abaa624079936c0c3a9),
    CKA_EC_PARAMS       = ec_curve_oid_p256))
print handle

print
print "Verifying canned signature with public key installed via C_CreateObject()"
p11.C_VerifyInit(session, CKM_ECDSA, handle)
p11.C_Verify(session,
             "7c3e883ddc8bd688f96eac5e9324222c8f30f9d6bb59e9c5f020bd39ba2b8377".decode("hex"),
             "7214bc9647160bbd39ff2f80533f5dc6ddd70ddf86bb815661e805d5d4e6f27c".decode("hex") +
             "7d1ff961980f961bdaa3233b6209f4013317d3e3f9e1493592dbeaa1af2bc367".decode("hex"))
print "OK"

p11.C_CloseAllSessions(slot)
p11.C_Finalize()