cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
pkcs11_init.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib PKCS #11 Init/Shutdown Routines *
4 * Copyright Peter Gutmann 1998-2005 *
5 * *
6 ****************************************************************************/
7 
8 #if defined( INC_ALL )
9  #include "crypt.h"
10  #include "context.h"
11  #include "device.h"
12  #include "pkcs11_api.h"
13  #include "asn1.h"
14 #else
15  #include "crypt.h"
16  #include "context/context.h"
17  #include "device/device.h"
18  #include "device/pkcs11_api.h"
19  #include "enc_dec//asn1.h"
20 #endif /* Compiler-specific includes */
21 
22 #ifdef USE_PKCS11
23 
24 /* The max. number of drivers we can work with and the max.number of slots
25  per driver */
26 
27 #define MAX_PKCS11_DRIVERS 5
28 #define MAX_PKCS11_SLOTS 16
29 
30 /* The default slot to look for tokens in */
31 
32 #define DEFAULT_SLOT 0
33 
34 /* Define the following to explicitly link each PKCS #11 function rather than
35  using C_GetFunctionList(). Note that this will require changes to the way
36  the functions are accessed, since currently it's done via a global function
37  pointer table in the pkcs11Info struct */
38 
39 /* #define USE_EXPLICIT_LINKING */
40 
41 /****************************************************************************
42 * *
43 * Utility Routines *
44 * *
45 ****************************************************************************/
46 
47 /* Get random data from the device */
48 
49 static int getRandomFunction( DEVICE_INFO *deviceInfo, void *buffer,
50  const int length,
52  {
53  CK_RV status;
54  PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
55 
56  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
57  assert( isWritePtr( buffer, length ) );
58 
59  status = C_GenerateRandom( pkcs11Info->hSession, buffer, length );
60  return( pkcs11MapError( status, CRYPT_ERROR_FAILED ) );
61  }
62 
63 /* Perform a self-test */
64 
65 static int selfTestFunction( void )
66  {
67  /* PKCS #11 doesn't provide any explicit means of performing a self-
68  test of a capability, and having to go through the gyrations needed
69  to do this via the PKCS #11 interface is excessively complex, so we
70  just assume that everything is OK. In general what a device does is
71  device-specific, for example as part of FIPS 140 requirements or even
72  just as general good engineering many will perform a self-test on
73  power-up while others (typically smart cards) barely do any checking
74  at all. The result that we return here is an implicit "whatever the
75  device does" */
76  return( CRYPT_ERROR_NOTAVAIL );
77  }
78 
79 /****************************************************************************
80 * *
81 * Init/Shutdown Routines *
82 * *
83 ****************************************************************************/
84 
85 /* Whether the PKCS #11 library has been initialised or not, this is
86  initialised on demand the first time it's accessed */
87 
88 static BOOLEAN pkcs11Initialised = FALSE;
89 
90 #ifdef DYNAMIC_LOAD
91 
92 /* Since we can be using multiple PKCS #11 drivers, we define an array of
93  them and access the appropriate one by name */
94 
95 typedef struct {
96  char name[ 32 + 1 + 8 ]; /* Name of device */
97  INSTANCE_HANDLE hPKCS11; /* Handle to driver */
98  CK_FUNCTION_LIST_PTR functionListPtr; /* Driver access information */
99 #ifdef USE_EXPLICIT_LINKING
100  CK_C_CloseSession pC_CloseSession; /* Interface function pointers */
101  CK_C_CreateObject pC_CreateObject;
102  CK_C_Decrypt pC_Decrypt;
103  CK_C_DecryptInit pC_DecryptInit;
104  CK_C_DestroyObject pC_DestroyObject;
105  CK_C_Digest pC_Digest;
106  CK_C_DigestInit pC_DigestInit;
107  CK_C_Encrypt pC_Encrypt;
108  CK_C_EncryptInit pC_EncryptInit;
109  CK_C_Finalize pC_Finalize;
110  CK_C_FindObjects pC_FindObjects;
111  CK_C_FindObjectsFinal pC_FindObjectsFinal;
112  CK_C_FindObjectsInit pC_FindObjectsInit;
113  CK_C_GenerateKey pC_GenerateKey;
114  CK_C_GenerateKeyPair pC_GenerateKeyPair;
115  CK_C_GenerateRandom pC_GenerateRandom;
116  CK_C_GetAttributeValue pC_GetAttributeValue;
117  CK_C_GetMechanismInfo pC_GetMechanismInfo;
118  CK_C_GetSlotInfo pC_GetSlotInfo;
119  CK_C_GetSlotList pC_GetSlotList;
120  CK_C_GetTokenInfo pC_GetTokenInfo;
121  CK_C_InitPIN pC_InitPIN;
122  CK_C_InitToken pC_InitToken;
123  CK_C_Login pC_Login;
124  CK_C_Logout pC_Logout;
125  CK_C_OpenSession pC_OpenSession;
126  CK_C_SetAttributeValue pC_SetAttributeValue;
127  CK_C_SetPIN pC_SetPIN;
128  CK_C_Sign pC_Sign;
129  CK_C_SignFinal pC_SignFinal;
130  CK_C_SignInit pC_SignInit;
131  CK_C_SignUpdate pC_SignUpdate;
132  CK_C_Verify pC_Verify;
133  CK_C_VerifyInit pC_VerifyInit;
134  CK_C_WrapKey pC_WrapKey;
135  CK_C_UnwrapKey pC_UnwrapKey;
136 #endif /* USE_EXPLICIT_LINKING */
137  } PKCS11_DRIVER_INFO;
138 
139 static PKCS11_DRIVER_INFO pkcs11InfoTbl[ MAX_PKCS11_DRIVERS + 8 ];
140 
141 /* The use of dynamically bound function pointers vs.statically linked
142  functions requires a bit of sleight of hand since we can't give the
143  pointers the same names as prototyped functions. To get around this we
144  redefine the actual function names to the names of the pointers */
145 
146 #ifdef USE_EXPLICIT_LINKING
147 
148 #define C_CloseSession pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_CloseSession
149 #define C_CreateObject pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_CreateObject
150 #define C_Decrypt pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Decrypt
151 #define C_DecryptInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_DecryptInit
152 #define C_DestroyObject pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_DestroyObject
153 #define C_Digest pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Digest
154 #define C_DigestInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_DigestInit
155 #define C_Encrypt pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Encrypt
156 #define C_EncryptInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_EncryptInit
157 #define C_Finalize pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Finalize
158 #define C_FindObjects pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_FindObjects
159 #define C_FindObjectsFinal pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_FindObjectsFinal
160 #define C_FindObjectsInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_FindObjectsInit
161 #define C_GenerateKey pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GenerateKey
162 #define C_GenerateKeyPair pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GenerateKeyPair
163 #define C_GenerateRandom pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GenerateRandom
164 #define C_GetAttributeValue pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GetAttributeValue
165 #define C_GetMechanismInfo pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GetMechanismInfo
166 #define C_GetSlotInfo pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GetSlotInfo
167 #define C_GetSlotList pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GetSlotList
168 #define C_GetTokenInfo pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_GetTokenInfo
169 #define C_Initialize pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Initialize
170 #define C_InitPIN pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_InitPIN
171 #define C_InitToken pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_InitToken
172 #define C_Login pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Login
173 #define C_Logout pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Logout
174 #define C_OpenSession pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_OpenSession
175 #define C_SetAttributeValue pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_SetAttributeValue
176 #define C_SetPIN pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_SetPIN
177 #define C_Sign pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Sign
178 #define C_SignFinal pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_SignFinal
179 #define C_SignInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_SignInit
180 #define C_SignUpdate pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_SignUpdate
181 #define C_Verify pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_Verify
182 #define C_VerifyInit pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_VerifyInit
183 #define C_WrapKey pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_WrapKey
184 #define C_UnwrapKey pkcs11InfoTbl[ pkcs11Info->deviceNo ].pC_UnwrapKey
185 
186 #endif /* USE_EXPLICIT_LINKING */
187 
188 /* Dynamically load and unload any necessary PKCS #11 drivers */
189 
190 static int loadPKCS11driver( PKCS11_DRIVER_INFO *pkcs11Info,
191  const char *driverName )
192  {
193 #ifdef USE_EXPLICIT_LINKING
194  CK_C_GetInfo pC_GetInfo;
195  CK_C_Initialize pC_Initialize;
196 #else
197  CK_C_GetFunctionList pC_GetFunctionList;
198 #endif /* USE_EXPLICIT_LINKING */
199  CK_INFO info = DUMMY_INIT_STRUCT;
200  CK_RV status;
201 #ifdef __WIN16__
202  UINT errorMode;
203 #endif /* __WIN16__ */
204  BOOLEAN isInitialised = FALSE;
205  int i = 32;
206 
207  assert( isWritePtr( pkcs11Info, sizeof( PKCS11_DRIVER_INFO ) ) );
208  assert( isReadPtr( driverName, 4 ) );
209 
210  /* Obtain a handle to the device driver module */
211 #ifdef __WIN16__
212  errorMode = SetErrorMode( SEM_NOOPENFILEERRORBOX );
213  pkcs11Info->hPKCS11 = LoadLibrary( driverName );
214  SetErrorMode( errorMode );
215  if( pkcs11Info->hPKCS11 < HINSTANCE_ERROR )
216  {
217  pkcs11Info->hPKCS11 = NULL_HINSTANCE;
218  return( CRYPT_ERROR );
219  }
220 #else
221  if( ( pkcs11Info->hPKCS11 = DynamicLoad( driverName ) ) == NULL_INSTANCE )
222  return( CRYPT_ERROR );
223 #endif /* OS-specific dynamic load */
224 
225  /* Now get pointers to the functions */
226 #ifdef USE_EXPLICIT_LINKING
227  pC_GetInfo = ( CK_C_GetInfo ) DynamicBind( pkcs11Info->hPKCS11, "C_GetInfo" );
228  pC_Initialize = ( CK_C_Initialize ) DynamicBind( pkcs11Info->hPKCS11, "C_Initialize" );
229  pkcs11Info->pC_CloseSession = ( CK_C_CloseSession ) DynamicBind( pkcs11Info->hPKCS11, "C_CloseSession" );
230  pkcs11Info->pC_CreateObject = ( CK_C_CreateObject ) DynamicBind( pkcs11Info->hPKCS11, "C_CreateObject" );
231  pkcs11Info->pC_Decrypt = ( CK_C_Decrypt ) DynamicBind( pkcs11Info->hPKCS11, "C_Decrypt" );
232  pkcs11Info->pC_DecryptInit = ( CK_C_DecryptInit ) DynamicBind( pkcs11Info->hPKCS11, "C_DecryptInit" );
233  pkcs11Info->pC_DestroyObject = ( CK_C_DestroyObject ) DynamicBind( pkcs11Info->hPKCS11, "C_DestroyObject" );
234  pkcs11Info->pC_Digest = ( CK_C_Digest ) DynamicBind( pkcs11Info->hPKCS11, "C_Digest" );
235  pkcs11Info->pC_DigestInit = ( CK_C_DigestInit ) DynamicBind( pkcs11Info->hPKCS11, "C_DigestInit" );
236  pkcs11Info->pC_Encrypt = ( CK_C_Encrypt ) DynamicBind( pkcs11Info->hPKCS11, "C_Encrypt" );
237  pkcs11Info->pC_EncryptInit = ( CK_C_EncryptInit ) DynamicBind( pkcs11Info->hPKCS11, "C_EncryptInit" );
238  pkcs11Info->pC_Finalize = ( CK_C_Finalize ) DynamicBind( pkcs11Info->hPKCS11, "C_Finalize" );
239  pkcs11Info->pC_FindObjects = ( CK_C_FindObjects ) DynamicBind( pkcs11Info->hPKCS11, "C_FindObjects" );
240  pkcs11Info->pC_FindObjectsFinal = ( CK_C_FindObjectsFinal ) DynamicBind( pkcs11Info->hPKCS11, "C_FindObjectsFinal" );
241  pkcs11Info->pC_FindObjectsInit = ( CK_C_FindObjectsInit ) DynamicBind( pkcs11Info->hPKCS11, "C_FindObjectsInit" );
242  pkcs11Info->pC_GenerateKey = ( CK_C_GenerateKey ) DynamicBind( pkcs11Info->hPKCS11, "C_GenerateKey" );
243  pkcs11Info->pC_GenerateKeyPair = ( CK_C_GenerateKeyPair ) DynamicBind( pkcs11Info->hPKCS11, "C_GenerateKeyPair" );
244  pkcs11Info->pC_GenerateRandom = ( CK_C_GenerateRandom ) DynamicBind( pkcs11Info->hPKCS11, "C_GenerateRandom" );
245  pkcs11Info->pC_GetAttributeValue = ( CK_C_GetAttributeValue ) DynamicBind( pkcs11Info->hPKCS11, "C_GetAttributeValue" );
246  pkcs11Info->pC_GetMechanismInfo = ( CK_C_GetMechanismInfo ) DynamicBind( pkcs11Info->hPKCS11, "C_GetMechanismInfo" );
247  pkcs11Info->pC_GetSlotInfo = ( CK_C_GetSlotInfo ) DynamicBind( pkcs11Info->hPKCS11, "C_GetSlotInfo" );
248  pkcs11Info->pC_GetSlotList = ( CK_C_GetSlotList ) DynamicBind( pkcs11Info->hPKCS11, "C_GetSlotList" );
249  pkcs11Info->pC_GetTokenInfo = ( CK_C_GetTokenInfo ) DynamicBind( pkcs11Info->hPKCS11, "C_GetTokenInfo" );
250  pkcs11Info->pC_InitPIN = ( CK_C_InitPIN ) DynamicBind( pkcs11Info->hPKCS11, "C_InitPIN" );
251  pkcs11Info->pC_InitToken = ( CK_C_InitToken ) DynamicBind( pkcs11Info->hPKCS11, "C_InitToken" );
252  pkcs11Info->pC_Login = ( CK_C_Login ) DynamicBind( pkcs11Info->hPKCS11, "C_Login" );
253  pkcs11Info->pC_Logout = ( CK_C_Logout ) DynamicBind( pkcs11Info->hPKCS11, "C_Logout" );
254  pkcs11Info->pC_OpenSession = ( CK_C_OpenSession ) DynamicBind( pkcs11Info->hPKCS11, "C_OpenSession" );
255  pkcs11Info->pC_SetAttributeValue = ( CK_C_SetAttributeValue ) DynamicBind( pkcs11Info->hPKCS11, "C_SetAttributeValue" );
256  pkcs11Info->pC_SetPIN = ( CK_C_SetPIN ) DynamicBind( pkcs11Info->hPKCS11, "C_SetPIN" );
257  pkcs11Info->pC_SignFinal = ( CK_C_SignFinal ) DynamicBind( pkcs11Info->hPKCS11, "C_SignFinal" );
258  pkcs11Info->pC_SignInit = ( CK_C_SignInit ) DynamicBind( pkcs11Info->hPKCS11, "C_SignInit" );
259  pkcs11Info->pC_SignUpdate = ( CK_C_SignUpdate ) DynamicBind( pkcs11Info->hPKCS11, "C_SignUpdate" );
260  pkcs11Info->pC_Verify = ( CK_C_Verify ) DynamicBind( pkcs11Info->hPKCS11, "C_Verify" );
261  pkcs11Info->pC_VerifyInit = ( CK_C_VerifyInit ) DynamicBind( pkcs11Info->hPKCS11, "C_VerifyInit" );
262  pkcs11Info->pC_WrapKey = ( CK_C_WrapKey ) DynamicBind( pkcs11Info->hPKCS11, "C_WrapKey" );
263  pkcs11Info->pC_UnwrapKey = ( CK_C_UnwrapKey ) DynamicBind( pkcs11Info->hPKCS11, "C_UnwrapKey" );
264 
265  /* Make sure that we got valid pointers for every device function.
266  C_FindObjectsFinal() wasn't added until 2.x and some drivers don't
267  implement it (a smaller subset of them nevertheless claim to be 2.x
268  drivers), so we allow this to be null - the code won't call it if it's
269  not present */
270  if( pC_GetInfo == NULL || pC_Initialize == NULL ||
271  pkcs11Info->pC_CloseSession == NULL ||
272  pkcs11Info->pC_CreateObject == NULL ||
273  pkcs11Info->pC_Decrypt == NULL ||
274  pkcs11Info->pC_DecryptInit == NULL ||
275  pkcs11Info->pC_DestroyObject == NULL ||
276  pkcs11Info->pC_Digest == NULL ||
277  pkcs11Info->pC_DigestInit == NULL ||
278  pkcs11Info->pC_Encrypt == NULL ||
279  pkcs11Info->pC_EncryptInit == NULL ||
280  pkcs11Info->pC_Finalize == NULL ||
281  pkcs11Info->pC_FindObjects == NULL ||
282  pkcs11Info->pC_FindObjectsInit == NULL ||
283  pkcs11Info->pC_GenerateRandom == NULL ||
284  pkcs11Info->pC_GenerateKey == NULL ||
285  pkcs11Info->pC_GenerateKeyPair == NULL ||
286  pkcs11Info->pC_GetAttributeValue == NULL ||
287  pkcs11Info->pC_GetMechanismInfo == NULL ||
288  pkcs11Info->pC_GetSlotInfo == NULL ||
289  pkcs11Info->pC_GetSlotList == NULL ||
290  pkcs11Info->pC_GetTokenInfo == NULL ||
291  pkcs11Info->pC_InitPIN == NULL ||
292  pkcs11Info->pC_InitToken == NULL || pkcs11Info->pC_Login == NULL ||
293  pkcs11Info->pC_Logout == NULL || pkcs11Info->pC_OpenSession == NULL ||
294  pkcs11Info->pC_SetAttributeValue == NULL ||
295  pkcs11Info->pC_SetPIN == NULL || pkcs11Info->pC_Sign == NULL ||
296  pkcs11Info->pC_SignFinal == NULL || pkcs11Info->pC_SignInit == NULL ||
297  pkcs11Info->pC_SignUpdate == NULL ||
298  pkcs11Info->pC_WrapKey == NULL || pkcs11Info->pC_UnwrapKey == NULL ||
299  pkcs11Info->pC_Verify == NULL || pkcs11Info->pC_VerifyInit == NULL )
300  {
301  /* Free the library reference and clear the information */
302  DynamicUnload( pkcs11Info->hPKCS11 );
303  memset( pkcs11Info, 0, sizeof( PKCS11_DRIVER_INFO ) );
304  return( CRYPT_ERROR );
305  }
306 
307  /* Initialise the PKCS #11 library and get information on the device.
308  There are four types of PKCS #11 driver around: v1, v1-like claiming
309  to be v2, v2-like claiming to be v1, and v2. cryptlib can in theory
310  handle all of these, however there are some problem areas with v1
311  (for example v1 uses 16-bit values while v2 uses 32-bit ones, this is
312  usually OK because data is passed around as 32-bit values with the
313  high bits zeroed but some implementations may leave garbage in the
314  high 16 bits that leads to all sorts of confusion). Because of this
315  we explicitly fail if something claims to be v1 even though it might
316  work in practice */
317  status = pC_Initialize( NULL_PTR ) & 0xFFFF;
318  if( status == CKR_OK || status == CKR_CRYPTOKI_ALREADY_INITIALIZED )
319  {
320  isInitialised = TRUE;
321  status = pC_GetInfo( &info ) & 0xFFFF;
322  }
323  if( status == CKR_OK && info.cryptokiVersion.major <= 1 )
324  {
325  /* It's v1, we can't work with it */
327  }
328  if( status != CKR_OK )
329  {
330  if( isInitialised )
331  pkcs11Info->pC_Finalize( NULL_PTR );
332  DynamicUnload( pkcs11Info->hPKCS11 );
333  memset( pkcs11Info, 0, sizeof( PKCS11_DRIVER_INFO ) );
334  return( CRYPT_ERROR );
335  }
336 #else
337  /* Get the access information for the PKCS #11 library, initialise it,
338  and get information on the device. There are four types of PKCS #11
339  driver around: v1, v1-like claiming to be v2, v2-like claiming to be
340  v1, and v2. cryptlib can in theory handle all of these, however
341  there are some problem areas with v1 (for example v1 uses 16-bit
342  values while v2 uses 32-bit ones, this is usually OK because data is
343  passed around as 32-bit values with the high bits zeroed but some
344  implementations may leave garbage in the high 16 bits that leads to
345  all sorts of confusion). Because of this we explicitly fail if
346  something claims to be v1 even though it might work in practice */
347  pC_GetFunctionList = ( CK_C_GetFunctionList ) \
348  DynamicBind( pkcs11Info->hPKCS11, "C_GetFunctionList" );
349  if( pC_GetFunctionList == NULL )
350  status = CKR_GENERAL_ERROR;
351  else
352  {
353  CK_FUNCTION_LIST_PTR functionListPtr;
354 
355  /* The following two-step initialisation is needed because PKCS #11
356  uses a 1-byte alignment on structs, which means that if we pass
357  in the pkcs11Info member address directly we run into alignment
358  problems with 64-bit architectures */
359  status = pC_GetFunctionList( &functionListPtr ) & 0xFFFF;
360  if( status == CKR_OK )
361  pkcs11Info->functionListPtr = functionListPtr;
362  }
363  if( status != CKR_OK )
364  {
365  /* Free the library reference and clear the information */
366  DynamicUnload( pkcs11Info->hPKCS11 );
367  memset( pkcs11Info, 0, sizeof( PKCS11_DRIVER_INFO ) );
368  return( CRYPT_ERROR );
369  }
370  status = C_Initialize( NULL_PTR ) & 0xFFFF;
371  if( status == CKR_OK || status == CKR_CRYPTOKI_ALREADY_INITIALIZED )
372  {
373  isInitialised = TRUE;
374  status = C_GetInfo( &info ) & 0xFFFF;
375  if( status == CKR_OK && info.cryptokiVersion.major <= 1 )
376  {
377  /* It's v1, we can't work with it */
379  }
380  }
381  if( status != CKR_OK )
382  {
383  if( isInitialised )
384  C_Finalize( NULL_PTR );
385  DynamicUnload( pkcs11Info->hPKCS11 );
386  memset( pkcs11Info, 0, sizeof( PKCS11_DRIVER_INFO ) );
387  return( CRYPT_ERROR );
388  }
389 #endif /* USE_EXPLICIT_LINKING */
390 
391  /* Copy out the device driver's name so that the user can access it by
392  name. Some vendors erroneously null-terminate the string so we check
393  for nulls as well */
394  memcpy( pkcs11Info->name, info.libraryDescription, 32 );
395  while( i > 0 && ( pkcs11Info->name[ i - 1 ] == ' ' || \
396  !pkcs11Info->name[ i - 1 ] ) )
397  i--;
398  pkcs11Info->name[ i ] = '\0';
399 
400  return( CRYPT_OK );
401  }
402 
403 void deviceEndPKCS11( void )
404  {
405  int i;
406 
407  if( pkcs11Initialised )
408  {
409  for( i = 0; i < MAX_PKCS11_DRIVERS; i++ )
410  {
411  if( pkcs11InfoTbl[ i ].hPKCS11 != NULL_INSTANCE )
412  {
413 #ifdef USE_EXPLICIT_LINKING
414  pkcs11InfoTbl[ i ].pC_Finalize( NULL_PTR );
415 #else
416  PKCS11_DRIVER_INFO *pkcs11Info = &pkcs11InfoTbl[ i ];
417 
418  C_Finalize( NULL_PTR );
419 #endif /* USE_EXPLICIT_LINKING */
420  DynamicUnload( pkcs11InfoTbl[ i ].hPKCS11 );
421  }
422  pkcs11InfoTbl[ i ].hPKCS11 = NULL_INSTANCE;
423  }
424  }
425  pkcs11Initialised = FALSE;
426  }
427 
428 int deviceInitPKCS11( void )
429  {
430  int tblIndex = 0, optionIndex, status;
431 
432  /* If we've previously tried to initialise the drivers, don't try it
433  again */
434  if( pkcs11Initialised )
435  return( CRYPT_OK );
436  memset( pkcs11InfoTbl, 0, sizeof( pkcs11InfoTbl ) );
437 
438  /* Try and link in each driver specified in the config options. Since
439  this is a general systemwide config option, we always query the built-
440  in default user object */
441  for( optionIndex = 0; optionIndex < MAX_PKCS11_DRIVERS; optionIndex++ )
442  {
444  char deviceDriverName[ MAX_PATH_LENGTH + 1 + 8 ];
445 
446  setMessageData( &msgData, deviceDriverName, MAX_PATH_LENGTH );
448  IMESSAGE_GETATTRIBUTE_S, &msgData,
449  optionIndex + CRYPT_OPTION_DEVICE_PKCS11_DVR01 );
450  if( cryptStatusError( status ) )
451  continue;
452  deviceDriverName[ msgData.length ] = '\0';
453  status = loadPKCS11driver( &pkcs11InfoTbl[ tblIndex ],
454  deviceDriverName );
455  if( cryptStatusOK( status ) )
456  {
457  tblIndex++;
458  pkcs11Initialised = TRUE;
459  }
460  }
461 
462  /* If it's a Unix system and there were no drivers explicitly specified,
463  try with the default driver name "libpkcs11.so". Unlike Windows,
464  where there are large numbers of PKCS #11 vendors and we have to use
465  vendor-specific names, under Unix there are very few vendors and
466  there's usually only one device/driver in use which inevitably
467  co-opts /usr/lib for its own use, so we can always try for a standard
468  name and location. As a backup measure we also try for the nCipher
469  PKCS #11 driver, which is by far the most commonly used one on Unix
470  systems (this may sometimes be found as /usr/lib/libcknfast.so).
471 
472  An unfortunate side-effect of this handling is that if there's more
473  than one PKCS #11 driver present and the user forgets to explicitly
474  specify it then this may load the wrong one, however the chances of
475  there being multiple drivers present on a Unix system is close to
476  zero so it's probably better to take the more user-friendly option
477  of trying to load a default driver */
478 #ifdef __UNIX__
479  if( !pkcs11Initialised )
480  {
481  status = loadPKCS11driver( &pkcs11InfoTbl[ tblIndex ],
482  "libpkcs11.so" );
483  if( cryptStatusOK( status ) )
484  pkcs11Initialised = TRUE;
485  }
486  if( !pkcs11Initialised )
487  {
488  status = loadPKCS11driver( &pkcs11InfoTbl[ tblIndex ],
489  "/opt/nfast/toolkits/pkcs11/libcknfast.so" );
490  if( cryptStatusOK( status ) )
491  pkcs11Initialised = TRUE;
492  }
493 #endif /* __UNIX__ */
494 
495  return( pkcs11Initialised ? CRYPT_OK : CRYPT_ERROR );
496  }
497 
498 #else
499 
500 int deviceInitPKCS11( void )
501  {
502  int status;
503 
504  /* If we've previously tried to initialise the drivers, don't try it
505  again */
506  if( pkcs11Initialised )
507  return( CRYPT_OK );
508 
509  status = C_Initialize( NULL_PTR );
510  if( status != CKR_OK && status != CKR_CRYPTOKI_ALREADY_INITIALIZED )
511  return( CRYPT_ERROR );
512  pkcs11Initialised = TRUE;
513  return( CRYPT_OK );
514  }
515 
516 void deviceEndPKCS11( void )
517  {
518  if( pkcs11Initialised )
519  C_Finalize( NULL_PTR );
520  pkcs11Initialised = FALSE;
521  }
522 #endif /* DYNAMIC_LOAD */
523 
524 /****************************************************************************
525 * *
526 * Device Capability Routines *
527 * *
528 ****************************************************************************/
529 
530 /* The reported key size for PKCS #11 implementations is rather inconsistent,
531  most are reported in bits, a number don't return a useful value, and a few
532  are reported in bytes. The following macros sort out which algorithms
533  have valid key size information and which report the length in bytes */
534 
535 #define keysizeValid( algo ) \
536  ( ( algo ) == CRYPT_ALGO_DH || ( algo ) == CRYPT_ALGO_RSA || \
537  ( algo ) == CRYPT_ALGO_DSA || ( algo ) == CRYPT_ALGO_RC2 || \
538  ( algo ) == CRYPT_ALGO_RC4 || ( algo ) == CRYPT_ALGO_RC5 )
539 #define keysizeInBytes( algo ) \
540  ( ( algo ) == CRYPT_ALGO_RC5 )
541 
542 /* Templates for the various capabilities. These contain only basic
543  information, the remaining fields are filled in when the capability is
544  set up */
545 
546 static CAPABILITY_INFO FAR_BSS capabilityTemplates[] = {
547  /* Encryption capabilities */
548  { CRYPT_ALGO_DES, bitsToBytes( 64 ), "DES", 3,
549  MIN_KEYSIZE, bitsToBytes( 64 ), bitsToBytes( 64 ) },
550  { CRYPT_ALGO_3DES, bitsToBytes( 64 ), "3DES", 4,
551  bitsToBytes( 64 + 8 ), bitsToBytes( 128 ), bitsToBytes( 192 ) },
552 #ifdef USE_RC2
553  { CRYPT_ALGO_RC2, bitsToBytes( 64 ), "RC2", 3,
554  MIN_KEYSIZE, bitsToBytes( 128 ), bitsToBytes( 1024 ) },
555 #endif /* USE_RC2 */
556 #ifdef USE_RC4
557  { CRYPT_ALGO_RC4, bitsToBytes( 8 ), "RC4", 3,
558  MIN_KEYSIZE, bitsToBytes( 128 ), 256 },
559 #endif /* USE_RC4 */
560 #ifdef USE_RC5
561  { CRYPT_ALGO_RC5, bitsToBytes( 64 ), "RC5", 3,
562  MIN_KEYSIZE, bitsToBytes( 128 ), bitsToBytes( 832 ) },
563 #endif /* USE_RC5 */
564  { CRYPT_ALGO_AES, bitsToBytes( 128 ), "AES", 3,
565  bitsToBytes( 128 ), bitsToBytes( 128 ), bitsToBytes( 256 ) },
566 #ifdef USE_BLOWFISH
567  { CRYPT_ALGO_BLOWFISH, bitsToBytes( 64 ), "Blowfish", 8,
568  MIN_KEYSIZE, bitsToBytes( 128 ), bitsToBytes( 448 ) },
569 #endif /* USE_BLOWFISH */
570 
571  /* Hash capabilities */
572 #ifdef USE_MD5
573  { CRYPT_ALGO_MD5, bitsToBytes( 128 ), "MD5", 3,
574  bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ) },
575 #endif /* USE_MD5 */
576  { CRYPT_ALGO_SHA1, bitsToBytes( 160 ), "SHA-1", 5,
577  bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ) },
578 #ifdef USE_SHA2
579  { CRYPT_ALGO_SHA2, bitsToBytes( 256 ), "SHA-2", 5,
580  bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ) },
581 #endif /* USE_SHA2 */
582 
583  /* MAC capabilities */
584 #ifdef USE_HMAC_MD5
585  { CRYPT_ALGO_HMAC_MD5, bitsToBytes( 128 ), "HMAC-MD5", 8,
586  bitsToBytes( 64 ), bitsToBytes( 128 ), CRYPT_MAX_KEYSIZE },
587 #endif /* USE_HMAC_MD5 */
588  { CRYPT_ALGO_HMAC_SHA1, bitsToBytes( 160 ), "HMAC-SHA1", 9,
589  bitsToBytes( 64 ), bitsToBytes( 128 ), CRYPT_MAX_KEYSIZE },
590 #ifdef USE_HMAC_RIPEMD160
591  { CRYPT_ALGO_HMAC_RIPEMD160, bitsToBytes( 160 ), "HMAC-RIPEMD160", 14,
592  bitsToBytes( 64 ), bitsToBytes( 128 ), CRYPT_MAX_KEYSIZE },
593 #endif /* USE_HMAC_RIPEMD160 */
594 #ifdef USE_HMAC_SHA2
595  { CRYPT_ALGO_HMAC_SHA2, bitsToBytes( 256 ), "HMAC-SHA2", 9,
596  bitsToBytes( 64 ), bitsToBytes( 128 ), CRYPT_MAX_KEYSIZE },
597 #endif /* USE_HMAC_SHA2 */
598 
599  /* Public-key capabilities */
600 #ifdef USE_DH
601  { CRYPT_ALGO_DH, bitsToBytes( 0 ), "Diffie-Hellman", 14,
603 #endif /* USE_DH */
604  { CRYPT_ALGO_RSA, bitsToBytes( 0 ), "RSA", 3,
606 #ifdef USE_DSA
607  { CRYPT_ALGO_DSA, bitsToBytes( 0 ), "DSA", 3,
609 #endif /* USE_DSA */
610 
611  /* Hier ist der Mast zu ende */
612  { CRYPT_ERROR }, { CRYPT_ERROR }
613  };
614 
615 /* Query a given capability for a device and fill out a capability
616  information record for it if present */
617 
618 static CAPABILITY_INFO *getCapability( const DEVICE_INFO *deviceInfo,
619  const PKCS11_MECHANISM_INFO *mechanismInfoPtr,
620  const int maxMechanisms )
621  {
622  VARIABLE_CAPABILITY_INFO *capabilityInfo;
623  CK_MECHANISM_INFO pMechanism;
624  CK_RV status;
625  const CRYPT_ALGO_TYPE cryptAlgo = mechanismInfoPtr->cryptAlgo;
626  const BOOLEAN isPKC = isPkcAlgo( cryptAlgo ) ? TRUE : FALSE;
627  const CK_FLAGS keyGenFlag = isPKC ? CKF_GENERATE_KEY_PAIR : CKF_GENERATE;
628  PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
629  int hardwareOnly, i, iterationCount;
630 
631  assert( isReadPtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
632  assert( isReadPtr( mechanismInfoPtr, \
633  maxMechanisms * sizeof( PKCS11_MECHANISM_INFO ) ) );
634 
635  /* Get the information for this mechanism. Since many PKCS #11 drivers
636  implement some of their capabilities using God knows what sort of
637  software implementation, we provide the option to skip emulated
638  mechanisms if required */
639  status = C_GetMechanismInfo( pkcs11Info->slotID,
640  mechanismInfoPtr->mechanism,
641  &pMechanism );
642  if( status != CKR_OK )
643  return( NULL );
646  if( hardwareOnly && !( pMechanism.flags & CKF_HW ) )
647  return( NULL );
648 
649  /* Copy across the template for this capability */
650  if( ( capabilityInfo = clAlloc( "getCapability", \
651  sizeof( CAPABILITY_INFO ) ) ) == NULL )
652  return( NULL );
653  for( i = 0; capabilityTemplates[ i ].cryptAlgo != cryptAlgo && \
654  capabilityTemplates[ i ].cryptAlgo != CRYPT_ERROR && \
655  i < FAILSAFE_ARRAYSIZE( capabilityTemplates, CAPABILITY_INFO );
656  i++ );
657  if( i >= FAILSAFE_ARRAYSIZE( capabilityTemplates, CAPABILITY_INFO ) || \
658  capabilityTemplates[ i ].cryptAlgo == CRYPT_ERROR )
660  memcpy( capabilityInfo, &capabilityTemplates[ i ],
661  sizeof( CAPABILITY_INFO ) );
662 
663  /* Set up the keysize information if there's anything useful available */
664  if( keysizeValid( cryptAlgo ) )
665  {
666  int minKeySize = ( int ) pMechanism.ulMinKeySize;
667  int maxKeySize = ( int ) pMechanism.ulMaxKeySize;
668 
669  /* Adjust the key size to bytes and make sure that all values are
670  consistent. Some implementations report silly lower bounds (e.g.
671  1-bit RSA, "You naughty minKey") so we adjust them to a sane value
672  if necessary. We also limit the maximum key size to match the
673  cryptlib native max.key size, both for consistency and because
674  cryptlib performs buffer allocation based on the maximum native
675  buffer size */
676  if( !keysizeInBytes( cryptAlgo ) )
677  {
678  minKeySize = bitsToBytes( minKeySize );
680  }
681  if( minKeySize > capabilityInfo->minKeySize )
682  capabilityInfo->minKeySize = minKeySize;
683  if( capabilityInfo->keySize < capabilityInfo->minKeySize )
684  capabilityInfo->keySize = capabilityInfo->minKeySize;
685  capabilityInfo->maxKeySize = min( maxKeySize,
686  capabilityInfo->maxKeySize );
687  if( capabilityInfo->maxKeySize < capabilityInfo->minKeySize )
688  {
689  /* Serious braindamage in the driver, we'll just have to make
690  a sensible guess */
691  DEBUG_DIAG(( "Maximum key size < minimum key size" ));
692  assert( DEBUG_WARN );
693  capabilityInfo->maxKeySize = \
694  ( cryptAlgo == CRYPT_ALGO_RSA || \
695  isDlpAlgo( cryptAlgo ) ) ? 128 : 16;
696  }
697  if( capabilityInfo->keySize > capabilityInfo->maxKeySize )
698  capabilityInfo->keySize = capabilityInfo->maxKeySize;
699  capabilityInfo->endFunction = genericEndFunction;
700  }
701 
702  /* Set up the device-specific handlers */
703  capabilityInfo->selfTestFunction = selfTestFunction;
704  capabilityInfo->getInfoFunction = getDefaultInfo;
705  if( cryptAlgo != CRYPT_ALGO_DH && cryptAlgo != CRYPT_ALGO_RSA && \
706  cryptAlgo != CRYPT_ALGO_DSA )
707  capabilityInfo->initParamsFunction = initGenericParams;
708  capabilityInfo->endFunction = mechanismInfoPtr->endFunction;
709  capabilityInfo->initKeyFunction = mechanismInfoPtr->initKeyFunction;
710  if( pMechanism.flags & keyGenFlag )
711  capabilityInfo->generateKeyFunction = \
712  mechanismInfoPtr->generateKeyFunction;
713  if( pMechanism.flags & CKF_SIGN )
714  {
715  /* cryptlib treats hashing as an encrypt/decrypt operation while
716  PKCS #11 treats it as a sign/verify operation, so we have to
717  juggle the function pointers based on the underlying algorithm
718  type */
719  if( isPKC )
720  capabilityInfo->signFunction = mechanismInfoPtr->signFunction;
721  else
722  capabilityInfo->encryptFunction = mechanismInfoPtr->encryptFunction;
723  }
724  if( pMechanism.flags & CKF_VERIFY )
725  {
726  /* See comment above */
727  if( isPKC )
728  capabilityInfo->sigCheckFunction = mechanismInfoPtr->sigCheckFunction;
729  else
730  capabilityInfo->decryptFunction = mechanismInfoPtr->decryptFunction;
731  }
732  if( pMechanism.flags & CKF_ENCRYPT )
733  {
734  /* Not all devices implement all modes, so we have to be careful to
735  set up the pointer for the exact mode that's supported */
736  switch( mechanismInfoPtr->cryptMode )
737  {
738  case CRYPT_MODE_CBC:
739  capabilityInfo->encryptCBCFunction = mechanismInfoPtr->encryptFunction;
740  break;
741 
742  case CRYPT_MODE_CFB:
743  capabilityInfo->encryptCFBFunction = mechanismInfoPtr->encryptFunction;
744  break;
745 
746  case CRYPT_MODE_OFB:
747  capabilityInfo->encryptOFBFunction = mechanismInfoPtr->encryptFunction;
748  break;
749 
750  case CRYPT_MODE_GCM:
751  capabilityInfo->encryptGCMFunction = mechanismInfoPtr->encryptFunction;
752  break;
753 
754  default: /* ECB or a PKC */
755  capabilityInfo->encryptFunction = mechanismInfoPtr->encryptFunction;
756  break;
757  }
758  }
759  if( pMechanism.flags & CKF_DECRYPT )
760  {
761  /* Not all devices implement all modes, so we have to be careful to
762  set up the pointer for the exact mode that's supported */
763  switch( mechanismInfoPtr->cryptMode )
764  {
765  case CRYPT_MODE_CBC:
766  capabilityInfo->decryptCBCFunction = mechanismInfoPtr->decryptFunction;
767  break;
768 
769  case CRYPT_MODE_CFB:
770  capabilityInfo->decryptCFBFunction = mechanismInfoPtr->decryptFunction;
771  break;
772 
773  case CRYPT_MODE_OFB:
774  capabilityInfo->decryptOFBFunction = mechanismInfoPtr->decryptFunction;
775  break;
776 
777  case CRYPT_MODE_GCM:
778  capabilityInfo->decryptGCMFunction = mechanismInfoPtr->decryptFunction;
779  break;
780 
781  default: /* ECB or a PKC */
782  capabilityInfo->decryptFunction = mechanismInfoPtr->decryptFunction;
783  break;
784  }
785  }
786  if( cryptAlgo == CRYPT_ALGO_DH && pMechanism.flags & CKF_DERIVE )
787  {
788  /* DH is a special-case that doesn't really have an encrypt function
789  and where "decryption" is actually a derivation */
790  capabilityInfo->encryptFunction = mechanismInfoPtr->encryptFunction;
791  capabilityInfo->decryptFunction = mechanismInfoPtr->decryptFunction;
792  }
793 
794  /* Keygen capabilities are generally present as separate mechanisms,
795  sometimes CKF_GENERATE/CKF_GENERATE_KEY_PAIR is set for the main
796  mechanism and sometimes it's set for the separate one so if it isn't
797  present in the main one we check the alternative one */
798  if( !( pMechanism.flags & keyGenFlag ) && \
799  ( mechanismInfoPtr->keygenMechanism != CKM_NONE ) )
800  {
801  status = C_GetMechanismInfo( pkcs11Info->slotID,
802  mechanismInfoPtr->keygenMechanism,
803  &pMechanism );
804  if( status == CKR_OK && ( pMechanism.flags & keyGenFlag ) && \
805  ( !hardwareOnly || ( pMechanism.flags & CKF_HW ) ) )
806  {
807  /* Some tinkertoy tokens don't implement key generation in
808  hardware but instead do it on the host PC (!!!) and load the
809  key into the token afterwards, so we have to perform another
810  check here to make sure that they're doing things right */
811  capabilityInfo->generateKeyFunction = \
812  mechanismInfoPtr->generateKeyFunction;
813  }
814  }
815 
816  /* Record mechanism-specific parameters if required */
817  if( isConvAlgo( cryptAlgo ) || isMacAlgo( cryptAlgo ) )
818  {
819  capabilityInfo->paramKeyType = mechanismInfoPtr->keyType;
820  capabilityInfo->paramKeyGen = mechanismInfoPtr->keygenMechanism;
821  capabilityInfo->paramDefaultMech = mechanismInfoPtr->defaultMechanism;
822  }
823 
824  /* If it's not a conventional encryption algo, we're done */
825  if( !isConvAlgo( cryptAlgo ) )
826  return( ( CAPABILITY_INFO * ) capabilityInfo );
827 
828  /* PKCS #11 handles encryption modes by defining a separate mechanism for
829  each one. In order to enumerate all the modes available for a
830  particular algorithm we check for each mechanism in turn and set up
831  the appropriate function pointers if it's available */
832  for( mechanismInfoPtr++, iterationCount = 0;
833  mechanismInfoPtr->cryptAlgo == cryptAlgo && \
834  iterationCount < maxMechanisms;
835  mechanismInfoPtr++, iterationCount++ )
836  {
837  /* There's a different form of the existing mechanism available,
838  check whether the driver implements it */
839  status = C_GetMechanismInfo( pkcs11Info->slotID,
840  mechanismInfoPtr->mechanism,
841  &pMechanism );
842  if( status != CKR_OK )
843  continue;
844 
845  /* Set up the pointer for the appropriate encryption mode */
846  switch( mechanismInfoPtr->cryptMode )
847  {
848  case CRYPT_MODE_CBC:
849  if( pMechanism.flags & CKF_ENCRYPT )
850  capabilityInfo->encryptCBCFunction = \
851  mechanismInfoPtr->encryptFunction;
852  if( pMechanism.flags & CKF_DECRYPT )
853  capabilityInfo->decryptCBCFunction = \
854  mechanismInfoPtr->decryptFunction;
855  break;
856  case CRYPT_MODE_CFB:
857  if( pMechanism.flags & CKF_ENCRYPT )
858  capabilityInfo->encryptCFBFunction = \
859  mechanismInfoPtr->encryptFunction;
860  if( pMechanism.flags & CKF_DECRYPT )
861  capabilityInfo->decryptCFBFunction = \
862  mechanismInfoPtr->decryptFunction;
863  break;
864  case CRYPT_MODE_OFB:
865  if( pMechanism.flags & CKF_ENCRYPT )
866  capabilityInfo->encryptOFBFunction = \
867  mechanismInfoPtr->encryptFunction;
868  if( pMechanism.flags & CKF_DECRYPT )
869  capabilityInfo->decryptOFBFunction = \
870  mechanismInfoPtr->decryptFunction;
871  break;
872  case CRYPT_MODE_GCM:
873  if( pMechanism.flags & CKF_ENCRYPT )
874  capabilityInfo->encryptGCMFunction = \
875  mechanismInfoPtr->encryptFunction;
876  if( pMechanism.flags & CKF_DECRYPT )
877  capabilityInfo->decryptGCMFunction = \
878  mechanismInfoPtr->decryptFunction;
879  break;
880 
881  default:
883  }
884  }
885  if( iterationCount >= maxMechanisms )
887 
888  return( ( CAPABILITY_INFO * ) capabilityInfo );
889  }
890 
891 /* Set the capability information based on device capabilities. Since
892  PKCS #11 devices can have assorted capabilities (and can vary depending
893  on what's plugged in), we have to build this up on the fly rather than
894  using a fixed table like the built-in capabilities */
895 
896 static void freeCapabilities( DEVICE_INFO *deviceInfo )
897  {
898  CAPABILITY_INFO_LIST *capabilityInfoListPtr = \
899  ( CAPABILITY_INFO_LIST * ) deviceInfo->capabilityInfoList;
900 
901  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
902 
903  /* If the list was empty, return now */
904  if( capabilityInfoListPtr == NULL )
905  return;
906  deviceInfo->capabilityInfoList = NULL;
907 
908  while( capabilityInfoListPtr != NULL )
909  {
910  CAPABILITY_INFO_LIST *listItemToFree = capabilityInfoListPtr;
911  CAPABILITY_INFO *itemToFree = ( CAPABILITY_INFO * ) listItemToFree->info;
912 
913  capabilityInfoListPtr = capabilityInfoListPtr->next;
914  zeroise( itemToFree, sizeof( CAPABILITY_INFO ) );
915  clFree( "freeCapabilities", itemToFree );
916  zeroise( listItemToFree, sizeof( CAPABILITY_INFO_LIST ) );
917  clFree( "freeCapabilities", listItemToFree );
918  }
919  }
920 
921 static int getCapabilities( DEVICE_INFO *deviceInfo,
922  const PKCS11_MECHANISM_INFO *mechanismInfoPtr,
923  const int maxMechanisms )
924  {
925  CAPABILITY_INFO_LIST *capabilityInfoListTail = \
926  ( CAPABILITY_INFO_LIST * ) deviceInfo->capabilityInfoList;
927  int i;
928 
929  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
930  assert( isReadPtr( mechanismInfoPtr, \
931  maxMechanisms * sizeof( PKCS11_MECHANISM_INFO ) ) );
932 
934  "Variable capability-info-struct" );
935 
936  /* Find the end of the list to add new capabilities */
937  if( capabilityInfoListTail != NULL )
938  {
939  while( capabilityInfoListTail->next != NULL )
940  capabilityInfoListTail = capabilityInfoListTail->next;
941  }
942 
943  /* Add capability information for each recognised mechanism type */
944  for( i = 0; i < maxMechanisms && \
945  mechanismInfoPtr[ i ].mechanism != CKM_NONE; i++ )
946  {
947  CAPABILITY_INFO_LIST *newCapabilityList;
948  CAPABILITY_INFO *newCapability;
949  const CRYPT_ALGO_TYPE cryptAlgo = mechanismInfoPtr[ i ].cryptAlgo;
950 
951  /* If the assertion below triggers then the PKCS #11 driver is
952  broken since it's returning inconsistent information such as
953  illegal key length data, conflicting algorithm information, etc
954  etc. This assertion is included here to detect buggy drivers
955  early on rather than forcing users to step through the PKCS #11
956  glue code to find out why an operation is failing.
957 
958  Because some tinkertoy implementations support only the bare
959  minimum functionality (e.g.RSA private key ops and nothing else),
960  we allow asymmetric functionality for PKCs */
961  newCapability = getCapability( deviceInfo, &mechanismInfoPtr[ i ],
962  maxMechanisms - i );
963  if( newCapability == NULL )
964  continue;
965  REQUIRES( sanityCheckCapability( newCapability,
966  isPkcAlgo( newCapability->cryptAlgo ) ? \
967  TRUE : FALSE ) );
968  if( ( newCapabilityList = \
969  clAlloc( "getCapabilities", \
970  sizeof( CAPABILITY_INFO_LIST ) ) ) == NULL )
971  {
972  clFree( "getCapabilities", newCapability );
973  continue;
974  }
975  newCapabilityList->info = newCapability;
976  newCapabilityList->next = NULL;
977  if( deviceInfo->capabilityInfoList == NULL )
978  deviceInfo->capabilityInfoList = newCapabilityList;
979  else
980  capabilityInfoListTail->next = newCapabilityList;
981  capabilityInfoListTail = newCapabilityList;
982 
983  /* Since there may be alternative mechanisms to the current one
984  defined, we have to skip mechanisms until we find a ones for a
985  new algorithm */
986  while( mechanismInfoPtr[ i + 1 ].cryptAlgo == cryptAlgo && \
987  i < maxMechanisms )
988  i++;
989  if( i >= maxMechanisms )
990  retIntError();
991  }
992  if( i >= maxMechanisms )
993  retIntError();
994 
995  return( ( deviceInfo->capabilityInfoList == NULL ) ? CRYPT_ERROR : CRYPT_OK );
996  }
997 
998 /****************************************************************************
999 * *
1000 * Device Init/Shutdown/Device Control Routines *
1001 * *
1002 ****************************************************************************/
1003 
1004 /* Close a previously-opened session with the device. We have to have this
1005  before the initialisation function since it may be called by it if the
1006  initialisation process fails */
1007 
1008 static void shutdownFunction( DEVICE_INFO *deviceInfo )
1009  {
1010  PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
1011 
1012  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
1013 
1014  /* Log out and close the session with the device */
1015  if( deviceInfo->flags & DEVICE_LOGGEDIN )
1016  C_Logout( pkcs11Info->hSession );
1017  C_CloseSession( pkcs11Info->hSession );
1018  pkcs11Info->hSession = CK_OBJECT_NONE;
1019  deviceInfo->flags &= ~( DEVICE_ACTIVE | DEVICE_LOGGEDIN );
1020 
1021  /* Free the device capability information */
1022  freeCapabilities( deviceInfo );
1023  }
1024 
1025 /* Open a session with the device */
1026 
1027 static int initFunction( DEVICE_INFO *deviceInfo, const char *name,
1028  const int nameLength )
1029  {
1030  CK_SESSION_HANDLE hSession;
1031  CK_SLOT_ID slotList[ MAX_PKCS11_SLOTS + 8 ];
1032  CK_ULONG slotCount = MAX_PKCS11_SLOTS;
1033  CK_SLOT_INFO slotInfo;
1034  CK_TOKEN_INFO tokenInfo;
1035  CK_RV status;
1036  PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
1037  const PKCS11_MECHANISM_INFO *mechanismInfoPtr;
1038  char *labelPtr;
1039  int tokenSlot = DEFAULT_SLOT, i, labelLength, mechanismInfoSize;
1040  int cryptStatus, cryptStatus2;
1041 
1042  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
1043  assert( isReadPtr( name, nameLength ) );
1044 
1045  /* Get information on all available slots */
1046  memset( slotList, 0, sizeof( slotList ) );
1047  status = C_GetSlotList( TRUE, slotList, &slotCount );
1048  if( status != CKR_OK )
1049  return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
1050  if( slotCount <= 0 )
1051  {
1052  /* There are token slots present but no tokens in the slots */
1053  return( CRYPT_ERROR_OPEN );
1054  }
1055 
1056  /* Check whether a token name (used to select the slot) has been
1057  specified */
1058  for( i = 1; i < nameLength - 1; i++ )
1059  {
1060  if( name[ i ] == ':' && name[ i + 1 ] == ':' )
1061  break;
1062  }
1063  if( i < nameLength - 1 )
1064  {
1065  const char *tokenName = name + i + 2; /* Skip '::' */
1066  const int tokenNameLength = nameLength - ( i + 2 );
1067 
1068  if( tokenNameLength <= 0 )
1069  return( CRYPT_ARGERROR_STR1 );
1070 
1071  /* Some tokens don't implement named slots, so we also allow them to
1072  be specified using slot counts */
1073  if( tokenNameLength == 1 && isDigit( *tokenName ) )
1074  {
1075  tokenSlot = *tokenName - '0';
1076  if( tokenSlot < 0 || tokenSlot > 9 )
1077  return( CRYPT_ARGERROR_STR1 );
1078  if( tokenSlot > slotCount - 1 ) /* Slots numbered from zero */
1079  return( CRYPT_ERROR_NOTFOUND );
1080  status = C_GetTokenInfo( slotList[ tokenSlot ], &tokenInfo );
1081  if( status != CKR_OK )
1082  return( CRYPT_ERROR_NOTFOUND );
1083  }
1084  else
1085  {
1086  /* Check each (named) slot for a token matching the given name */
1087  for( tokenSlot = 0; tokenSlot < slotCount && \
1088  tokenSlot < FAILSAFE_ITERATIONS_MED;
1089  tokenSlot++ )
1090  {
1091  status = C_GetTokenInfo( slotList[ tokenSlot ], &tokenInfo );
1092  if( status == CKR_OK && \
1093  !strCompare( tokenName, tokenInfo.label, tokenNameLength ) )
1094  break;
1095  }
1096  if( tokenSlot >= FAILSAFE_ITERATIONS_MED )
1097  retIntError();
1098  if( tokenSlot >= slotCount )
1099  return( CRYPT_ERROR_NOTFOUND );
1100  }
1101  }
1102  pkcs11Info->slotID = slotList[ tokenSlot ];
1103 
1104  /* Get information on device-specific capabilities */
1105  status = C_GetSlotInfo( pkcs11Info->slotID, &slotInfo );
1106  if( status != CKR_OK )
1107  {
1108  shutdownFunction( deviceInfo );
1109  return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
1110  }
1111  if( slotInfo.flags & CKF_REMOVABLE_DEVICE )
1112  {
1113  /* The device is removable */
1114  deviceInfo->flags |= DEVICE_REMOVABLE;
1115  }
1116  status = C_GetTokenInfo( pkcs11Info->slotID, &tokenInfo );
1117  if( status != CKR_OK )
1118  {
1119  shutdownFunction( deviceInfo );
1120  return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
1121  }
1122  if( tokenInfo.flags & CKF_RNG )
1123  {
1124  /* The device has an onboard RNG that we can use */
1125  deviceInfo->getRandomFunction = getRandomFunction;
1126  }
1127 #if 0 /* The Spyrus driver for pre-Lynks-II cards returns the local system
1128  time (with a GMT/localtime offset), ignoring the fact that the
1129  token has an onboard clock, so having the CKF_CLOCK_ON_TOKEN not
1130  set is accurate, although having it ignore the presence of the
1131  clock isn't very valid */
1132  if( !( tokenInfo.flags & CKF_CLOCK_ON_TOKEN ) && \
1133  ( !strCompare( tokenInfo.label, "Lynks Token", 11 ) || \
1134  !strCompare( tokenInfo.model, "Rosetta", 7 ) ) )
1135  {
1136  /* Fix buggy Spyrus PKCS #11 drivers which claim that the token
1137  doesn't have a RTC even though it does (the Rosetta (smart card)
1138  form of the token is even worse, it returns garbage in the label
1139  and manufacturer fields, but the model field is OK). There is a
1140  chance that there's a genuine problem with the clock (there are
1141  batches of tokens with bad clocks) but the time check that
1142  follows below will catch those */
1143  tokenInfo.flags |= CKF_CLOCK_ON_TOKEN;
1144  }
1145 #endif /* 0 */
1146  if( tokenInfo.flags & CKF_CLOCK_ON_TOKEN )
1147  {
1148  const time_t theTime = getTokenTime( &tokenInfo );
1149  const time_t currentTime = getTime();
1150 
1151  /* The token claims to have an onboard clock that we can use. Since
1152  this could be arbitrarily inaccurate we compare it with the
1153  system time and only rely on it if it's within +/- 1 day of the
1154  system time.
1155 
1156  There is a second check that we should make to catch drivers that
1157  claim to read the time from the token but actually use the local
1158  computer's time, but this isn't easy to do. The most obvious way
1159  is to set the system time to a bogus value and check whether this
1160  matches the returned time, but this is somewhat drastic and
1161  requires superuser privs on most systems. An alternative is to
1162  check whether the claimed token time exactly matches the system
1163  time, but this will produce false positives if (for example) the
1164  token has been recently synchronised to the system time. For now
1165  all we can do is throw an exception if it appears that the token
1166  time is faked */
1167  if( theTime > MIN_TIME_VALUE && \
1168  theTime >= currentTime - 86400 && \
1169  theTime <= currentTime + 86400 )
1170  deviceInfo->flags |= DEVICE_TIME;
1171 
1172  /* If this assertion is triggered then the token time may be faked
1173  since it's identical to the host system time, see the comment
1174  above for details. We make an exception for soft-tokens, which
1175  will (by definition) have the same time as the system time */
1176  assert( ( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name[ 0 ] && \
1177  !strCompare( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name,
1178  "Software", 8 ) ) || \
1179  theTime < currentTime - 1 || theTime > currentTime + 1 );
1180  }
1181  if( tokenInfo.flags & CKF_WRITE_PROTECTED )
1182  {
1183  /* The device can't have data on it changed */
1184  deviceInfo->flags |= DEVICE_READONLY;
1185  }
1186  if( ( tokenInfo.flags & CKF_LOGIN_REQUIRED ) || \
1187  !( tokenInfo.flags & CKF_USER_PIN_INITIALIZED ) )
1188  {
1189  /* The user needs to log in before using various device functions.
1190  We check for the absence of CKF_USER_PIN_INITIALIZED as well as
1191  the more obvious CKF_LOGIN_REQUIRED because if we've got an
1192  uninitialised device there's no PIN set so some devices will
1193  report that there's no login required (or at least none is
1194  possible). We need to introduce some sort of pipeline stall if
1195  this is the case because otherwise the user could successfully
1196  perform some functions that don't require a login (where the
1197  exact details of what's allowed without a login are device-
1198  specific) before running into mysterious failures when they get
1199  to functions that do require a login. To avoid this, we make an
1200  uninitialised device look like a login-required device, so the
1201  user gets an invalid-PIN error if they try and proceed */
1202  deviceInfo->flags |= DEVICE_NEEDSLOGIN;
1203  }
1204  if( ( pkcs11Info->minPinSize = ( int ) tokenInfo.ulMinPinLen ) < 4 )
1205  {
1206  /* Some devices report silly PIN sizes */
1207  pkcs11Info->minPinSize = 4;
1208  }
1209  if( ( pkcs11Info->maxPinSize = ( int ) tokenInfo.ulMaxPinLen ) < 4 )
1210  {
1211  /* Some devices report silly PIN sizes (setting this to ULONG_MAX or
1212  4GB, which becomes -1 as an int, counts as silly). Since we can't
1213  differentiate between 0xFFFFFFFF = bogus value and 0xFFFFFFFF =
1214  ULONG_MAX we play it safe and set the limit to 8 bytes, which most
1215  devices should be able to handle */
1216  pkcs11Info->maxPinSize = 8;
1217  }
1218  labelPtr = ( char * ) tokenInfo.label;
1219  for( labelLength = 32;
1220  labelLength > 0 && \
1221  ( labelPtr[ labelLength - 1 ] == ' ' || \
1222  !labelPtr[ labelLength - 1 ] );
1223  labelLength-- ); /* Strip trailing blanks/nulls */
1224  while( labelLength > 0 && *labelPtr == ' ' )
1225  {
1226  /* Strip leading blanks */
1227  labelPtr++;
1228  labelLength--;
1229  }
1230  if( labelLength > 0 )
1231  {
1232  memcpy( pkcs11Info->label, labelPtr, labelLength );
1233  pkcs11Info->labelLen = labelLength;
1234  sanitiseString( pkcs11Info->label, CRYPT_MAX_TEXTSIZE,
1235  labelLength );
1236  }
1237  else
1238  {
1239  /* There's no label for the token, use the device label instead */
1240  if( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name[ 0 ] )
1241  {
1242  labelLength = \
1243  min( strlen( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name ),
1245  memcpy( pkcs11Info->label,
1246  pkcs11InfoTbl[ pkcs11Info->deviceNo ].name, labelLength );
1247  }
1248  }
1249  pkcs11Info->hActiveSignObject = CK_OBJECT_NONE;
1250  deviceInfo->label = pkcs11Info->label;
1251  deviceInfo->labelLen = pkcs11Info->labelLen;
1252 
1253  /* Open a session with the device. This gets a bit awkward because we
1254  can't tell whether a R/W session is OK without opening a session, but
1255  we can't open a session unless we know whether a R/W session is OK,
1256  so we first try for a RW session and if that fails we go for a read-
1257  only session */
1258  status = C_OpenSession( pkcs11Info->slotID,
1259  CKF_RW_SESSION | CKF_SERIAL_SESSION, NULL_PTR,
1260  NULL_PTR, &hSession );
1261  if( status == CKR_TOKEN_WRITE_PROTECTED )
1262  status = C_OpenSession( pkcs11Info->slotID,
1263  CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR,
1264  &hSession );
1265  if( status != CKR_OK )
1266  {
1267  cryptStatus = pkcs11MapError( status, CRYPT_ERROR_OPEN );
1268  if( cryptStatus == CRYPT_ERROR_OPEN && \
1269  !( tokenInfo.flags & CKF_USER_PIN_INITIALIZED ) )
1270  {
1271  /* We couldn't do much with the error code, it could be that the
1272  token hasn't been initialised yet but unfortunately PKCS #11
1273  doesn't define an error code for this condition. In addition
1274  many tokens will allow a session to be opened and then fail
1275  with a "PIN not set" error at a later point (which allows for
1276  more accurate error reporting), however a small number won't
1277  allow a session to be opened and return some odd-looking error
1278  because there's nothing useful available. The best way to
1279  report this in a meaningful manner to the caller is to check
1280  whether the user PIN has been initialised, if it hasn't then
1281  it's likely that the token as a whole hasn't been initialised
1282  so we return a not initialised error */
1283  cryptStatus = CRYPT_ERROR_NOTINITED;
1284  }
1285  return( cryptStatus );
1286  }
1287  ENSURES( hSession != CK_OBJECT_NONE );
1288  pkcs11Info->hSession = hSession;
1289  deviceInfo->flags |= DEVICE_ACTIVE;
1290 
1291  /* Set up the capability information for this device. Since there can
1292  be devices that have one set of capabilities but not the other (e.g.
1293  a smart card that only performs RSA ops), we allow one of the two
1294  sets of mechanism information setups to fail, but not both */
1295  mechanismInfoPtr = getMechanismInfoPKC( &mechanismInfoSize );
1296  cryptStatus = getCapabilities( deviceInfo, mechanismInfoPtr,
1297  mechanismInfoSize );
1298  mechanismInfoPtr = getMechanismInfoConv( &mechanismInfoSize );
1299  cryptStatus2 = getCapabilities( deviceInfo, mechanismInfoPtr,
1300  mechanismInfoSize );
1301  if( cryptStatusError( cryptStatus ) && cryptStatusError( cryptStatus2 ) )
1302  {
1303  shutdownFunction( deviceInfo );
1304  return( ( cryptStatus == CRYPT_ERROR ) ? \
1305  CRYPT_ERROR_OPEN : ( int ) cryptStatus );
1306  }
1307 
1308  return( CRYPT_OK );
1309  }
1310 
1311 /* Set up the function pointers to the init/shutdown methods */
1312 
1313 int initPKCS11Init( DEVICE_INFO *deviceInfo, const char *name,
1314  const int nameLength )
1315  {
1316  PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
1317 #ifdef DYNAMIC_LOAD
1318  int i, driverNameLength = nameLength;
1319 #else
1320  UNUSED_ARG( name );
1321 #endif /* DYNAMIC_LOAD */
1322 
1323  assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
1324  assert( isReadPtr( name, nameLength ) );
1325 
1326  /* Make sure that the PKCS #11 driver DLL's are loaded */
1327  if( !pkcs11Initialised )
1328  return( CRYPT_ERROR_OPEN );
1329 
1330 #ifdef DYNAMIC_LOAD
1331  /* Check whether there's a token name appended to the driver name */
1332  for( i = 1; i < nameLength - 1; i++ )
1333  {
1334  if( name[ i ] == ':' && name[ i + 1 ] == ':' )
1335  {
1336  driverNameLength = i;
1337  break;
1338  }
1339  }
1340 
1341  /* If we're auto-detecting the device, use the first one that we find.
1342  There are two basic approaches to this, to keep going until we find
1343  something that responds, or to try the first device and report an
1344  error if it doesn't respond. Both have their own problems, keeping
1345  going will find (for example) the device in slot 2 if slot 1 is
1346  empty, but will also return a completely unexpected device if slot 1
1347  contains a device that isn't responding for some reason. Conversely,
1348  only checking the first device will fail if slot 1 is empty but slot
1349  2 isn't. Users seem to prefer the obvious-fail approach, so we only
1350  check the first device and fail if there's a problem. If they
1351  explicitly want a secondary slot, they can specify it by name */
1352  if( driverNameLength == 12 && \
1353  !strnicmp( "[Autodetect]", name, driverNameLength ) )
1354  {
1355  if( !pkcs11InfoTbl[ 0 ].name[ 0 ] )
1356  return( CRYPT_ERROR_NOTFOUND );
1357  pkcs11Info->deviceNo = 0;
1358  }
1359  else
1360  {
1361  /* Try and find the driver based on its name */
1362  for( i = 0; i < MAX_PKCS11_DRIVERS; i++ )
1363  {
1364  if( !strnicmp( pkcs11InfoTbl[ i ].name, name, driverNameLength ) )
1365  break;
1366  }
1367  if( i >= MAX_PKCS11_DRIVERS )
1368  return( CRYPT_ERROR_NOTFOUND );
1369  pkcs11Info->deviceNo = i;
1370  }
1371 #endif /* DYNAMIC_LOAD */
1372 
1373  /* Set up remaining function and access information */
1374  deviceInfo->initFunction = initFunction;
1375  deviceInfo->shutdownFunction = shutdownFunction;
1376  deviceInfo->devicePKCS11->functionListPtr = \
1377  pkcs11InfoTbl[ pkcs11Info->deviceNo ].functionListPtr;
1378 
1379  return( CRYPT_OK );
1380  }
1381 #endif /* USE_PKCS11 */