1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 #ifndef _PK11PUB_H_
5 #define _PK11PUB_H_
6 #include "plarena.h"
7 #include "seccomon.h"
8 #include "secoidt.h"
9 #include "secdert.h"
10 #include "keythi.h"
11 #include "certt.h"
12 #include "pk11hpke.h"
13 #include "pkcs11t.h"
14 #include "secmodt.h"
15 #include "seccomon.h"
16 #include "pkcs7t.h"
17 #include "cmsreclist.h"
18 
19 /*
20  * Exported PK11 wrap functions.
21  */
22 
23 SEC_BEGIN_PROTOS
24 
25 /************************************************************
26  * Generic Slot Lists Management
27  ************************************************************/
28 void PK11_FreeSlotList(PK11SlotList *list);
29 SECStatus PK11_FreeSlotListElement(PK11SlotList *list, PK11SlotListElement *le);
30 PK11SlotListElement *PK11_GetFirstSafe(PK11SlotList *list);
31 PK11SlotListElement *PK11_GetNextSafe(PK11SlotList *list,
32                                       PK11SlotListElement *le, PRBool restart);
33 
34 /************************************************************
35  * Generic Slot Management
36  ************************************************************/
37 PK11SlotInfo *PK11_ReferenceSlot(PK11SlotInfo *slot);
38 void PK11_FreeSlot(PK11SlotInfo *slot);
39 SECStatus PK11_DestroyObject(PK11SlotInfo *slot, CK_OBJECT_HANDLE object);
40 SECStatus PK11_DestroyTokenObject(PK11SlotInfo *slot, CK_OBJECT_HANDLE object);
41 PK11SlotInfo *PK11_GetInternalKeySlot(void);
42 PK11SlotInfo *PK11_GetInternalSlot(void);
43 SECStatus PK11_Logout(PK11SlotInfo *slot);
44 void PK11_LogoutAll(void);
45 
46 /************************************************************
47  *  Slot Password Management
48  ************************************************************/
49 void PK11_SetSlotPWValues(PK11SlotInfo *slot, int askpw, int timeout);
50 void PK11_GetSlotPWValues(PK11SlotInfo *slot, int *askpw, int *timeout);
51 SECStatus PK11_CheckSSOPassword(PK11SlotInfo *slot, char *ssopw);
52 SECStatus PK11_CheckUserPassword(PK11SlotInfo *slot, const char *pw);
53 PRBool PK11_IsLoggedIn(PK11SlotInfo *slot, void *wincx);
54 SECStatus PK11_InitPin(PK11SlotInfo *slot, const char *ssopw,
55                        const char *pk11_userpwd);
56 SECStatus PK11_ChangePW(PK11SlotInfo *slot, const char *oldpw,
57                         const char *newpw);
58 void PK11_SetPasswordFunc(PK11PasswordFunc func);
59 int PK11_GetMinimumPwdLength(PK11SlotInfo *slot);
60 SECStatus PK11_ResetToken(PK11SlotInfo *slot, char *sso_pwd);
61 SECStatus PK11_Authenticate(PK11SlotInfo *slot, PRBool loadCerts, void *wincx);
62 SECStatus PK11_TokenRefresh(PK11SlotInfo *slot);
63 
64 /******************************************************************
65  *           Slot info functions
66  ******************************************************************/
67 PK11SlotInfo *PK11_FindSlotByName(const char *name);
68 /******************************************************************
69  * PK11_FindSlotsByNames searches for a PK11SlotInfo using one or
70  * more criteria : dllName, slotName and tokenName . In addition, if
71  * presentOnly is set , only slots with a token inserted will be
72  * returned.
73  ******************************************************************/
74 PK11SlotList *PK11_FindSlotsByNames(const char *dllName,
75                                     const char *slotName, const char *tokenName, PRBool presentOnly);
76 PRBool PK11_IsReadOnly(PK11SlotInfo *slot);
77 PRBool PK11_IsInternal(PK11SlotInfo *slot);
78 PRBool PK11_IsInternalKeySlot(PK11SlotInfo *slot);
79 char *PK11_GetTokenName(PK11SlotInfo *slot);
80 char *PK11_GetTokenURI(PK11SlotInfo *slot);
81 char *PK11_GetSlotName(PK11SlotInfo *slot);
82 PRBool PK11_NeedLogin(PK11SlotInfo *slot);
83 PRBool PK11_IsFriendly(PK11SlotInfo *slot);
84 PRBool PK11_IsHW(PK11SlotInfo *slot);
85 PRBool PK11_IsRemovable(PK11SlotInfo *slot);
86 PRBool PK11_NeedUserInit(PK11SlotInfo *slot);
87 PRBool PK11_ProtectedAuthenticationPath(PK11SlotInfo *slot);
88 int PK11_GetSlotSeries(PK11SlotInfo *slot);
89 int PK11_GetCurrentWrapIndex(PK11SlotInfo *slot);
90 unsigned long PK11_GetDefaultFlags(PK11SlotInfo *slot);
91 CK_SLOT_ID PK11_GetSlotID(PK11SlotInfo *slot);
92 SECMODModuleID PK11_GetModuleID(PK11SlotInfo *slot);
93 SECStatus PK11_GetSlotInfo(PK11SlotInfo *slot, CK_SLOT_INFO *info);
94 SECStatus PK11_GetTokenInfo(PK11SlotInfo *slot, CK_TOKEN_INFO *info);
95 PRBool PK11_IsDisabled(PK11SlotInfo *slot);
96 PRBool PK11_HasRootCerts(PK11SlotInfo *slot);
97 PK11DisableReasons PK11_GetDisabledReason(PK11SlotInfo *slot);
98 /* Prevents the slot from being used, and set disable reason to user-disable */
99 /* NOTE: Mechanisms that were ON continue to stay ON */
100 /*       Therefore, when the slot is enabled, it will remember */
101 /*       what mechanisms needs to be turned on */
102 PRBool PK11_UserDisableSlot(PK11SlotInfo *slot);
103 /* Allow all mechanisms that are ON before UserDisableSlot() */
104 /* was called to be available again */
105 PRBool PK11_UserEnableSlot(PK11SlotInfo *slot);
106 /*
107  * wait for a specific slot event.
108  * event is a specific event to wait for. Currently only
109  *    PK11TokenChangeOrRemovalEvent and PK11TokenPresentEvents are defined.
110  * timeout can be an interval time to wait, PR_INTERVAL_NO_WAIT (meaning only
111  * poll once), or PR_INTERVAL_NO_TIMEOUT (meaning block until a change).
112  * pollInterval is a suggested pulling interval value. '0' means use the
113  *  default. Future implementations that don't poll may ignore this value.
114  * series is the current series for the last slot. This should be the series
115  *  value for the slot the last time you read persistant information from the
116  *  slot. For instance, if you publish a cert from the slot, you should obtain
117  *  the slot series at that time. Then PK11_WaitForTokenEvent can detect a
118  *  a change in the slot between the time you publish and the time
119  *  PK11_WaitForTokenEvent is called, elliminating potential race conditions.
120  *
121  * The current status that is returned is:
122  *   PK11TokenNotRemovable - always returned for any non-removable token.
123  *   PK11TokenPresent - returned when the token is present and we are waiting
124  *     on a PK11TokenPresentEvent. Then next event to look for is a
125  *     PK11TokenChangeOrRemovalEvent.
126  *   PK11TokenChanged - returned when the old token has been removed and a new
127  *     token ad been inserted, and we are waiting for a
128  *     PK11TokenChangeOrRemovalEvent. The next event to look for is another
129  *     PK11TokenChangeOrRemovalEvent.
130  *   PK11TokenRemoved - returned when the token is not present and we are
131  *     waiting for a PK11TokenChangeOrRemovalEvent. The next event to look for
132  *     is a PK11TokenPresentEvent.
133  */
134 PK11TokenStatus PK11_WaitForTokenEvent(PK11SlotInfo *slot, PK11TokenEvent event,
135                                        PRIntervalTime timeout, PRIntervalTime pollInterval, int series);
136 
137 PRBool PK11_NeedPWInit(void);
138 PRBool PK11_TokenExists(CK_MECHANISM_TYPE);
139 SECStatus PK11_GetModInfo(SECMODModule *mod, CK_INFO *info);
140 char *PK11_GetModuleURI(SECMODModule *mod);
141 PRBool PK11_IsFIPS(void);
142 SECMODModule *PK11_GetModule(PK11SlotInfo *slot);
143 
144 /*********************************************************************
145  *            Slot mapping utility functions.
146  *********************************************************************/
147 PRBool PK11_IsPresent(PK11SlotInfo *slot);
148 PRBool PK11_DoesMechanism(PK11SlotInfo *slot, CK_MECHANISM_TYPE type);
149 PK11SlotList *PK11_GetAllTokens(CK_MECHANISM_TYPE type, PRBool needRW,
150                                 PRBool loadCerts, void *wincx);
151 PK11SlotInfo *PK11_GetBestSlotMultipleWithAttributes(CK_MECHANISM_TYPE *type,
152                                                      CK_FLAGS *mechFlag, unsigned int *keySize,
153                                                      unsigned int count, void *wincx);
154 PK11SlotInfo *PK11_GetBestSlotMultiple(CK_MECHANISM_TYPE *type,
155                                        unsigned int count, void *wincx);
156 PK11SlotInfo *PK11_GetBestSlot(CK_MECHANISM_TYPE type, void *wincx);
157 PK11SlotInfo *PK11_GetBestSlotWithAttributes(CK_MECHANISM_TYPE type,
158                                              CK_FLAGS mechFlag, unsigned int keySize, void *wincx);
159 CK_MECHANISM_TYPE PK11_GetBestWrapMechanism(PK11SlotInfo *slot);
160 int PK11_GetBestKeyLength(PK11SlotInfo *slot, CK_MECHANISM_TYPE type);
161 
162 /*
163  * Open a new database using the softoken. The caller is responsible for making
164  * sure the module spec is correct and usable. The caller should ask for one
165  * new database per call if the caller wants to get meaningful information
166  * about the new database.
167  *
168  * moduleSpec is the same data that you would pass to softoken at
169  * initialization time under the 'tokens' options. For example, if you were
170  * to specify tokens=<0x4=[configdir='./mybackup' tokenDescription='Backup']>
171  * You would specify "configdir='./mybackup' tokenDescription='Backup'" as your
172  * module spec here. The slot ID will be calculated for you by
173  * SECMOD_OpenUserDB().
174  *
175  * Typical parameters here are configdir, tokenDescription and flags.
176  *
177  * a Full list is below:
178  *
179  *
180  *  configDir - The location of the databases for this token. If configDir is
181  *         not specified, and noCertDB and noKeyDB is not specified, the load
182  *         will fail.
183  *   certPrefix - Cert prefix for this token.
184  *   keyPrefix - Prefix for the key database for this token. (if not specified,
185  *         certPrefix will be used).
186  *   tokenDescription - The label value for this token returned in the
187  *         CK_TOKEN_INFO structure with an internationalize string (UTF8).
188  *         This value will be truncated at 32 bytes (no NULL, partial UTF8
189  *         characters dropped). You should specify a user friendly name here
190  *         as this is the value the token will be referred to in most
191  *         application UI's. You should make sure tokenDescription is unique.
192  *   slotDescription - The slotDescription value for this token returned
193  *         in the CK_SLOT_INFO structure with an internationalize string
194  *         (UTF8). This value will be truncated at 64 bytes (no NULL, partial
195  *         UTF8 characters dropped). This name will not change after the
196  *         database is closed. It should have some number to make this unique.
197  *   minPWLen - minimum password length for this token.
198  *   flags - comma separated list of flag values, parsed case-insensitive.
199  *         Valid flags are:
200  *              readOnly - Databases should be opened read only.
201  *              noCertDB - Don't try to open a certificate database.
202  *              noKeyDB - Don't try to open a key database.
203  *              forceOpen - Don't fail to initialize the token if the
204  *                databases could not be opened.
205  *              passwordRequired - zero length passwords are not acceptable
206  *                (valid only if there is a keyDB).
207  *              optimizeSpace - allocate smaller hash tables and lock tables.
208  *                When this flag is not specified, Softoken will allocate
209  *                large tables to prevent lock contention.
210  */
211 PK11SlotInfo *SECMOD_OpenUserDB(const char *moduleSpec);
212 SECStatus SECMOD_CloseUserDB(PK11SlotInfo *slot);
213 
214 /*
215  * This is exactly the same as OpenUserDB except it can be called on any
216  * module that understands softoken style new slot entries. The resulting
217  * slot can be closed using SECMOD_CloseUserDB above. Value of moduleSpec
218  * is token specific.
219  */
220 PK11SlotInfo *SECMOD_OpenNewSlot(SECMODModule *mod, const char *moduleSpec);
221 
222 /*
223  * merge the permanent objects from on token to another
224  */
225 SECStatus PK11_MergeTokens(PK11SlotInfo *targetSlot, PK11SlotInfo *sourceSlot,
226                            PK11MergeLog *log, void *targetPwArg, void *sourcePwArg);
227 
228 /*
229  * create and destroy merge logs needed by PK11_MergeTokens
230  */
231 PK11MergeLog *PK11_CreateMergeLog(void);
232 void PK11_DestroyMergeLog(PK11MergeLog *log);
233 
234 /*********************************************************************
235  *       Mechanism Mapping functions
236  *********************************************************************/
237 CK_KEY_TYPE PK11_GetKeyType(CK_MECHANISM_TYPE type, unsigned long len);
238 CK_MECHANISM_TYPE PK11_GetKeyGen(CK_MECHANISM_TYPE type);
239 int PK11_GetBlockSize(CK_MECHANISM_TYPE type, SECItem *params);
240 int PK11_GetIVLength(CK_MECHANISM_TYPE type);
241 SECItem *PK11_ParamFromIV(CK_MECHANISM_TYPE type, SECItem *iv);
242 unsigned char *PK11_IVFromParam(CK_MECHANISM_TYPE type, SECItem *param, int *len);
243 SECItem *PK11_BlockData(SECItem *data, unsigned long size);
244 
245 /* PKCS #11 to DER mapping functions */
246 SECItem *PK11_ParamFromAlgid(SECAlgorithmID *algid);
247 SECItem *PK11_GenerateNewParam(CK_MECHANISM_TYPE, PK11SymKey *);
248 CK_MECHANISM_TYPE PK11_AlgtagToMechanism(SECOidTag algTag);
249 SECOidTag PK11_MechanismToAlgtag(CK_MECHANISM_TYPE type);
250 SECOidTag PK11_FortezzaMapSig(SECOidTag algTag);
251 SECStatus PK11_ParamToAlgid(SECOidTag algtag, SECItem *param,
252                             PLArenaPool *arena, SECAlgorithmID *algid);
253 SECStatus PK11_SeedRandom(PK11SlotInfo *, unsigned char *data, int len);
254 SECStatus PK11_GenerateRandomOnSlot(PK11SlotInfo *, unsigned char *data, int len);
255 SECStatus PK11_RandomUpdate(void *data, size_t bytes);
256 SECStatus PK11_GenerateRandom(unsigned char *data, int len);
257 
258 /* warning: cannot work with pkcs 5 v2
259  * use algorithm ID s instead of pkcs #11 mechanism pointers */
260 CK_RV PK11_MapPBEMechanismToCryptoMechanism(CK_MECHANISM_PTR pPBEMechanism,
261                                             CK_MECHANISM_PTR pCryptoMechanism,
262                                             SECItem *pbe_pwd, PRBool bad3DES);
263 CK_MECHANISM_TYPE PK11_GetPadMechanism(CK_MECHANISM_TYPE);
264 CK_MECHANISM_TYPE PK11_MapSignKeyType(KeyType keyType);
265 
266 /**********************************************************************
267  *                   Symmetric, Public, and Private Keys
268  **********************************************************************/
269 void PK11_FreeSymKey(PK11SymKey *key);
270 PK11SymKey *PK11_ReferenceSymKey(PK11SymKey *symKey);
271 PK11SymKey *PK11_ImportDataKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, PK11Origin origin,
272                                CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx);
273 PK11SymKey *PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
274                               PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx);
275 PK11SymKey *PK11_ImportSymKeyWithFlags(PK11SlotInfo *slot,
276                                        CK_MECHANISM_TYPE type, PK11Origin origin, CK_ATTRIBUTE_TYPE operation,
277                                        SECItem *key, CK_FLAGS flags, PRBool isPerm, void *wincx);
278 PK11SymKey *PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent,
279                                   PK11Origin origin, CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID,
280                                   PRBool owner, void *wincx);
281 /* PK11_GetWrapKey and PK11_SetWrapKey are not thread safe. */
282 PK11SymKey *PK11_GetWrapKey(PK11SlotInfo *slot, int wrap,
283                             CK_MECHANISM_TYPE type, int series, void *wincx);
284 void PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey);
285 CK_MECHANISM_TYPE PK11_GetMechanism(PK11SymKey *symKey);
286 /*
287  * import a public key into the desired slot
288  *
289  * This function takes a public key structure and creates a public key in a
290  * given slot. If isToken is set, then a persistant public key is created.
291  *
292  * Note: it is possible for this function to return a handle for a key which
293  * is persistant, even if isToken is not set.
294  */
295 CK_OBJECT_HANDLE PK11_ImportPublicKey(PK11SlotInfo *slot,
296                                       SECKEYPublicKey *pubKey, PRBool isToken);
297 PK11SymKey *PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
298                         SECItem *param, int keySize, void *wincx);
299 PK11SymKey *PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
300                              SECItem *param, int keySize, SECItem *keyid,
301                              PRBool isToken, void *wincx);
302 PK11SymKey *PK11_TokenKeyGenWithFlags(PK11SlotInfo *slot,
303                                       CK_MECHANISM_TYPE type, SECItem *param,
304                                       int keySize, SECItem *keyid, CK_FLAGS opFlags,
305                                       PK11AttrFlags attrFlags, void *wincx);
306 /* Generates a key using the exact template supplied by the caller. The other
307  * PK11_[Token]KeyGen mechanisms should be used instead of this one whenever
308  * they work because they include/exclude the CKA_VALUE_LEN template value
309  * based on the mechanism type as required by many tokens.
310  *
311  * keyGenType should be PK11_GetKeyGenWithSize(type, <key size>) or it should
312  * be equal to type if PK11_GetKeyGenWithSize cannot be used (e.g. because
313  * pk11wrap does not know about the mechanisms).
314  */
315 PK11SymKey *PK11_KeyGenWithTemplate(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
316                                     CK_MECHANISM_TYPE keyGenType,
317                                     SECItem *param, CK_ATTRIBUTE *attrs,
318                                     unsigned int attrsCount, void *wincx);
319 PK11SymKey *PK11_ListFixedKeysInSlot(PK11SlotInfo *slot, char *nickname,
320                                      void *wincx);
321 PK11SymKey *PK11_GetNextSymKey(PK11SymKey *symKey);
322 CK_KEY_TYPE PK11_GetSymKeyType(PK11SymKey *key);
323 CK_OBJECT_HANDLE PK11_GetSymKeyHandle(PK11SymKey *symKey);
324 
325 /*
326  * PK11_SetSymKeyUserData
327  *   sets generic user data on keys (usually a pointer to a data structure)
328  * that can later be retrieved by PK11_GetSymKeyUserData().
329  *    symKey - key where data will be set.
330  *    data - data to be set.
331  *    freefunc - function used to free the data.
332  * Setting user data on symKeys with existing user data already set will cause
333  * the existing user data to be freed before the new user data is set.
334  * Freeing user data is done by calling the user specified freefunc.
335  * If freefunc is NULL, the user data is assumed to be global or static an
336  * not freed. Passing NULL for user data to PK11_SetSymKeyUserData has the
337  * effect of freeing any existing user data, and clearing the user data
338  * pointer. If user data exists when the symKey is finally freed, that
339  * data will be freed with freefunc.
340  *
341  * Applications should only use this function on keys which the application
342  * has created directly, as there is only one user data value per key.
343  */
344 void PK11_SetSymKeyUserData(PK11SymKey *symKey, void *data,
345                             PK11FreeDataFunc freefunc);
346 /* PK11_GetSymKeyUserData
347  *   retrieves generic user data which was set on a key by
348  * PK11_SetSymKeyUserData.
349  *    symKey - key with data to be fetched
350  *
351  * If no data exists, or the data has been cleared, PK11_GetSymKeyUserData
352  * will return NULL. Returned data is still owned and managed by the SymKey,
353  * the caller should not free the data.
354  *
355  */
356 void *PK11_GetSymKeyUserData(PK11SymKey *symKey);
357 
358 SECStatus PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
359                              PK11SymKey *symKey, SECItem *wrappedKey);
360 SECStatus PK11_PubWrapSymKeyWithMechanism(SECKEYPublicKey *pubKey,
361                                           CK_MECHANISM_TYPE mechType,
362                                           SECItem *param,
363                                           PK11SymKey *symKey,
364                                           SECItem *wrappedKey);
365 SECStatus PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *params,
366                           PK11SymKey *wrappingKey, PK11SymKey *symKey, SECItem *wrappedKey);
367 /* move a key to 'slot' optionally set the key attributes according to either
368  * operation or the  flags and making the key permanent at the same time.
369  * If the key is moved to the same slot, operation and flags values are
370  * currently ignored */
371 PK11SymKey *PK11_MoveSymKey(PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation,
372                             CK_FLAGS flags, PRBool perm, PK11SymKey *symKey);
373 /*
374  * To do joint operations, we often need two keys in the same slot.
375  * Usually the PKCS #11 wrappers handle this correctly (like for PK11_WrapKey),
376  * but sometimes the wrappers don't know about mechanism specific keys in
377  * the Mechanism params. This function makes sure the two keys are in the
378  * same slot by copying one or both of the keys into a common slot. This
379  * functions makes sure the slot can handle the target mechanism. If the copy
380  * is warranted, this function will prefer to move the movingKey first, then
381  * the preferedKey. If the keys are moved, the new keys are returned in
382  * newMovingKey and/or newPreferedKey. The application is responsible
383  * for freeing those keys one the operation is complete.
384  */
385 SECStatus PK11_SymKeysToSameSlot(CK_MECHANISM_TYPE mech,
386                                  CK_ATTRIBUTE_TYPE preferedOperation,
387                                  CK_ATTRIBUTE_TYPE movingOperation,
388                                  PK11SymKey *preferedKey, PK11SymKey *movingKey,
389                                  PK11SymKey **newPreferedKey,
390                                  PK11SymKey **newMovingKey);
391 
392 /*
393  * derive a new key from the base key.
394  *  PK11_Derive returns a key which can do exactly one operation, and is
395  * ephemeral (session key).
396  *  PK11_DeriveWithFlags is the same as PK11_Derive, except you can use
397  * CKF_ flags to enable more than one operation.
398  *  PK11_DeriveWithFlagsPerm is the same as PK11_DeriveWithFlags except you can
399  *  (optionally) make the key permanent (token key).
400  */
401 PK11SymKey *PK11_Derive(PK11SymKey *baseKey, CK_MECHANISM_TYPE mechanism,
402                         SECItem *param, CK_MECHANISM_TYPE target,
403                         CK_ATTRIBUTE_TYPE operation, int keySize);
404 PK11SymKey *PK11_DeriveWithFlags(PK11SymKey *baseKey,
405                                  CK_MECHANISM_TYPE derive, SECItem *param, CK_MECHANISM_TYPE target,
406                                  CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags);
407 PK11SymKey *PK11_DeriveWithFlagsPerm(PK11SymKey *baseKey,
408                                      CK_MECHANISM_TYPE derive,
409                                      SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
410                                      int keySize, CK_FLAGS flags, PRBool isPerm);
411 PK11SymKey *
412 PK11_DeriveWithTemplate(PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
413                         SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
414                         int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs,
415                         PRBool isPerm);
416 
417 PK11SymKey *PK11_PubDerive(SECKEYPrivateKey *privKey,
418                            SECKEYPublicKey *pubKey, PRBool isSender, SECItem *randomA, SECItem *randomB,
419                            CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
420                            CK_ATTRIBUTE_TYPE operation, int keySize, void *wincx);
421 PK11SymKey *PK11_PubDeriveWithKDF(SECKEYPrivateKey *privKey,
422                                   SECKEYPublicKey *pubKey, PRBool isSender, SECItem *randomA, SECItem *randomB,
423                                   CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
424                                   CK_ATTRIBUTE_TYPE operation, int keySize,
425                                   CK_ULONG kdf, SECItem *sharedData, void *wincx);
426 
427 /*
428  * unwrap a new key with a symetric key.
429  *  PK11_Unwrap returns a key which can do exactly one operation, and is
430  * ephemeral (session key).
431  *  PK11_UnwrapWithFlags is the same as PK11_Unwrap, except you can use
432  * CKF_ flags to enable more than one operation.
433  *  PK11_UnwrapWithFlagsPerm is the same as PK11_UnwrapWithFlags except you can
434  *  (optionally) make the key permanent (token key).
435  */
436 PK11SymKey *PK11_UnwrapSymKey(PK11SymKey *key,
437                               CK_MECHANISM_TYPE wraptype, SECItem *param, SECItem *wrapppedKey,
438                               CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize);
439 PK11SymKey *PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey,
440                                        CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
441                                        CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
442                                        CK_FLAGS flags);
443 PK11SymKey *PK11_UnwrapSymKeyWithFlagsPerm(PK11SymKey *wrappingKey,
444                                            CK_MECHANISM_TYPE wrapType,
445                                            SECItem *param, SECItem *wrappedKey,
446                                            CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
447                                            int keySize, CK_FLAGS flags, PRBool isPerm);
448 
449 /*
450  * unwrap a new key with a private key.
451  *  PK11_PubUnwrap returns a key which can do exactly one operation, and is
452  * ephemeral (session key).
453  *  PK11_PubUnwrapWithFlagsPerm is the same as PK11_PubUnwrap except you can
454  * use * CKF_ flags to enable more than one operation, and optionally make
455  * the key permanent (token key).
456  */
457 PK11SymKey *PK11_PubUnwrapSymKey(SECKEYPrivateKey *key, SECItem *wrapppedKey,
458                                  CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize);
459 PK11SymKey *PK11_PubUnwrapSymKeyWithMechanism(SECKEYPrivateKey *key,
460                                               CK_MECHANISM_TYPE mechType,
461                                               SECItem *param,
462                                               SECItem *wrapppedKey,
463                                               CK_MECHANISM_TYPE target,
464                                               CK_ATTRIBUTE_TYPE operation,
465                                               int keySize);
466 PK11SymKey *PK11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey,
467                                               SECItem *wrappedKey, CK_MECHANISM_TYPE target,
468                                               CK_ATTRIBUTE_TYPE operation, int keySize,
469                                               CK_FLAGS flags, PRBool isPerm);
470 PK11SymKey *PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
471                               SECItem *keyID, void *wincx);
472 SECStatus PK11_DeleteTokenPrivateKey(SECKEYPrivateKey *privKey, PRBool force);
473 SECStatus PK11_DeleteTokenPublicKey(SECKEYPublicKey *pubKey);
474 SECStatus PK11_DeleteTokenSymKey(PK11SymKey *symKey);
475 SECStatus PK11_DeleteTokenCertAndKey(CERTCertificate *cert, void *wincx);
476 SECKEYPrivateKey *PK11_LoadPrivKey(PK11SlotInfo *slot,
477                                    SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
478                                    PRBool token, PRBool sensitive);
479 char *PK11_GetSymKeyNickname(PK11SymKey *symKey);
480 char *PK11_GetPrivateKeyNickname(SECKEYPrivateKey *privKey);
481 char *PK11_GetPublicKeyNickname(SECKEYPublicKey *pubKey);
482 SECStatus PK11_SetSymKeyNickname(PK11SymKey *symKey, const char *nickname);
483 SECStatus PK11_SetPrivateKeyNickname(SECKEYPrivateKey *privKey,
484                                      const char *nickname);
485 SECStatus PK11_SetPublicKeyNickname(SECKEYPublicKey *pubKey,
486                                     const char *nickname);
487 
488 /*
489  * Using __PK11_SetCertificateNickname is *DANGEROUS*.
490  *
491  * The API will update the NSS database, but it *will NOT* update the in-memory data.
492  * As a result, after calling this API, there will be INCONSISTENCY between
493  * in-memory data and the database.
494  *
495  * Use of the API should be limited to short-lived tools, which will exit immediately
496  * after using this API.
497  *
498  * If you ignore this warning, your process is TAINTED and will most likely misbehave.
499  */
500 SECStatus __PK11_SetCertificateNickname(CERTCertificate *cert,
501                                         const char *nickname);
502 
503 /* size to hold key in bytes */
504 unsigned int PK11_GetKeyLength(PK11SymKey *key);
505 /* size of actual secret parts of key in bits */
506 /* algid is because RC4 strength is determined by the effective bits as well
507  * as the key bits */
508 unsigned int PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid);
509 SECStatus PK11_ExtractKeyValue(PK11SymKey *symKey);
510 SECItem *PK11_GetKeyData(PK11SymKey *symKey);
511 PK11SlotInfo *PK11_GetSlotFromKey(PK11SymKey *symKey);
512 void *PK11_GetWindow(PK11SymKey *symKey);
513 
514 /*
515  * Explicitly set the key usage for the generated private key.
516  *
517  * This allows us to specify single use EC and RSA keys whose usage
518  * can be regulated by the underlying token.
519  *
520  * The underlying key usage is set using opFlags. opFlagsMask specifies
521  * which operations are specified by opFlags. For instance to turn encrypt
522  * on and signing off, opFlags would be CKF_ENCRYPT|CKF_DECRYPT and
523  * opFlagsMask would be CKF_ENCRYPT|CKF_DECRYPT|CKF_SIGN|CKF_VERIFY. You
524  * need to specify both the public and private key flags,
525  * PK11_GenerateKeyPairWithOpFlags will sort out the correct flag to the
526  * correct key type. Flags not specified in opFlagMask will be defaulted
527  * according to mechanism type and token capabilities.
528  */
529 SECKEYPrivateKey *PK11_GenerateKeyPairWithOpFlags(PK11SlotInfo *slot,
530                                                   CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
531                                                   PK11AttrFlags attrFlags, CK_FLAGS opFlags, CK_FLAGS opFlagsMask,
532                                                   void *wincx);
533 /*
534  * The attrFlags is the logical OR of the PK11_ATTR_XXX bitflags.
535  * These flags apply to the private key.  The PK11_ATTR_TOKEN,
536  * PK11_ATTR_SESSION, PK11_ATTR_MODIFIABLE, and PK11_ATTR_UNMODIFIABLE
537  * flags also apply to the public key.
538  */
539 SECKEYPrivateKey *PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot,
540                                                 CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
541                                                 PK11AttrFlags attrFlags, void *wincx);
542 SECKEYPrivateKey *PK11_GenerateKeyPair(PK11SlotInfo *slot,
543                                        CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
544                                        PRBool isPerm, PRBool isSensitive, void *wincx);
545 SECKEYPrivateKey *PK11_FindPrivateKeyFromCert(PK11SlotInfo *slot,
546                                               CERTCertificate *cert, void *wincx);
547 SECKEYPrivateKey *PK11_FindKeyByAnyCert(CERTCertificate *cert, void *wincx);
548 SECKEYPrivateKey *PK11_FindKeyByKeyID(PK11SlotInfo *slot, SECItem *keyID,
549                                       void *wincx);
550 int PK11_GetPrivateModulusLen(SECKEYPrivateKey *key);
551 
552 SECStatus PK11_Decrypt(PK11SymKey *symkey,
553                        CK_MECHANISM_TYPE mechanism, SECItem *param,
554                        unsigned char *out, unsigned int *outLen,
555                        unsigned int maxLen,
556                        const unsigned char *enc, unsigned int encLen);
557 SECStatus PK11_Encrypt(PK11SymKey *symKey,
558                        CK_MECHANISM_TYPE mechanism, SECItem *param,
559                        unsigned char *out, unsigned int *outLen,
560                        unsigned int maxLen,
561                        const unsigned char *data, unsigned int dataLen);
562 
563 /* note: despite the name, this function takes a private key. */
564 SECStatus PK11_PubDecryptRaw(SECKEYPrivateKey *key,
565                              unsigned char *data, unsigned *outLen,
566                              unsigned int maxLen,
567                              const unsigned char *enc, unsigned encLen);
568 #define PK11_PrivDecryptRaw PK11_PubDecryptRaw
569 /* The encrypt function that complements the above decrypt function. */
570 SECStatus PK11_PubEncryptRaw(SECKEYPublicKey *key,
571                              unsigned char *enc,
572                              const unsigned char *data, unsigned dataLen,
573                              void *wincx);
574 
575 SECStatus PK11_PrivDecryptPKCS1(SECKEYPrivateKey *key,
576                                 unsigned char *data, unsigned *outLen,
577                                 unsigned int maxLen,
578                                 const unsigned char *enc, unsigned encLen);
579 /* The encrypt function that complements the above decrypt function. */
580 SECStatus PK11_PubEncryptPKCS1(SECKEYPublicKey *key,
581                                unsigned char *enc,
582                                const unsigned char *data, unsigned dataLen,
583                                void *wincx);
584 
585 SECStatus PK11_PrivDecrypt(SECKEYPrivateKey *key,
586                            CK_MECHANISM_TYPE mechanism, SECItem *param,
587                            unsigned char *out, unsigned int *outLen,
588                            unsigned int maxLen,
589                            const unsigned char *enc, unsigned int encLen);
590 SECStatus PK11_PubEncrypt(SECKEYPublicKey *key,
591                           CK_MECHANISM_TYPE mechanism, SECItem *param,
592                           unsigned char *out, unsigned int *outLen,
593                           unsigned int maxLen,
594                           const unsigned char *data, unsigned int dataLen,
595                           void *wincx);
596 
597 SECStatus PK11_ImportPrivateKeyInfo(PK11SlotInfo *slot,
598                                     SECKEYPrivateKeyInfo *pki, SECItem *nickname,
599                                     SECItem *publicValue, PRBool isPerm, PRBool isPrivate,
600                                     unsigned int usage, void *wincx);
601 SECStatus PK11_ImportPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
602                                                 SECKEYPrivateKeyInfo *pki, SECItem *nickname,
603                                                 SECItem *publicValue, PRBool isPerm, PRBool isPrivate,
604                                                 unsigned int usage, SECKEYPrivateKey **privk, void *wincx);
605 SECStatus PK11_ImportDERPrivateKeyInfo(PK11SlotInfo *slot,
606                                        SECItem *derPKI, SECItem *nickname,
607                                        SECItem *publicValue, PRBool isPerm, PRBool isPrivate,
608                                        unsigned int usage, void *wincx);
609 SECStatus PK11_ImportDERPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
610                                                    SECItem *derPKI, SECItem *nickname,
611                                                    SECItem *publicValue, PRBool isPerm, PRBool isPrivate,
612                                                    unsigned int usage, SECKEYPrivateKey **privk, void *wincx);
613 SECStatus PK11_ImportEncryptedPrivateKeyInfo(PK11SlotInfo *slot,
614                                              SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
615                                              SECItem *nickname, SECItem *publicValue, PRBool isPerm,
616                                              PRBool isPrivate, KeyType type,
617                                              unsigned int usage, void *wincx);
618 SECStatus PK11_ImportEncryptedPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot,
619                                                          SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
620                                                          SECItem *nickname, SECItem *publicValue, PRBool isPerm,
621                                                          PRBool isPrivate, KeyType type,
622                                                          unsigned int usage, SECKEYPrivateKey **privk, void *wincx);
623 SECItem *PK11_ExportDERPrivateKeyInfo(SECKEYPrivateKey *pk, void *wincx);
624 SECKEYPrivateKeyInfo *PK11_ExportPrivKeyInfo(
625     SECKEYPrivateKey *pk, void *wincx);
626 SECKEYPrivateKeyInfo *PK11_ExportPrivateKeyInfo(
627     CERTCertificate *cert, void *wincx);
628 SECKEYEncryptedPrivateKeyInfo *PK11_ExportEncryptedPrivKeyInfo(
629     PK11SlotInfo *slot, SECOidTag algTag, SECItem *pwitem,
630     SECKEYPrivateKey *pk, int iteration, void *pwArg);
631 SECKEYEncryptedPrivateKeyInfo *PK11_ExportEncryptedPrivateKeyInfo(
632     PK11SlotInfo *slot, SECOidTag algTag, SECItem *pwitem,
633     CERTCertificate *cert, int iteration, void *pwArg);
634 /* V2 refers to PKCS #5 V2 here. If a PKCS #5 v1 or PKCS #12 pbe is passed
635  * for pbeTag, then encTag and hashTag are ignored. If pbe is an encryption
636  * algorithm, then PKCS #5 V2 is used with prfTag for the prf. If prfTag isn't
637  * supplied prf will be SEC_OID_HMAC_SHA1 */
638 SECKEYEncryptedPrivateKeyInfo *PK11_ExportEncryptedPrivKeyInfoV2(
639     PK11SlotInfo *slot, SECOidTag pbeTag, SECOidTag encTag, SECOidTag prfTag,
640     SECItem *pwitem, SECKEYPrivateKey *pk, int iteration, void *pwArg);
641 SECKEYEncryptedPrivateKeyInfo *PK11_ExportEncryptedPrivateKeyInfoV2(
642     PK11SlotInfo *slot, SECOidTag pbeTag, SECOidTag encTag, SECOidTag prfTag,
643     SECItem *pwitem, CERTCertificate *cert, int iteration, void *pwArg);
644 SECKEYPrivateKey *PK11_FindKeyByDERCert(PK11SlotInfo *slot,
645                                         CERTCertificate *cert, void *wincx);
646 SECKEYPublicKey *PK11_MakeKEAPubKey(unsigned char *data, int length);
647 SECStatus PK11_DigestKey(PK11Context *context, PK11SymKey *key);
648 PRBool PK11_VerifyKeyOK(PK11SymKey *key);
649 SECKEYPrivateKey *PK11_UnwrapPrivKey(PK11SlotInfo *slot,
650                                      PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
651                                      SECItem *param, SECItem *wrappedKey, SECItem *label,
652                                      SECItem *publicValue, PRBool token, PRBool sensitive,
653                                      CK_KEY_TYPE keyType, CK_ATTRIBUTE_TYPE *usage, int usageCount,
654                                      void *wincx);
655 SECStatus PK11_WrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
656                            SECKEYPrivateKey *privKey, CK_MECHANISM_TYPE wrapType,
657                            SECItem *param, SECItem *wrappedKey, void *wincx);
658 /*
659  * The caller of PK11_DEREncodePublicKey should free the returned SECItem with
660  * a SECITEM_FreeItem(..., PR_TRUE) call.
661  */
662 SECItem *PK11_DEREncodePublicKey(const SECKEYPublicKey *pubk);
663 PK11SymKey *PK11_CopySymKeyForSigning(PK11SymKey *originalKey,
664                                       CK_MECHANISM_TYPE mech);
665 SECKEYPrivateKeyList *PK11_ListPrivKeysInSlot(PK11SlotInfo *slot,
666                                               char *nickname, void *wincx);
667 SECKEYPublicKeyList *PK11_ListPublicKeysInSlot(PK11SlotInfo *slot,
668                                                char *nickname);
669 SECKEYPQGParams *PK11_GetPQGParamsFromPrivateKey(SECKEYPrivateKey *privKey);
670 /* deprecated */
671 SECKEYPrivateKeyList *PK11_ListPrivateKeysInSlot(PK11SlotInfo *slot);
672 
673 PK11SymKey *PK11_ConvertSessionSymKeyToTokenSymKey(PK11SymKey *symk,
674                                                    void *wincx);
675 SECKEYPrivateKey *PK11_ConvertSessionPrivKeyToTokenPrivKey(
676     SECKEYPrivateKey *privk, void *wincx);
677 SECKEYPrivateKey *PK11_CopyTokenPrivKeyToSessionPrivKey(PK11SlotInfo *destSlot,
678                                                         SECKEYPrivateKey *privKey);
679 
680 /**********************************************************************
681  *                   Certs
682  **********************************************************************/
683 SECItem *PK11_MakeIDFromPubKey(SECItem *pubKeyData);
684 SECStatus PK11_TraverseSlotCerts(
685     SECStatus (*callback)(CERTCertificate *, SECItem *, void *),
686     void *arg, void *wincx);
687 CERTCertificate *PK11_FindCertFromNickname(const char *nickname, void *wincx);
688 CERTCertificate *PK11_FindCertFromURI(const char *uri, void *wincx);
689 CERTCertList *PK11_FindCertsFromURI(const char *uri, void *wincx);
690 CERTCertList *PK11_FindCertsFromEmailAddress(const char *email, void *wincx);
691 CERTCertList *PK11_FindCertsFromNickname(const char *nickname, void *wincx);
692 CERTCertificate *PK11_GetCertFromPrivateKey(SECKEYPrivateKey *privKey);
693 SECStatus PK11_ImportCert(PK11SlotInfo *slot, CERTCertificate *cert,
694                           CK_OBJECT_HANDLE key, const char *nickname,
695                           PRBool includeTrust);
696 SECStatus PK11_ImportDERCert(PK11SlotInfo *slot, SECItem *derCert,
697                              CK_OBJECT_HANDLE key, char *nickname, PRBool includeTrust);
698 PK11SlotInfo *PK11_ImportCertForKey(CERTCertificate *cert,
699                                     const char *nickname, void *wincx);
700 PK11SlotInfo *PK11_ImportDERCertForKey(SECItem *derCert, char *nickname,
701                                        void *wincx);
702 PK11SlotInfo *PK11_KeyForCertExists(CERTCertificate *cert,
703                                     CK_OBJECT_HANDLE *keyPtr, void *wincx);
704 PK11SlotInfo *PK11_KeyForDERCertExists(SECItem *derCert,
705                                        CK_OBJECT_HANDLE *keyPtr, void *wincx);
706 CERTCertificate *PK11_FindCertByIssuerAndSN(PK11SlotInfo **slot,
707                                             CERTIssuerAndSN *sn, void *wincx);
708 CERTCertificate *PK11_FindCertAndKeyByRecipientList(PK11SlotInfo **slot,
709                                                     SEC_PKCS7RecipientInfo **array, SEC_PKCS7RecipientInfo **rip,
710                                                     SECKEYPrivateKey **privKey, void *wincx);
711 int PK11_FindCertAndKeyByRecipientListNew(NSSCMSRecipient **recipientlist,
712                                           void *wincx);
713 SECStatus PK11_TraverseCertsForSubjectInSlot(CERTCertificate *cert,
714                                              PK11SlotInfo *slot, SECStatus (*callback)(CERTCertificate *, void *),
715                                              void *arg);
716 CERTCertificate *PK11_FindCertFromDERCert(PK11SlotInfo *slot,
717                                           CERTCertificate *cert, void *wincx);
718 CERTCertificate *PK11_FindCertFromDERCertItem(PK11SlotInfo *slot,
719                                               const SECItem *derCert, void *wincx);
720 SECStatus PK11_ImportCertForKeyToSlot(PK11SlotInfo *slot, CERTCertificate *cert,
721                                       char *nickname, PRBool addUsage,
722                                       void *wincx);
723 CERTCertificate *PK11_FindBestKEAMatch(CERTCertificate *serverCert, void *wincx);
724 PRBool PK11_FortezzaHasKEA(CERTCertificate *cert);
725 CK_OBJECT_HANDLE PK11_FindEncodedCertInSlot(PK11SlotInfo *slot, SECItem *derCert, void *wincx);
726 CK_OBJECT_HANDLE PK11_FindCertInSlot(PK11SlotInfo *slot, CERTCertificate *cert,
727                                      void *wincx);
728 SECStatus PK11_TraverseCertsForNicknameInSlot(SECItem *nickname,
729                                               PK11SlotInfo *slot, SECStatus (*callback)(CERTCertificate *, void *),
730                                               void *arg);
731 CERTCertList *PK11_ListCerts(PK11CertListType type, void *pwarg);
732 CERTCertList *PK11_ListCertsInSlot(PK11SlotInfo *slot);
733 CERTSignedCrl *PK11_ImportCRL(PK11SlotInfo *slot, SECItem *derCRL, char *url,
734                               int type, void *wincx, PRInt32 importOptions, PLArenaPool *arena, PRInt32 decodeOptions);
735 CK_BBOOL PK11_HasAttributeSet(PK11SlotInfo *slot,
736                               CK_OBJECT_HANDLE id,
737                               CK_ATTRIBUTE_TYPE type,
738                               PRBool haslock /* must be set to PR_FALSE */);
739 
740 /**********************************************************************
741  *                   Hybrid Public Key Encryption
742  **********************************************************************/
743 
744 /* Some of the various HPKE arguments would ideally be const, but the
745  * underlying PK11 functions take them as non-const. To avoid lying to
746  * the application with a cast, this idiosyncrasy is exposed. */
747 SECStatus PK11_HPKE_ValidateParameters(HpkeKemId kemId, HpkeKdfId kdfId, HpkeAeadId aeadId);
748 HpkeContext *PK11_HPKE_NewContext(HpkeKemId kemId, HpkeKdfId kdfId, HpkeAeadId aeadId,
749                                   PK11SymKey *psk, const SECItem *pskId);
750 SECStatus PK11_HPKE_Deserialize(const HpkeContext *cx, const PRUint8 *enc,
751                                 unsigned int encLen, SECKEYPublicKey **outPubKey);
752 void PK11_HPKE_DestroyContext(HpkeContext *cx, PRBool freeit);
753 
754 /* Serialize an initialized receiver context. This only retains the keys and
755  * associated information necessary to resume Export and Open operations after
756  * import. Serialization is currently supported for receiver contexts only.
757  * This is done for two reasons: 1) it avoids having to move the encryption
758  * sequence number outside of the token (or adding encryption context
759  * serialization support to softoken), and 2) we don't have to worry about IV
760  * reuse due to sequence number cloning.
761  *
762  * |wrapKey| is required when exporting in FIPS mode. If exported with a
763  * wrapping key, that same key must be provided to the import function,
764  * otherwise behavior is undefined.
765  *
766  * Even when exported with key wrap, HPKE expects the nonce to also be kept
767  * secret and that value is not protected by wrapKey. Applications are
768  * responsible for maintaining the confidentiality of the exported information.
769  */
770 SECStatus PK11_HPKE_ExportContext(const HpkeContext *cx, PK11SymKey *wrapKey, SECItem **serialized);
771 SECStatus PK11_HPKE_ExportSecret(const HpkeContext *cx, const SECItem *info, unsigned int L,
772                                  PK11SymKey **outKey);
773 const SECItem *PK11_HPKE_GetEncapPubKey(const HpkeContext *cx);
774 HpkeContext *PK11_HPKE_ImportContext(const SECItem *serialized, PK11SymKey *wrapKey);
775 SECStatus PK11_HPKE_Open(HpkeContext *cx, const SECItem *aad, const SECItem *ct, SECItem **outPt);
776 SECStatus PK11_HPKE_Seal(HpkeContext *cx, const SECItem *aad, const SECItem *pt, SECItem **outCt);
777 SECStatus PK11_HPKE_Serialize(const SECKEYPublicKey *pk, PRUint8 *buf, unsigned int *len, unsigned int maxLen);
778 SECStatus PK11_HPKE_SetupS(HpkeContext *cx, const SECKEYPublicKey *pkE, SECKEYPrivateKey *skE,
779                            SECKEYPublicKey *pkR, const SECItem *info);
780 SECStatus PK11_HPKE_SetupR(HpkeContext *cx, const SECKEYPublicKey *pkR, SECKEYPrivateKey *skR,
781                            const SECItem *enc, const SECItem *info);
782 
783 /**********************************************************************
784  *                   Sign/Verify
785  **********************************************************************/
786 
787 /*
788  * Return the length in bytes of a signature generated with the
789  * private key.
790  *
791  * Return 0 or -1 on failure.  (XXX Should we fix it to always return
792  * -1 on failure?)
793  */
794 int PK11_SignatureLen(SECKEYPrivateKey *key);
795 PK11SlotInfo *PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key);
796 SECStatus PK11_Sign(SECKEYPrivateKey *key, SECItem *sig,
797                     const SECItem *hash);
798 SECStatus PK11_SignWithMechanism(SECKEYPrivateKey *key,
799                                  CK_MECHANISM_TYPE mechanism,
800                                  const SECItem *param, SECItem *sig,
801                                  const SECItem *hash);
802 SECStatus PK11_SignWithSymKey(PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism,
803                               SECItem *param, SECItem *sig, const SECItem *data);
804 SECStatus PK11_VerifyRecover(SECKEYPublicKey *key, const SECItem *sig,
805                              SECItem *dsig, void *wincx);
806 SECStatus PK11_Verify(SECKEYPublicKey *key, const SECItem *sig,
807                       const SECItem *hash, void *wincx);
808 SECStatus PK11_VerifyWithMechanism(SECKEYPublicKey *key,
809                                    CK_MECHANISM_TYPE mechanism,
810                                    const SECItem *param, const SECItem *sig,
811                                    const SECItem *hash, void *wincx);
812 
813 /**********************************************************************
814  *                   Crypto Contexts
815  **********************************************************************/
816 void PK11_DestroyContext(PK11Context *context, PRBool freeit);
817 PK11Context *PK11_CreateContextBySymKey(CK_MECHANISM_TYPE type,
818                                         CK_ATTRIBUTE_TYPE operation,
819                                         PK11SymKey *symKey,
820                                         const SECItem *param);
821 PK11Context *PK11_CreateContextByPubKey(CK_MECHANISM_TYPE type,
822                                         CK_ATTRIBUTE_TYPE operation,
823                                         SECKEYPublicKey *pubKey,
824                                         const SECItem *param, void *pwArg);
825 PK11Context *PK11_CreateContextByPrivKey(CK_MECHANISM_TYPE type,
826                                          CK_ATTRIBUTE_TYPE operation,
827                                          SECKEYPrivateKey *privKey,
828                                          const SECItem *param);
829 PK11Context *PK11_CreateDigestContext(SECOidTag hashAlg);
830 PK11Context *PK11_CloneContext(PK11Context *old);
831 SECStatus PK11_DigestBegin(PK11Context *cx);
832 /*
833  * The output buffer 'out' must be big enough to hold the output of
834  * the hash algorithm 'hashAlg'.
835  */
836 SECStatus PK11_HashBuf(SECOidTag hashAlg, unsigned char *out,
837                        const unsigned char *in, PRInt32 len);
838 SECStatus PK11_DigestOp(PK11Context *context, const unsigned char *in,
839                         unsigned len);
840 SECStatus PK11_CipherOp(PK11Context *context, unsigned char *out, int *outlen,
841                         int maxout, const unsigned char *in, int inlen);
842 /* application builds the mechanism specific params */
843 SECStatus PK11_AEADRawOp(PK11Context *context, void *params, int paramslen,
844                          const unsigned char *aad, int aadlen,
845                          unsigned char *out, int *outlen,
846                          int maxout, const unsigned char *in, int inlen);
847 /* NSS builds the mechanism specific params */
848 SECStatus PK11_AEADOp(PK11Context *context, CK_GENERATOR_FUNCTION ivGen,
849                       int fixedbits, unsigned char *iv, int ivlen,
850                       const unsigned char *aad, int aadlen,
851                       unsigned char *out, int *outlen,
852                       int maxout, unsigned char *tag, int taglen,
853                       const unsigned char *in, int inlen);
854 
855 SECStatus PK11_Finalize(PK11Context *context);
856 SECStatus PK11_DigestFinal(PK11Context *context, unsigned char *data,
857                            unsigned int *outLen, unsigned int length);
858 #define PK11_CipherFinal PK11_DigestFinal
859 SECStatus PK11_SaveContext(PK11Context *cx, unsigned char *save,
860                            int *len, int saveLength);
861 
862 /* Save the context's state, with possible allocation.
863  * The caller may supply an already allocated buffer in preAllocBuf,
864  * with length pabLen.  If the buffer is large enough for the context's
865  * state, it will receive the state.
866  * If the buffer is not large enough (or NULL), then a new buffer will
867  * be allocated with PORT_Alloc.
868  * In either case, the state will be returned as a buffer, and the length
869  * of the state will be given in *stateLen.
870  */
871 unsigned char *
872 PK11_SaveContextAlloc(PK11Context *cx,
873                       unsigned char *preAllocBuf, unsigned int pabLen,
874                       unsigned int *stateLen);
875 
876 SECStatus PK11_RestoreContext(PK11Context *cx, unsigned char *save, int len);
877 SECStatus PK11_GenerateFortezzaIV(PK11SymKey *symKey, unsigned char *iv, int len);
878 void PK11_SetFortezzaHack(PK11SymKey *symKey);
879 
880 /**********************************************************************
881  *                   PBE functions
882  **********************************************************************/
883 
884 /* This function creates PBE parameters from the given inputs.  The result
885  * can be used to create a password integrity key for PKCS#12, by sending
886  * the return value to PK11_KeyGen along with the appropriate mechanism.
887  */
888 SECItem *
889 PK11_CreatePBEParams(SECItem *salt, SECItem *pwd, unsigned int iterations);
890 
891 /* free params created above (can be called after keygen is done */
892 void PK11_DestroyPBEParams(SECItem *params);
893 
894 SECAlgorithmID *
895 PK11_CreatePBEAlgorithmID(SECOidTag algorithm, int iteration, SECItem *salt);
896 
897 /* use to create PKCS5 V2 algorithms with finder control than that provided
898  * by PK11_CreatePBEAlgorithmID. */
899 SECAlgorithmID *
900 PK11_CreatePBEV2AlgorithmID(SECOidTag pbeAlgTag, SECOidTag cipherAlgTag,
901                             SECOidTag prfAlgTag, int keyLength, int iteration,
902                             SECItem *salt);
903 PK11SymKey *
904 PK11_PBEKeyGen(PK11SlotInfo *slot, SECAlgorithmID *algid, SECItem *pwitem,
905                PRBool faulty3DES, void *wincx);
906 
907 /* warning: cannot work with PKCS 5 v2 use PK11_PBEKeyGen instead */
908 PK11SymKey *
909 PK11_RawPBEKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *params,
910                   SECItem *pwitem, PRBool faulty3DES, void *wincx);
911 SECItem *
912 PK11_GetPBEIV(SECAlgorithmID *algid, SECItem *pwitem);
913 /*
914  * Get the Mechanism and parameter of the base encryption or mac scheme from
915  * a PBE algorithm ID.
916  *  Caller is responsible for freeing the return parameter (param).
917  */
918 CK_MECHANISM_TYPE
919 PK11_GetPBECryptoMechanism(SECAlgorithmID *algid,
920                            SECItem **param, SECItem *pwd);
921 
922 /**********************************************************************
923  * Functions to manage secmod flags
924  **********************************************************************/
925 const PK11DefaultArrayEntry *PK11_GetDefaultArray(int *size);
926 SECStatus PK11_UpdateSlotAttribute(PK11SlotInfo *slot,
927                                    const PK11DefaultArrayEntry *entry,
928                                    PRBool add);
929 
930 /**********************************************************************
931  * Functions to look at PKCS #11 dependent data
932  **********************************************************************/
933 PK11GenericObject *PK11_FindGenericObjects(PK11SlotInfo *slot,
934                                            CK_OBJECT_CLASS objClass);
935 PK11GenericObject *PK11_GetNextGenericObject(PK11GenericObject *object);
936 PK11GenericObject *PK11_GetPrevGenericObject(PK11GenericObject *object);
937 SECStatus PK11_UnlinkGenericObject(PK11GenericObject *object);
938 SECStatus PK11_LinkGenericObject(PK11GenericObject *list,
939                                  PK11GenericObject *object);
940 SECStatus PK11_DestroyGenericObjects(PK11GenericObject *object);
941 SECStatus PK11_DestroyGenericObject(PK11GenericObject *object);
942 PK11GenericObject *PK11_CreateManagedGenericObject(PK11SlotInfo *slot,
943                                                    const CK_ATTRIBUTE *pTemplate,
944                                                    int count, PRBool token);
945 /* deprecated */
946 PK11GenericObject *PK11_CreateGenericObject(PK11SlotInfo *slot,
947                                             const CK_ATTRIBUTE *pTemplate,
948                                             int count, PRBool token);
949 
950 /*
951  * PK11_ReadRawAttribute and PK11_WriteRawAttribute are generic
952  * functions to read and modify the actual PKCS #11 attributes of
953  * the underlying pkcs #11 object.
954  *
955  * object is a pointer to an NSS object that represents the underlying
956  *  PKCS #11 object. It's type must match the type of PK11ObjectType
957  *  as follows:
958  *
959  *     type                           object
960  *   PK11_TypeGeneric            PK11GenericObject *
961  *   PK11_TypePrivKey            SECKEYPrivateKey *
962  *   PK11_TypePubKey             SECKEYPublicKey *
963  *   PK11_TypeSymKey             PK11SymKey *
964  *
965  *  All other types are considered invalid. If type does not match the object
966  *  passed, unpredictable results will occur.
967  *
968  * PK11_ReadRawAttribute allocates the buffer for returning the attribute
969  * value.  The caller of PK11_ReadRawAttribute should free the data buffer
970  * pointed to by item using a SECITEM_FreeItem(item, PR_FALSE) or
971  * PORT_Free(item->data) call.
972  */
973 SECStatus PK11_ReadRawAttribute(PK11ObjectType type, void *object,
974                                 CK_ATTRIBUTE_TYPE attr, SECItem *item);
975 SECStatus PK11_ReadRawAttributes(PLArenaPool *arena, PK11ObjectType type, void *object,
976                                  CK_ATTRIBUTE *pTemplate, unsigned int count);
977 SECStatus PK11_WriteRawAttribute(PK11ObjectType type, void *object,
978                                  CK_ATTRIBUTE_TYPE attr, SECItem *item);
979 /* get the PKCS #11 handle and slot for a generic object */
980 CK_OBJECT_HANDLE PK11_GetObjectHandle(PK11ObjectType objType, void *objSpec,
981                                       PK11SlotInfo **slotp);
982 
983 /*
984  * PK11_GetAllSlotsForCert returns all the slots that a given certificate
985  * exists on, since it's possible for a cert to exist on more than one
986  * PKCS#11 token.
987  */
988 PK11SlotList *
989 PK11_GetAllSlotsForCert(CERTCertificate *cert, void *arg);
990 
991 /*
992  * Finds all certificates on the given slot with the given subject distinguished
993  * name and returns them as DER bytes. If no such certificates can be found,
994  * returns SECSuccess and sets *results to NULL. If a failure is encountered
995  * while fetching any of the matching certificates, SECFailure is returned and
996  * *results will be NULL.
997  */
998 SECStatus
999 PK11_FindRawCertsWithSubject(PK11SlotInfo *slot, SECItem *derSubject,
1000                              CERTCertificateList **results);
1001 
1002 /*
1003  * Finds and returns all certificates with a public key that matches the given
1004  * private key. May return an empty list if no certificates match. Returns NULL
1005  * if a failure is encountered.
1006  */
1007 CERTCertList *
1008 PK11_GetCertsMatchingPrivateKey(SECKEYPrivateKey *privKey);
1009 
1010 /**********************************************************************
1011  * New functions which are already deprecated....
1012  **********************************************************************/
1013 SECItem *
1014 PK11_GetLowLevelKeyIDForCert(PK11SlotInfo *slot,
1015                              CERTCertificate *cert, void *pwarg);
1016 SECItem *
1017 PK11_GetLowLevelKeyIDForPrivateKey(SECKEYPrivateKey *key);
1018 
1019 PRBool SECMOD_HasRootCerts(void);
1020 
1021 /**********************************************************************
1022  * Other Utilities
1023  **********************************************************************/
1024 /*
1025  * Get the state of the system FIPS mode -
1026  *  NSS uses this to force FIPS mode if the system bit is on. This returns
1027  *  the system state independent of the database state and can be called
1028  *  before NSS initializes.
1029  */
1030 int SECMOD_GetSystemFIPSEnabled(void);
1031 
1032 /* FIPS indicator functions. Some operations are physically allowed, but
1033  * are against the NSS FIPS security policy. This is because sometimes NSS
1034  * functions are used in non-security contexts. You can call these functions
1035  * to determine if you are operating inside or outside the the current vendor's
1036  * FIPS Security Policy for NSS. NOTE: if the current version of NSS is not
1037  * actually FIPS certified, then these functions will always return PR_FALSE */
1038 
1039 /* This function tells if if the last single shot operation on the slot
1040  * was inside or outside the FIPS security policy */
1041 PRBool PK11_SlotGetLastFIPSStatus(PK11SlotInfo *slot);
1042 /* This tells you if the current operation is within the FIPS security policy. If
1043  * you have called finalize on the context, it tells you if the last operation
1044  * was within the FIPS security policy */
1045 PRBool PK11_ContextGetFIPSStatus(PK11Context *context);
1046 /* This tells you if the requested object was created in accordance to the
1047  * NSS FIPS security policy. */
1048 PRBool PK11_ObjectGetFIPSStatus(PK11ObjectType objType, void *objSpec);
1049 
1050 SEC_END_PROTOS
1051 
1052 #endif
1053