Skip to content

Bug 1057463. Fix build error. r=me#11

Closed
ekr wants to merge 1 commit intonss-dev:masterfrom
ekr:build_fix
Closed

Bug 1057463. Fix build error. r=me#11
ekr wants to merge 1 commit intonss-dev:masterfrom
ekr:build_fix

Conversation

@ekr
Copy link
Copy Markdown
Contributor

@ekr ekr commented Feb 2, 2016

No description provided.

moz-v2v-gh pushed a commit that referenced this pull request May 2, 2016
moz-v2v-gh pushed a commit that referenced this pull request Mar 8, 2018
Summary:

Previously, NSS dropped PKCS #8 PrivateKeyInfo when importing a
private key from a PKCS #12 file.  This patch attaches the
corresponding CKA_PUBLIC_KEY_INFO attribute to a private key when
unwrapping it (see PKCS #11 v2.40 4.9).  When wrapping it again, the
attribute is restored in the encrypted PrivateKeyInfo.

Reviewers: rrelyea

Reviewed By: rrelyea

Bug #: 1413596

Differential Revision: https://phabricator.services.mozilla.com/D198
moz-v2v-gh pushed a commit that referenced this pull request Jul 23, 2018
Summary: This patch allows client applications to specify tokens unambiguously with PKCS #11 URI, instead of token name.  It also includes a minor fixes to PKCS #11 URI handling that previously treated the scheme case sensitively.

Reviewers: kaie, rrelyea

Bug #: 1475274

Differential Revision: https://phabricator.services.mozilla.com/D2099

--HG--
extra : amend_source : 2c523bef26f62206b178c9ba04833c85cf5492cb
moz-v2v-gh pushed a commit that referenced this pull request Jun 6, 2019
gtests/pk11_gtest/pk11_import_unittest.cc

Pick up the gtest changes from patch https://phabricator.services.mozilla.com/D33262#change-GhQvkCURcwqg
Update the gtest to accept dsa and dh keys as well.

lib/cryptohi/seckey.c
When converting private keys to public keys, if we can't find a cert, look for a public key. If none found use the CKM_NSS_PUB_FROM_PRIV derive mechanism to create one.

lib/pk11wrap/pk11priv.h
lib/pk11wrap/pk11skey.c
Implement an internal function that can be used to derive a public key from a private key. Give appropriate warnings about what has to happen to make this public.

lib/softoken/lowkey.c
Add code to the low level derive public from private to actually calculate public componants that aren't stored in the private key.

lib/softoken/pkcs11i.h
lib/softoken/pkcs11.c
Add helper function to populate a PKCS #11 object from a NSSLOWKEYPublicKey.

lib/util/pkcs11n.h
lib/softoken/pkcs11c.c
Implement CKM_NSS_PUB_FROM_PRIV.

Differential Revision: https://phabricator.services.mozilla.com/D33682

--HG--
branch : NSS_3_44_BRANCH
moz-v2v-gh pushed a commit that referenced this pull request Jun 6, 2019
Differential Revision: https://phabricator.services.mozilla.com/D28519

Patch notes:

cmd/fipstest:

  Update fipstest to allow using old CAVS vectors in our all.sh. The various scripts have been moved to tests/fips/cavs_scripts. IKE functions were added to fipstest, and fipstest was updated to support verifying the output of ecdh and dh key agreement tests (kas).
fipstest.c:
  NOTE: fipstest is the program NSS uses to process CAVS vectors from NIST. For historical reasons, it has known memory management issues. In general if there is a mistake, fipstest will likely crash. It has very little error checking. It has a very simplistic parser for the CAVS files. It requires the elements of the CAVS files to be in the correct order (most notably it requires the last element to always be in the last position. This is true of all the tests in fipstest, not just the new code.
  1. when verifying ec_dh and dh, accept both CAVSHashZZ and HashZZ as the input hash. This allows verify not only to verify NIST CAVS vectors, but also the output of ec_dh and dh functional tests.
  2. create ike functions modelled after the tls test functions. We test ike at the pkcs #11 level. There are three ike tests (driven by the three types of ike tests that NIST supplies):
      2.1) ikev1. This generates the ike v1 keys from the provided input. It used ike_prf to generate SKEYID and ikev1_prf to generate SKEYID_d, SKEYID_a, and SKEYID_e.
      2.2) ikev1_psk. This generates ike v1 keys from the provided input. It uses a pre-shared-secret-key. It also

used ike_prf to generate SKEYID (though it uses it with bDataAsKey=false), and ikev1_prf to generate SKEYID_d, SKEYID_a, and SKEYID_e.

    2.3) ikev2. This generates ike v2 keys from the provided input. It uses ike_prf to generate SKEYSEED and ike_prf_plus to generate the key material. It also does a rekey using ike_prf and bRekey = true.
3. Add parameters so the tls can be called.

lib/softoken

  This is the main location where the new functionality is provided.
fipstest.c
  Add the power up self test for ike. The actual test lives in sftkike.c.
manifest.mn
  Add sftkike.c to the build.
pkcs11.c
  Add AES XCBC MAC and IKE Mechanisms to the softoken mechanism table.
pkcs11c.c
  sftk_MapCryptError() is now a 'global' within softoken and lives in pkcs11u.c. This was done so that sftkike.c can use it.
  sftk_InitCBCMac(). Update to handle AES XCBC., which is AES CBC MAC except 1) the underlying AES key is derived from the input key, and 2) the pad block is obscured using 2 new keys (k2, k3) also derived from the input key.
  sftk_MACFinal() handle the special pad processing for the XCBC case.
  sftk_MACUpdate() change the padding code to keep one full pad in the buffer. This won't affect normal MACs, but means that the last block in the Mac is always in the buffer so it can be processed in the XCBC case.
  NSC_DerviceKey() add the ike functions into the mechanism swtich table. The actual implementations are in sftkike.c
pkcs11i.h
   Add the XCBC state information into the SessionContext structure.
   sftk_MapCryptError is now global, include it in the header.
   include the ike and aes_xcbc helper functions.
pkcs11u.c
   sftk_MapCryptError() now lives in pkcs11 utilities.
sftkike.c
   prf_* functions implement all the underlying prf specific stuff. It hides whether the prf is an hmac or aes_xcbc. If there are additional prfs, they can be implemented here without affecting the rest of the derivation code. The AES_XCBC code is aes specific. If we ever add another XCBC type operation, we would probably want to initialize some encryption functions in prf_setup and only handle the difference between hmac and xcbc in the other prf functions.
   sftk_aes_xcbc_get_keys - takes in input key and derives k1, k2, and k3. This function handles this derivation for both the prf_ functions in sftkike and the exported AES_XCBC Mac in pkcs11c.c
   sftk_xcbc_mac_pad - function to handle the correct padding method for the last block of an xcbc operation. Unlike sftk_aes_xcbc_get_keys, it is independent of the xcbc's underlying encryption method, though only AES_XCBC is defined at this time.
   sftk_ike_prf - common prf between ikev1 and ikev2 to generate SKEYID/SKEYSEED. See comments in code.
   sftk_ike1_prf - ikev1 prf to generate the session keys in ikev1 from SKEYID. See comments in code.
   sftk_ike_prf_plus - ike prf+ to generate the session keys in ikev2 from SKEYSEED. See comments in code.
   sftk_aes_xcbc_new_keys - used in pkcs11c.c to generate the 2 derived keys used in aes_xcbc. Loads k1 into the pkcs11 slot as a session key.
   prf_test - helper function to test our known test vectors for our FIPS powerup self tests.
   sftk_fips_IKE_PowerUpSelfTests - test to make sure our basic system is working correctly.
softokn.gyp - add sftkike.c to gyp

lib/util

pkcs11n.h
   add defines and structures for IKE. Since they are not yet an official PKCS #11 mechanism, use CKM_NSS and CK_NSS names for them.
pkcs11t.h
   add CKM_AES_XCBC* mechanisms. These are defined in the latest PKCS #11 spec.

tests/fips

The work in this directory hooks up the CAVS tests we run to do fips validation into our normal test suite. This lets us use the NIST generated samples for
cavs_samples/* These are all vectors generated by the NIST CAVS tools (*.req) or the expected results generated by the last openssl or NSS runs and verified by the NIST CAVS tools (*.fax). These are the inputs to our fipstest. No need to detail review these. The are not explicitly included in this patch because they are too big for phabricator to handle.
cavs_scripts/* See the read me in that directory. These scripts were originally in cmd/fipstest. I added ike.sh, and I updated the verify target of all the scripts so they they return 0 on success and 1 on failure. This allows us to use the tests in fips.sh
fips.sh run the CAVS tests as part of the fips tests. This works to test our IKE support. Three of the cavs tests can take significant type (dsa and rsa takes several minutes, tdea is just over a minute). The code currently skips running those tests. You can run all the cavs tests by setting CAV_VECTORS=all

--HG--
branch : NSS_3_44_BRANCH
cipherboy added a commit to cipherboy/nss that referenced this pull request Jul 30, 2019
Signed-off-by: Alexander Scheel <ascheel@redhat.com>
cipherboy added a commit to cipherboy/nss that referenced this pull request Jul 31, 2019
Signed-off-by: Alexander Scheel <ascheel@redhat.com>
cipherboy added a commit to cipherboy/nss that referenced this pull request Jul 31, 2019
Signed-off-by: Alexander Scheel <ascheel@redhat.com>
moz-v2v-gh pushed a commit that referenced this pull request Sep 5, 2019
Differential Revision: https://phabricator.services.mozilla.com/D40121

--HG--
extra : source : 20c543ab422e06d610bb316690a01a77b2668a66
moz-v2v-gh pushed a commit that referenced this pull request Nov 5, 2019
Summary:
This adds a mock PKCS #11 module from Firefox and add basic tests around it.
This is needed for proper testing of PKCS #11 v3.0 profile objects (D45669).

Reviewers: rrelyea

Reviewed By: rrelyea

Subscribers: reviewbot

Bug #: 1577803

Differential Revision: https://phabricator.services.mozilla.com/D47060

--HG--
extra : amend_source : a3e817577f697a06f0dd2deee18cf31ea1bf70ea
moz-v2v-gh pushed a commit that referenced this pull request Nov 6, 2019
…IC_CERTIFICATES_TOKEN, r=rrelyea

Summary: This makes NSS look for CKO_PROFILE object at token initialization time to check if it implements the [[ https://docs.oasis-open.org/pkcs11/pkcs11-profiles/v3.0/pkcs11-profiles-v3.0.pdf | Public Certificates Token profile ]] as defined in PKCS #11 v3.0.  If it is found, the token is automatically marked as friendly so no authentication attempts will be made when accessing certificates.

Reviewers: rrelyea

Reviewed By: rrelyea

Subscribers: reviewbot

Bug #: 1577803

Differential Revision: https://phabricator.services.mozilla.com/D45669

--HG--
extra : amend_source : 58fe6ec6aaa684b0af41843b1a46669537171f0e
moz-v2v-gh pushed a commit that referenced this pull request Mar 17, 2020
https://phabricator.services.mozilla.com/D63241

This patch implements the first phase: updating the headers.

lib/util/pkcs11.h
lib/util/pkcs11f.h
lib/util/pkcs11t.h

Were updated using the released OASIS PKCS #11 v3.0 header files.
lib/util/pkcs11n.h was updated to finally deprecate all uses of CK?_NETSCAPE_?.

A new define as added: NSS_PKCS11_2_0_COMPAT. If it's defined, the small
semantic changes (including the removal of deprecated defines) between the
NSS PKCS #11 v2 header file and the new PKCS #11 v3 are reverted in favor of
the PKCS #11 v2 definitions. This include the removal of CK?_NETSCAPE_? in
favor of CK?_NSS_?.

One notable change was caused by an inconsistancy between the spec and the
released headers in PKCS #11 v2.40. CK_GCM_PARAMS had an extra field in
the header that was not in the spec. OASIS considers the header file to be
normative, so PKCS #11 v3.0 resolved the issue in favor of the header file
definition. NSS had the spec definition, so now there are 2 defines for this
structure:

CK_NSS_GCM_PARAMS - the old nss define. Still used internally in freebl.
CK_GCM_PARAMS_V3 - the new define.
CK_GCM_PARAMS - no longer referenced in NSS itself. It's defined as
CK_GCM_PARAMS_V3 if NSS_PKCS11_2_0_COMPAT is *not* defined, and it's defined as
CKM_NSS_GCM_PARAMS if NSS_PKCS11_2_0_COMPAT is defined.

Softoken has been updated to accept either CK_NSS_GCM_PARAMS or
CK_GCM_PARAMS_V3. In a future patch NSS will be updated to use
CK_GCM_PARAMS_V3 and fall back to CK_NSS_GMC_PARAMS.

One other semantic difference between the 3.0 version of pkcs11f.h and the
version here: In the oasis version of the header, you must define
CK_PKCS11_2_0_ONLY to get just the PKCS #11 v2 defines. In our version you
must define CK_PKCS11_3 to get the PCKS #11 v3 defines.

Most of this patch is to handle changing the deprecated defines that have been
removed in PCKS #11 v3 from NSS.

Differential Revision: https://phabricator.services.mozilla.com/D63241
moz-v2v-gh pushed a commit that referenced this pull request Mar 18, 2020
Update to PKCS #11 v3.0 part 2.

Create the functions and switch to the C_Interface() function to fetch the PKCS #11 function table. Also PKCS #11 v3.0 uses a new fork safe interface. NSS can already handle the case if the PKCS #11 module happens to be fork safe (when asked by the application to refresh the tokens in the child process, NSS can detect that such a refresh is not necessary and continue. Softoken could also be put in fork_safe mode with an environment variable. With this patch it's the default, and NSS asks for the fork safe API by default. Technically softoken should implement the old non-fork safe interface when PKCS #11 v2.0 is called, but NSS no longer needs it, and doing so would double the number of PKCS #11 interfaces are needed. You can still compile with fork unsafe semantics, and the PKCS #11 V3.0 module will do the right thing and not include the fork safe flag. Firefox does not fork(), so for firefox this is simply code that is no longer compilied.

We now use C_GetInterface, which allows us to specify what kind of interface we want (PKCS #11 v3.0, PKCS #11 v2.0, fork safe, etc.). Vendor specific functions can now be accessed through the C_GetInterface. If the C_GetInterface function does not exists, we fall bak to the old C_GetFunctionList.

There are 24 new functions in PKCS #11 v3.0:
C_GetInterfaceList - return a table of all the supported interfaces
C_GetInterface - return a specific interface. You can specify interface name, version and flags separately. You can leave off any of these and you will get what the token thinks is the best match of the interfaces that meet the criteria. We do this in softoken by the order of the interface list.
C_SessionCancel - Cancel one or more multipart operation
C_LoginUser - Supply a user name to C_Login(). This function has no meaning for softoken, so it just returns CKR_OPERATION_NOT_INITIALIZED under the theory that if we in the future want to support usernames, the NSS db would need special initialization to make that happen.
C_Message* and C_*Message*  (20 functions in all) are the new AEAD interface (they are written generally so that it can be used for things other than AEAD). In this patch they are unimplemented (see the next patch).

This patch adds regular (NSC_) and FIPS (FC_) versions of these functions.
Also when creating the PKCS #11 v2.0 interface, we had to create a 2.0 specific version of C_GetInfo so that it can return a 2.40 in the CK_VERSION field rather than 3.00. We do this with #defines since all the function tables are generated automagically with pkcs11f.h.

Differential Revision: https://phabricator.services.mozilla.com/D67240
moz-v2v-gh pushed a commit that referenced this pull request Mar 26, 2020
…S GCM and ChaCha Poly

PKCS #11 defines a new interface for handling AEAD type ciphers that allow
multiple AEAD operations without repeating the key schedule. It also allows
tokens to keep track of the number of operations, and generate IVs (depending
on the cipher).

This patch:
    1. implement those new functions in softoken.
       With the addition of CKF_MESSAGE_* flags to various mechanism, we need
       to strip them when using the version 2 API of softoken (since there are
       no C_Message* function in version 2). For that we need a separate
       C_GetMechanismInfo function. We use the same trick we used to have
       a separate version function for the V2 interface.
       Also now that the new message functions are in their own file, they
       still need access to the common Session state processing functions.
       those have gone from static to exported within softoken to accomidate
       that. Same with sftk_MapDecryptError() (sftk_MapVerifyError() was also
       made global, though nothing else is yet using it).
       Only C_MessageEncrptInit(), C_EncryptMessage(), C_MessageEncryptFinal,
       C_MessageDecryptInit(), C_DecryptMessage(), and C_MessageDecryptFinal
       are implemented. C_EncryptMessageBegin(), C_EncryptMessageNext(),
       C_DecryptMessageBegin(), and C_DecryptMessageNext() are all
       part of the multi-part withing a multi-part operation and
       are only necessary for things like S/MIME (potentially). If we wanted
       to implement them, we would need more functions exported from freebl
       (and initaead, updateaead, finalaead for each mechanism type).
    2. make those interfaces call aes_gcm and chacha20_poly1503
    (and make adjustments for those ciphers).
      For AES, I added a new function AES_AEAD, which handles both encrypt
      and decrypt. Internally, the gcm functions (both the generic gcm and
      the intel gcm wrapper) had their init functions split into key scheduling
      and counter mode/tag initialization. The latter is still called from
      init, but the former is now for each update call. IV generation is
      handled by a single function in gcm.c, and shared with intel_gcm_wrapper.c
      Since the AES functions already know about the underlying PKCS #11
      mechanism parameters, the new AEAD functions also parse the PKCS #11 GCM
      parameters.
      For Chacha/Poly new aead update functions were created called
      ChaChaPoly1305_Encrypt and ChaChaChaPoly1305_Decrypt. There was no
      Message specific initialization in the existing chacha_init, so no
      changes were needed there. The primary difference between
      _Encrypt/_Decrypt and _Seal/_Open is the fact that the tag is put at
      the end of the encrypted data buffer in the latter, and in a generic
      buffer in the former.
    3. create new pk11wrap interfaces that also squash the api differences
    between the various mechanisms for aead (similiar to the way we do it for
    CBC and ECB crypto today).
      To accomplish this I added PK11_AEADOp() and PK11_AEADRawOp(). Both
      functions handle the case where the token only supports the single shot
      interface, by using the single short interface to simulate the
      Message interface. The PK11_AEADOp() also smooths out the
      differences in the parameters and symantics of the various mechanism
      so the application does not need to worry about the PKCS #11 differences
      in the mechanism. Both use contexts from the standard
      PK11_CreateContext(), so key schedules are done once for each key rather
      than once for each message. MESSAGE/AEAD operations are selected by adding
      the psuedo attribute flag CKA_NSS_MESSAGE to the requested operation
      (CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY).
    4. write tests for the new interfaces
      Tests were added to make sure the PK11_AEADRawOp interface works,
      The single shot interface is used to test output of the message interface
      we also use two test only functions to force the connection to use
      the simulation interface, which is also compared to the non-simulate
      inteface. The AES_GCM also tests various IV generators.

Differential Revision: https://phabricator.services.mozilla.com/D67552
moz-v2v-gh pushed a commit that referenced this pull request Apr 6, 2020
Patch 1 of 2.
This patch updates softoken and helper functions with the new PKCS #11 v3 HKDF,
which handles all the correct key management so that we can work in FIPS mode

1) Salts can be passed in as data, as and explicit NULL (which per spec means
a zero filled buffer of length of the underlying HMAC), or through a key handle
2) A Data object can be used as a key (explicitly allowed for this mechanism by
the spec).
3) A special mechansism produces a data object rather than a key, the latter
which can be exported. Softoken does not do the optional validation on the pInfo
to verify that the requested values are supposed to be data rather than keys.
Some other tokens may.

The old hkdf mechanism has been retained for compatibility (well namely until
patch 2 is created, tls is still using it). The hkdf function has been broken
off into it's own function rather than inline in the derive function.

Note: because the base key and/or the export key could really be a data object,
our explicit handling of sensitive and extractable are adjusted to take into
account that those flags do not exist in data objects.

Differential Revision: https://phabricator.services.mozilla.com/D68940
moz-v2v-gh pushed a commit that referenced this pull request Apr 7, 2020
Part 2 of 2

Use the official PKCS #11 HKDF mechanism to implement tls 1.3.

1) The new mechanism is a single derive mechanism, so we no longer need to
pick it based on the underlying hmac (Note, we still need to know the
underlying hmac, which is passed in as a mechanism parameter).

2) Use the new keygen to generate CKK_HKDF keys rather than doing it by hand
with the random number generator (never was really the best way of doing this).

3) modify tls13hkdf.c to use the new mechanisms:
    1) Extract: use the new key handle in the mechanism parameters to pass the
    salt when the salt is a key handle.
       Extract: use the explicit NULL salt parameter if for the hash len salt of
    zeros.
    2) Expand: Expand is mostly a helper function which takes a mechanism. For
    regular expand, the mechanism is the normal _Derive, for the Raw version
    its the _Data function. That creates a data object, which is extractable
    in FIPS mode.

4) update slot handling in tls13hkdf.c:
    1) we need to make sure that the key and the salt key are in the same
    slot. Provide a PK11wrap function to make that guarrentee (and use that
    function in PK11_WrapKey, which already has to do the same function).
    2) When importing a 'data' key for the zero key case, make sure we import
    into the salt key's slot. If there is no salt key, use PK11_GetBestSlot()
    rather than PK11_GetInternal slot.

Differential Revision: https://phabricator.services.mozilla.com/D69899
moz-v2v-gh pushed a commit that referenced this pull request Apr 8, 2020
…S GCM and ChaCha Poly r=mt

Update ssl to use the new PK11_AEADOp() interface.
 1. We restore the use of PK11Context_Create() for AEAD operations.
 2. AES GCM and CHACHA/Poly specific functions are no longer needed as
  PK11_AEADOp() handles all the mechanism specific processing.
 3. TLS semantic differences between the two algorithms is handled by their
  parameters:
       1. Nonce length is the length of the nonce counter. If it's zero, then
       XOR_Counter is used (and the nonce length is the
       sizeof(sslSequenceNumber)).
       2. IV length is the full IV length - nonce length.
       3. TLS 1.3 always uses XOR_Counter.
 4. The IV is returned from the token in the encrypt case. Only in the explict
  nonce case is it examined. (The code depends on the fact that the count in
  the token will match sslSequenceNumber). I did have assert code to verify
  this was happening for testing, but it's removed from this patch it can be
  added back.
 5. All the decrypt instances of XOR_Counter IV creation have been colapsed
  into tls13_WriteNonce().
 6. Even tough PK11_AEADOp returns and accepts the tag separately (for encrypt
  and decrypt respectively). The SSL code still returns the values as
  buffer||tag.
 7. tls13_AEAD() has been enhanced so all uses of AEAD outside of the TLS
  stream can use it instead of their own wrapped version. It can handle streams
  (CreateContext() tls13_AEAD() tls13_AEAD() DestroyContext()) or single shot
  tls13_AEAD(context=NULL). In the later case, the keys for the single shot
  operation should not be resued.
 8. libssl_internals.c in the gtests directory has been updated to handle
  advancing the internal iv counter when we artifically advance the seqNum.
  Since we don't have access to any token iv counter (including softoken),
  The code switches to simulated message mode, and updates the simulated state
  as appropriate. (obviously this is for testing only code as it reaches into
  normally private data structures).

Differential Revision: https://phabricator.services.mozilla.com/D68480
moz-v2v-gh pushed a commit that referenced this pull request Apr 21, 2020
For FIPS we need the following:

 1. NIST official Key padding for AES Key Wrap.
 2. Combined Hash/Sign mechanisms for DSA and ECDSA.

In the first case our AES_KEY_WRAP_PAD function addes pkcs8 padding to the
normal AES_KEY_WRAP, which is a different algorithm then the padded key wrap
specified by NIST. PKCS #11 recognized this and created a special mechanism to
handle NIST padding. That is why we don't have industry test vectors for
CKM_NSS_AES_KEY_WRAP_PAD. This patch implements that NIST version (while
maintaining our own). Also PKCS #11 v3.0 specified PKCS #11 mechanism for
AES_KEY_WRAP which are compatible (semantically) with the NSS vendor specific
versions, but with non-vendor specific numbers. Softoken now accepts both
numbers.

This patch also updates softoken to handle DSA and ECDSA combined hash
algorithms other than just SHA1 (which is no longer validated).

Finally this patch uses the NIST KWP test vectors in new gtests for the
AES_KEY_WRAP_KWP wrapping algorithm.

As part of the AES_KEY_WRAP_KWP code, the Constant time macros have been
generalized and moved to secport. Old macros scattered throughout the code
have been deleted and existing contant time code has been updated to use
the new macros.

Differential Revision: https://phabricator.services.mozilla.com/D71225
moz-v2v-gh pushed a commit that referenced this pull request Apr 24, 2020
…utes that lack NSS database columns r=keeler,rrelyea

`sdb_GetAttributeValueNoLock` builds a query string from a list of attributes in the input template. Unfortunately, `sqlite3_prepare_v2` will fail the entire query if one of the attributes is missing from the underlying table. The PKCS #11 spec [[ https://www.cryptsoft.com/pkcs11doc/v220/pkcs11__all_8h.html#aC_GetAttributeValue | requires ]] setting the output `ulValueLen` field to -1 for such invalid attributes.

This patch reads and stores the columns of nssPublic/nssPrivate when opened, then filters an input template in `sdb_GetAttributeValueNoLock` for unbacked/invalid attributes, removing them from the query and setting their template output lengths to -1.

Differential Revision: https://phabricator.services.mozilla.com/D71622

--HG--
extra : moz-landing-system : lando
moz-v2v-gh pushed a commit that referenced this pull request Aug 24, 2020
… comments=kjacobs

FIPS guidance now requires self-tests for our kdfs. It also requires self-tests for cmac which we didn't have in the cmac patch.

Currently only one test per kdf is necessary. Specifially for SP-800-108, only
one of the three flavors are needed (counter, feedback, or pipeline). This
patch includes more complete testing but it has been turned off the currently
extraneous tests under the assumption that NIST guidance may require them
in the future. HKDF is currently not included in FIPS, but is on track to be
included, so hkdf have been included in this patch.

Because the test vectors are const strings, the patch pushes some const
definitions that were missing in existing private interfaces.

There are three flavors of self-tests:
Function implemented in freebl are added to the freebl/fipsfreebl.c
Functions implemented in pkcs11c.c have selftests completely implemented in
softoken/fipstest.c
Functions implemented in their own .c file have their selftest function
implemented in that .c file and called by fipstests.c
These are consistant with the previous choices for selftests.

Some private interfaces that took in keys from pkcs #11 structures or outputted keys to pkcs #11 structures were modified to optionally take keys in by bytes
and output keys as bytes so the self-tests can work in just bytes.

Differential Revision: https://phabricator.services.mozilla.com/D87812
moz-v2v-gh pushed a commit that referenced this pull request Oct 12, 2020
…f-cfrg-hpke-05). r=mt

This patch adds support for Hybrid Public Key Encryption (draft-irtf-cfrg-hpke-05).

Because the draft number (and the eventual RFC number) is an input to the key schedule, future updates will *not* be backwards compatible in terms of key material or encryption/decryption. For this reason, a default compilation will produce stubs that simply return an "Invalid Algorithm" error. To opt into using the HPKE functionality , compile with `NSS_ENABLE_DRAFT_HPKE` defined. Once finalized, this flag will not be required to access the functions.

Lastly, the `DeriveKeyPair` API is not implemented as it adds complextiy around PKCS #11 and is unnecessary for ECH.

Differential Revision: https://phabricator.services.mozilla.com/D73947

--HG--
extra : moz-landing-system : lando
moz-v2v-gh pushed a commit that referenced this pull request Feb 24, 2021
…ofiles

r=ueno,bbeurdouche

User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0

Steps to reproduce:

Using NSS with PKCS #11 library that returns CKR_ATTRIBUTE_VALUE_INVALID when searching for CKA_CLASS = CKO_PROFILE.

Actual results:

PK11_InitToken calls pk11_ReadProfileList and passes on failures. Thus, if the profiles cannot be read the token cannot be initialized.
pk11_ReadProfileList in turn uses pk11_FindObjectsByTemplate to search for CKO_PROFILE objects. This function fails if C_FindObjectsInit fails.
However, it should be perfectly ok that C_FindObjectsInit fails if CKO_PROFILE is not known. In fact, CKR_ATTRIBUTE_VALUE_INVALID is a valid return code here since the library does not know (yet) the value CKO_PROFILE for CKA_CLASS and since the CKA_CLASS is a fixed list it the standard allows to return this error code.

Expected results:

PK11_InitToken should complete successfully.

Differential Revision: https://phabricator.services.mozilla.com/D106167
moz-v2v-gh pushed a commit that referenced this pull request Apr 19, 2021
1) Add code to treat softokn as a non-threadsafe module.
2) Add a cycle to test ssl against non-threadafe modules.
3) Fix deadlock by restricting the ContextMonitor to only be active around PKCS #11 function calls.

Differential Revision: https://phabricator.services.mozilla.com/D112092
moz-v2v-gh pushed a commit that referenced this pull request Apr 29, 2021
FIPS requires that we supply a hash and sign interface for our supported
signing algorithms to be validated. We already have those interfaces in
softoken for RSA PKCS1, DSA, and ECDSA. However, we don't test those
interfaces, now do we supply a way for an application to access those
interfaces (usually applications use the VFY_ and SGN_ interfaces which
handles the hashing an verify/sign operations).

We also have a generic pk11_signature_tests class in pk11_gtest, but only ecdsa
and some rsa pss tests uses it.

This patch rectifies all of these deficiencies:

lib/softokn
1) Hash and sign/verify mechanisms have been added to softoken to support PSS
hash and sign.
2) The rsa, dsa, and ecdsa hash and sign algorithms were also cleaned up by
creating a fake CKM_SHA1 which matches CKM_SHA_1 so that we can fully use the
same macros for all the hash types.

1&2 was sufficient to provide the goals of this task, however we wanted to be
able to add tests for this functionality..

lib/pk11wrap
3) Two new functions were added: PK11_CreateContextByPubKey and
PK11_CreateContextByPrivKey. These allow you to create multipart contexts with
Public and Private keys. This is a requirement to support hash and sign, as
they are multi-part operations (rather then just signing a hash, which is a
single part operation). With these functions, you can now use the PK11_DigestOp
and PK11_DigestFinal to complete a signature or verify optiation.

gtests/pk11_gtest
4) Add hash and sign/hash and verify support to the generic
pk11_signature_tests.h.
5) pk11_dsa_unittest.cc, pk11_rsa_unittest.cc, and the remainder of
pk11_rsapss_unittest.cc (Wycheproof tests) were moved to use the
pk11_signature_tests common implementation rather then their own.
6) pk11_ecdsa_unittest.cc was updated to support the hash&sign/verify combo
mechanism.
7) With multiple functions using pk11_signature_tests.h, The large functions
are moved to pk11_signature_tests.cpp.
8) The test vectors themselves were not changes, now just test against the
traditional hash first then verify interfaces and the hash and verify
interfaces.

Differential Revision: https://phabricator.services.mozilla.com/D110641

--HG--
extra : rebase_source : d2ec6b9589562cedd4aca45b79a649162eadc5ec
moz-v2v-gh pushed a commit that referenced this pull request May 4, 2021
…ult r=mt

Also fixes:
Bug 452464 pk12util -o fails when -C option specifies AES or Camellia ciphers

Related:
Bug 1694689 Firefox should use modern algorithms in PKCS#12 files by default
Bug 452471 pk12util -o fails when -c option specifies pkcs12v2 PBE ciphers


The base of this fix is was a simple 3 line fix in pkcs12.c, changing the initial setting of cipher and cert cipher.

Overview for why this patch is larger than just 3 lines:
1. First issue was found in trying to change the mac hashing value.
   a. While the decrypt side knew how to handle SHA2 hashes, the equivalent code was not updated on the encrypt side. I refactored that code and placed the common function in p12local.c. Now p12e.c and p12d.c share common code to find the required function to produce the mac key.
   b. The prf hmac was hard coded to SHA1. I changed the code to pass the hmac matching the hashing algorithm for the mac. This required changes to p12e.c to calculate and pass the new hmac as well and adding new PK11_ExportEncryptedPrivateKey and PK11_ExportEncryptedPrivKey to take the PKCS #5 v2 parameters. I also corrected an error which prevented pkcs12 encoding of ciphers other than AES.
2. Once I've made my changes, I realized we didn't have a way of testing them. While we had code that verified that particular sets of parameters for pkcs12 worked together and could be listed and imported, we didn't have a way to verify what algorithms were actually generated by our tools.
  a. pk12util -l doesn't list the encryption used for the certs, so I updated pp to take a pkcs12 option. In doing so I had to update pp to handle indefinite encoding when decoding blocks. I also factored that decoding out in it's own function so the change only needed to be placed once. Finally I renabled a function which prints the output of an EncryptedPrivate key. This function was disabled long ago when the Encrypted Private key info was made private for NSS. It has since been exported, so these functions could easily be enabled (archeological note: I verified that this disabling was not a recent think I found I had done it back when I still have a netscape email address;).
 b. I updated tools.sh to us the new pp -t pkcs12 feature to verify that the key encryption, cert encryption, and hash functions matched what we expected when we exported a new key. I also updated tools.sh to handle the new hash variable option to pk12util.
 c. I discovered several tests commented out with comments that the don't work. I enabled those tests and discovered that they can now encrypt, but the can't decrypt because of pkcs12 policy. I updated the policy code, but I updated it to use the new NSS system wide policy mechanism. This enabled all the ciphers to work. There is still policy work to do. The pk12 policy currently only prevents ciphers from use in decrypting the certificates, not decrypting the keys and not encrypting. I left that for future work.
3. New options for pp and pk12util were added to the man pages for these tools.

---------------------------------------------------------------------------
With that in mind, here's a file by file description of the patch:

automation/abi-check/expected-report-libnss3.so.txt
-Add new exported functions. (see lib/nss/nss.def)

cmd/lib/basicutil.h:
-Removed the HAVE_EPV_TEMPLATE ifdefs (NSS has exported the Encrypted Private Key data structure for a while now.

cmd/lib/secutil.c:
global: Updated several functions to take a const char * m (message) rather than a char * m
global: Made the various PrintPKCS7 return an error code.
global: Added a state variable to be passed around the various PKCS7 Print functions. It gives the proper context to interpret PKCS7 Data Content. PKCS 12 used PKCS7 to package the various PKCS12 Safes and Bags.
-Updated SECU_StripTagAndLength to handle indefinite encoding, and to set the Error code.
-Added SECU_ExtractDERAndStep to grab the next DER Tag, Length, and Data.
-Updated secu_PrintRawStringQuotesOptional to remove the inline DER parsing and use SECU_ExtractDERAndStep().
-Updated SECU_PrintEncodedObjectID to return the SECOidTag just like SECU_PrintObjectID.
-Renable SECU_PrintPrivateKey
-Added secu_PrintPKCS12Attributes to print out the Attributes tied to a PKCS #12 Bag
-Added secu_PrintPKCS12Bag to print out a PKCS #12 Bag
-Added secu_PrintPKCS7Data, which uses the state to determine what it was printing out.
-Added secu_PrintDERPKCS7ContentInfo which is identical to the global function SECU_PrintPKCS7ContentInfo except it takes a state variable. The latter function now calls the former.
-Added secu_PrintPKCS12DigestInfo to print the Hash information of the Mac. DigestInfo is the name in the PKCS 12 spec.
-Added secu_PrintPKCS12MacData to print the Mac portion of the PKCS 12 file.
-Added SECU_PrintPKCS12 to print otu the pkcs12 file.

cmd/lib/secutil.h
-Added string for pkc12 for the command line of pp
reenabled SECU_PrintPrivateKey
-Added SECU_PrintPKCS12 for export.

cmd/pk12util/pk12util.c
-Added the -M option to specify a hash algorithm for the mac.
updated P12U_ExportPKCS12Object: pass the hash algorithm to the PasswordIntegrity handler.
-Added PKCS12U_FindTagFromString: generalized string to SECOidTag which only filters based on the oid having a matching PKCS #11 mechanism.
updated PKCS12U_MapCipherFromString to call use PKCS12U_FindTagFromString to get the candidate tag before doing it's post processing to decide if the tag is really an encryption algorithm.
-Added PKCS12U_MapHashFromString with is like MapCipherFromString except it verifies the resulting tag is a hash object.
-Updated main to 1) change the default cipher, change the default certCipher, and process the new hash argument. NOTE: in the old code we did not encrypt the certs in FIPS mode. That's because the certs were encrypted with RC4 in the default pkcs12 file, which wasn't a FIPS algorithm. Since AES is, we can use it independent on whether or not we are in FIPS mode.

cmd/pp/pp.c
-Added the pkcs12 option which calls SECU_PrintPKCS12 from secutil.c

lib/nss/nss.def
-Add exports to the new PK11_ExportEncryptedPrivKeyInfoV2 and PK11_ExportEncryptedPrivateKeyInfoV2 (V2 means PKCS 5 v2, not Version 2 of ExportEncrypted*Info).
-Add export for the old HASH_GetHMACOidTagByHashOidTag which should have been exported long ago to avoid the proliferation of copies of this function in places like ssl.

lib/pk11wrap/pk11akey.c
-Add PK11_ExportEncryptedPrivKeyInfoV2 (which the old function now calls), which takes the 3 PKCS 5 v2 parameters. The underlying pkcs5 code can fill in missing tags if necessary, but supplying all three gives the caller full control of the underlying pkcs5 PBE used.
-Add PK11_ExportEncryptedPrivateKeyInfoV2, same as the above function except it takes a cert which is used to look up the private key. It's the function that pkcs12 actually uses, but the former was exported for completeness.

lib/pk11wrap/pk11pub.h
-Added the new PK11_ExportEncryptedPriv*KeyInfoV2 functions.

lib/pkcs12/p12d.c
-Remove the switch statement and place it in p12local.c so that p12e.c can use the same function.

lib/pkc12/p12e.c
-Remove the unnecessary privAlg check so we can encode any mechanism we support. This only prevented encoding certificates in the pk12 file, not the keys.
-add code to get the hmac used in the pbe prf from the integrity hash, which is under application control.
-Do the same for key encryption, then use the new PK11_ExportEncryptedPrivateKeyInfo to pass that hash value.
-Use the new sec_pkcs12_algtag_to_keygen_mech so there is only one switch statement to update rather than 2.
-Update the hash data to old the length of the largest hash rather than the length of a SHA1 hash.

lib/pkcs12/p12local.c
- Add new function new sec_pkcs12_algtag_to_keygen_mech to factor out the common switch statement between p12e and p12d.

lib/pkcs12/p12local.h
-Export the new sec_pkcs12_algtag_to_keygen_mech

lib/pkcs12/p12plcy.c
-Map the old p12 policy functions to use the new NSS_GetAlgorithmPolicy. We keep the old table so that applications can change the policy with the old PKCS12 specific defines (so the old code keeps working). NOTE: policies now default to true rather than false.

lib/util/secoidt.h
-Add new NSS_USE_ALG_IN_PKCS12 used by pk11plcy.c
NOTE: I have not updated the policy table in pk11wrap/pk11pars.c, so we can't yet control pkcs12 policy with the nss system policy table. That's a patch for another time.

test/tools/tool.sh
-global: Remove trailing spaces
-global: DEFAULT is changed to 'default'
-Update the PBE mechanism to exactly match the string in secoid.c. PKCS #12 does case independent compares, so case doesn't matter there, but now I'm comparing to the output of pp, and I didn't want to spend the time to figure out case independent compares in bash.
-Add our defauts and shell variables at the top so there are easy to change in the future.
export_with_*** have all been colapsed into a single export_p12_file which handles taking 'default' and turning off that argument.
-Add for loops for the hash functions.
-Restore the camellia ciphers back now that they work.
-Restore the pkcs12V2pbe back now that they work.
-Collect various pbe types into single variables and use those variables in loops
-Reduce the number of tests ran in optimized mode (which takes 60x the time to do a pbe then than debug mode based on a larger iterator).
-Add verify_p12 which dumps out the p12 file and makes sure the expected CERT_ENCRYPTION, KEY_ENCRYPTION, and HASH are used.

doc/pp.xml
-Add pkcs12 option

doc/pk12util.xml
-Add -M option
-Update synopsis with options in the description but not in the synopsis

Differential Revision: https://phabricator.services.mozilla.com/D113699
moz-v2v-gh pushed a commit that referenced this pull request May 18, 2021
Changes from the review:
The while loop was taken out of it's subshell pipe, which prevented the selfserv PID from being passed on to the final selfserv-kill. This eventally lead to a freeze on windows.

The last paragraph of ISO 19790:2012 section 7.2.4.2 states:

All services shall [02.24] provide an indicator when the service utilises an approved cryptographic algorithm, security function or process in an approved manner and those services or processes specified in 7.4.3

This means our libraries need to grow an API or provide some additional information via contexts or similar in order for an application to be able to query this indicator. This can't be just a Security Policy description because ISO 24759:2017 section 6.2.4.2 states:

TE02.24.02: The tester shall execute all services and verify that the indicator provides an unambiguous indication of whether the service utilizes an approved cryptographic algorithm, security function or process in an approved manner or not.

The indicator can't be just a marker over an algorithm either, because it needs to show different values based on whether the algorithm parameters causes the algorithm to run in approved or non-approved mode (ie keys outside of valid range for RSA means RSA is being used in non-approved mode ...)

For NSS, there is a PKCS #11 design:
https://docs.google.com/document/d/1Me9YksPE7K1Suvk9Ls5PqJXPpDmpAboLsrq0z54m_tA/edit?usp=sharing

This patch implments the above design as well as:
   1) NSS proper functions to access these indicators from either the pk11wrap layer or the ssl layer.
   2) Updates to the ssl tests which will output the value of the

Changes decription by file:
cmd/selfserv/selfserv.c
   Add a FIPS indicator if the connection was excuted in FIPS mode on a FIPS token.
cmd/strsclnt/strsclnt.c
   Add a FIPS indicator if the connection was excuted in FIPS mode on a FIPS token.
cmd/tstclnt/tstclnt.c
   Add a FIPS indicator if the connection was excuted in FIPS mode on a FIPS token.
lib/nss/nss.def
   Add the new pk11 functions to access the fips indicator.
lib/pk11wrap/pk11cxt.c
   Implement a function to get the FIPS indicator for the current PK11Context.
lib/pk11wrap/pk11load.c
   Get the fips indicator function from the PKCS #11 module using the vendor function interface from PKCS #11 v3.0
lib/pk11wrap/pk11obj.c
   Implement a function to get the FIPS indicator for a specific PKCS #11 object.
lib/pk11wrap/pk11priv.h
   Add a generalized helper function to get the FIPS indicator used by all the other exported functions to get FIPS indicator.
lib/pk11wrap/pk11pub.h
   Add function to get the FIPS indicator for the current PK11Context.
lib/pk11wrap/pk11slot.c
   Implement a generalized helper function to get the FIPS indicator.
   Implement a function to get the FIPS indicator for the latest single shot operation on the slot.
lib/pk11wrap/secmodt.h
   Add a new field to hold the fipsIndicator function.
lib/softoken/fips_algorithms.h
   New sample header which vendors can replace with their own table. In the default NSS case, the table in this header will be empty.
lib/softoken/fipstokn.c
   Add Vendor specific interface for the FIPS indicator to the FIPS token.
lib/softoken/pkcs11.c
   Add Vendor specific interface for the FIPS indicator to the non-FIPS token.
   Factor out the code tha maps an attribute value to a mechanism flag to it's own file so it can
be used by other parts of softoken. (new function is in pkcs11u.c
   Implement the function that returns the FIPS indicator. This function fetches the indicator from either the session or the object or both. The session indicator is in the crypto context (except the last operation indicator, which is in the session itself. The object indicator is in the base object.
lib/softoken/pkcs11c.c
   Record the FIPS indicator in the various helper function.
    - sftk_TerminateOp is called when a crypto operation had been finalized, so we can store that fips indicator in the lastOpWasFIPS field.
    - sftk_InitGeneric is called when a crypto operation has been initialized, so we can make a preliminary determination if the operation is within the FIPS policy (could later change bases on other operations. For this to work, we need the actual mechanism, so pMechanism is now a parameter to sftk_InitGeneric.
    - sftk_HKDF - HKDF when used in TLS has the unusual characteristic that the salt could actually be a key. In this case, usually the base key is some known public value which would not be FIPS generated, but the security is based on whether the salt is really a FIPS generated key. In this case we redo the calculation based on the salt key.
lib/softoken/pkcs11i.h
    - add the FIPS indicators to the various structures (crypto contexts, sessions, objects).
    - add the FIPS indicators function list
    - add pMechanism the the sftkInitGeneric function.
    - add the helper function to map Attribute Types to Mechanism Flags.
    - add the function that will look up the current operation in the FIPS table to determine that it is allowed by policy.
lib/softoken/pkcs11u.c
    - include the new fips_algorithms.h (if NSS_FIPS_DISABLED is not on)
    - handle the FIPS status for objects and session on creation an copy.
    - implement the helper function to map Attribute Types to Mechanism Flags.
    - get the key length of a key. This involves getting the key type and then using the key type to determin the appropriate attribute to fetch. Most keys it's simply the CKA_VALUE. ECC is special, we get the key length from the curve. Since only a subset of curves can be FIPS Curves, we use key length to return false for other curves.
    - the handle special function handles any unusal semantics for various mechanism types. This function precodes possible mechanism semantics we may need to check. The special handling can be selected by the mechanism table in fips_algorithms.h
    - sftk_operationIsFIPS - the actual function to determine if the givelib/n operation is in the FIPS table.
lib/softoken/sftkmessage.c
    - just need to update the sftk_InitGeneric function to pass the mechanism.
lib/ssl/ssl3con.c
    - and functions to query the underlying crypto contexts to see if the current ssl session is running in FIPS approved mode based on the security policy. It does so by checking the CipherSpecIsFIPS function to verify that both the mac and the encryption algorithm FIPS conforms to the ciphers in the security profile (using PK11_GetFIPSStatus). We check both the cipher specs for read and write. These underlying specs depends on the keys used in these specs being generated with FIPS approved algorithms as well, so this verifies the kea and kdf functions as well.
lib/ssl/sslimpl.h
   - ass ssl_isFIPS() so it can be used by other files here in the ssl directory.
lib/ssl/sslinfo.c
   - set the new isFIPS field in the existing sslinfo structure. SSL_GetChannelInfo knows how to handle sslinfo structures that are smaller then expected and larger than expected. unknown fields will be set to '0' (so new applications running against old versions will always get zero for new fields). sslinfo that are smaller will only return a the subset the calling application expects (so old applications will not get the new fields).
lib/ssl/sslt.h
    - Add the new isFIPS field (must be at the end of the ChannelInfo structure).
lib/util/pkcs11n.h
    - add the new FIPS indicator defines.
tests/ssl/ssl.h
    - The main changes was to turn on verbose for the coverage tests so we can test the FIPS indicators on various cipher suites. NOTE: this only works with either NSS_TEST_FIPS_ALGORIHTMS set, or a vendor fips_algorthims.h, so vendors will need to do their own test interpretation. While working in ssl.sh I fixed an number of other issues:
    - many tests that were skipped in FIPS mode were skipped not because they didn't work in FIPS mode, but because tstclnt requires a password when running in FIPS mode. I've now added the password if the function is running in fips mode and removed the fips restrictions.
    - dtls had a race condition. the server side needed to come up before the client, but couldn't end before the client ran. We already had a sleep to guarrentee the former, I added a sleep before sending the server it's data to handle the latter.
    - CURVE25519 is the default ECC curve, but it's not a fiPS curve, so I disable it in FIPS mode so we will actually get FIPS indicators when using ECDHE.
    - I added TLS 1.3 to the coverage tests.

Differential Revision: https://phabricator.services.mozilla.com/D115034

--HG--
extra : rebase_source : a1362bcf8107d26492578475d95522001ed0c3bd
moz-v2v-gh pushed a commit that referenced this pull request Sep 7, 2021
…upported

Bug 1707130 Fixed the base issue with Camellia, but now it has the same issue
as AES did which was fixed in Bug 1268141.

The fix is to generalize the AES patch, recognizing the issue isn't AES
specific but an issue for any case where we encode the keysize into the
oid, but the oid maps to the same PKCS #11 mechanism.

This patch condenses a lot of the original AES fix, collecting several blocks
of common code into single functions, and putting one place where the key
sizes of pkcs5v2 algorithms with different oids with keys size specific
to those oids, but their mechanism maps to a single PKCS #11 mechanism
live. This means future algorithms can be handled easily.

bob

--HG--
extra : rebase_source : 672d24a1300f40236f9c3a82376fbfad57f68f84
moz-v2v-gh pushed a commit that referenced this pull request Nov 17, 2021
1. This patch adds a new command, validation, which dumps the validation
objects ina given token. It defaults to the softoken.

2. It sets up the infrastructure to allow creation at init time of token
specific objects (like validation objects and profile objects) by:
    2a. factoring out the code to get the next available object handle to a
    new function call sftk_getNextHandle().
    2b. The object freelists are now initialized before SFTK_SlotInit, so that
    SFTK_SlotInit can initialize these new token objects.
    2c. A new staticly defined session is created to hand these object on.
        2c1. sftk_NewSession and sftk_FreeSession has the initialization and
        clearing functions factored out from the actual space freeing clearing
        so they can be used on this staticly allocated session. (NOTE: NSS has
        two ways it handles this internally: use of Init/New Clear/Free
        functions as in this patch, or the use of a bool called 'FreeIt' added
        to the original function. There is no technical reason for why I used
        Init/New other than I didn't have to go change all the places the
        currently call them. These are internal private functions, so it's ok
        to change their signatures.
        2c2. The static sessions are initialized on freed when the slot is
        created and destroyed.

3. For fips slot the validation object is created. The version number is
   selected at compile time with a build time environment variable. If no
   version number is provided, a default version number (related to the NSS
   version) is selected as well as the string 'unvalidated'.

4. The NSS spefic defines for Validation objects are defined in the NSS vendor
space (until PKCS #11 v3.2 comes out with the official values).

Differential Revision: https://phabricator.services.mozilla.com/D124951

--HG--
extra : rebase_source : 026cc5f261af7166a9ced1e4deb7c7ac338e581d
moz-v2v-gh pushed a commit that referenced this pull request Jul 27, 2022
…RI, r=kjacobs,rrelyea

Previously we only used the "object" attribute (mapped to CKA_LABEL) to find certificates by PKCS #11 URI. This updates the logic to match also with "id" (mapped to CKA_ID) and reject the request if a "type" attribute is present with the value other than "cert".

Note: as "id" may not be null-terminated, the PKCS #11 URI API had to be revamped to allow binary blobs. This is still not perfect because PK11URIAttribute doesn't have a length field of value.

Differential Revision: https://phabricator.services.mozilla.com/D98940

--HG--
extra : amend_source : 3d4d3341ff0acdb69fe03915c0b89527577730b2
moz-v2v-gh pushed a commit that referenced this pull request Sep 15, 2023
…t NSC_ or FC_ variants.

NSS softoken presents a PKCS #11 API to the NSS low level crypto. This allows NSS to have native support for replacement PKCS #11 libraries, and is also the FIPS boundary, allowing the rest of NSS to change without affecting any FIPS validations.

Some applications that need crypto, but have their own higher level implementations of SSL or S/MIME use NSS softoken. Softoken has 2 general APIs: NSC_xxxx calls which implement the normal NSS interface, but does not include any FIPS restrictions, The FC_xxx interfaces which implements FIPS restrictions on the semantics of the calls and additional FIPS requirements (like self-tests and software integrity checks). The official PKCS #11 APIs are C_xxx interfaces, and NSS exports those as aliases for NSC_xxxx calls.

Right now applications that use softoken have to know the NSS names if they want to access the FIPS api. This bugs removes this restriction and causes calls to C_xxxx to alias to FC_xxxxx if the system is in FIPS mode. If the system has no system FIPS indicator, or the that indicator is off, the C_xxxx will continue to call NSC_xxxxx. NSS itself will continue to use NSC_xxxx or FC_xxxx according to the NSS internal FIPS settings.

----------------
Currently there are 3 layers in NSS with code that identifies the whether the system is in NSS: nss proper (which is also exported to applications), and freebl for the Freebl hash direct case. This code would add a 3rd (in softoken). Rather than adding a third, this patch relocates the main function to nssutil where softoken, nss, and freebl can all access it. The exception is when building freebl with 'NODEPEND' (freebl can provide hashing without dependencies on NSPR or NSSUTIL), there needs to be a stub implementation. In most platforms and cases this stub is never compiled.

Differential Revision: https://phabricator.services.mozilla.com/D175259
@beurdouche beurdouche closed this Dec 5, 2023
moz-v2v-gh pushed a commit that referenced this pull request May 6, 2024
Step 1:
All of these (and any new signature algorithm going forward) will no longer separate encryption from hashing, but only define single hash and sign version of the signature. This is because the new signatures include a 'salt' as part of the signature that is hashed before the actual message is hashed. This means our signature code needs to handle the full hash and sign operation. secsign and secvfy already support these kinds of interfaces, and PKCS #11 already defines combo mechanisms for the existing signatures. We just need to have secsign/secvfy use the combo mechanisms when they are available. This can be done independently of the PQ Signature changes.

Changes:
1. sec_DecodeSigAlg now returns a PKCS #11 mechanism for the combined signature alg, and a mechanism parameter for that mechanism. If the returned mechanism is CKM_INVALID_MECHANISM, then the code is to fallback to the old version of the
code.
2. SGNContext and VFYContext gain a PK11Context * to hold the ongoing PKCS #11 op.
3. In Sign and verify functions, if we can get a PK11Context, we use that rather than the hash context.
4. New sgn_SingleShot and vfy_SingleShot handles the case where we are have the full data to sign all in one case.
5. Some refactoring of common operations (converting PKCS #11 sigs into DER sigs, allocating items to store signatures, and storing the PKCS #11 signature in the verify context) into their own functions to reduce the complexity of the code.
6. Updating the missing mechanisms in the combined OID values.

Differential Revision: https://phabricator.services.mozilla.com/D175258

--HG--
extra : rebase_source : f6f21b0cb6f4a8724affce47239c119bea844b81
moz-v2v-gh pushed a commit that referenced this pull request Jun 3, 2025
The 3.1 definition for IPSEC is based on our vendor specific implementation. We need to move to the PKCS #11 3.1 names so applications can use the official PKCS #11 identifiers and names in their program.
 1. Since the vendor structs and the pkcs #11 structs are identical except for the name, we don't need to do any struct conversion, just use the new names.
 2. Since the semantics of the Mechanisms between the vendor specific and the PKSC #11 spec is identical, we only need to add the new mechanism number to our tables and switch statements.
 3. For backward compatibility, we still need to use the vendor specific mechanism, so turn off the deprecation warning for those files that need those mechanism.
 4. Mark all the vendor specific versions as deprecated if possible.
 5. Update all out tests to use the new names and mechanism. We rework some existing code from trust to make it more general.

Differential Revision: https://phabricator.services.mozilla.com/D245633

--HG--
extra : rebase_source : 21778b1dcd1091c202237c96fe237b7fb9e66713
moz-v2v-gh pushed a commit that referenced this pull request Jun 3, 2025
Update the headers to v3.2. This does not start using the PKCS #11 v3.2
function tables in softoken yet.

The collision between the vendor specific CKA_TRUST names and the pkcs #11
spec is handled by renaming the PKCS #11 trust attributes as CKA_PKCS_TRUST and the vendor specific ones as CKA_NSS_TRUST. A define is used to select which
value the old name takes on. For now it stays with CKA_NSS_TRUST for
compatibility (and until the internal NSS usages have been updated).

Differential Revision: https://phabricator.services.mozilla.com/D249642

--HG--
extra : rebase_source : e6418b7456a0d57820bb0515d3bafd3830fde9b9
moz-v2v-gh pushed a commit that referenced this pull request Jun 3, 2025
1. add the -C function to force non-FIPS mode in shlibsign.
2. update shlibsign to fetch the following pkcs #11 interfaces:
    a. NSC_ functions when -C is supplied (always use non-FIPS mode).
    b. C_ functions when neither -C nor -F is supplied (fetch non-FIPS if the system is non-FIPS otherwise fetch FIPS).
    .c FC_ functions when -F is supplied (always use FIPS mode).
3. update the hmac portion to generate the key externally and import it in FIPS mode so we don't have to extract it.
    a. record the key in the case it was provided to us so we don't have to extract it later.
    b. refactor how this happens into smaller functions so we can reuse them in FIPS mode.
4. fix error message issue by initializing the NSS error strings.
5. remove OS/2 specific .cmd file.
6. add -C to the build. In the build case we are using the newly built libraries to sign themselves. They can't function in FIPS mode until they are signed, so always sign them in non-FIPS mode as part of the build. (releases that want to sign them in FIPS mode can resign them after the initial signature).
7. add test to make sure FIPS mode of shlib sign continues to work.

Differential Revision: https://phabricator.services.mozilla.com/D230330

--HG--
extra : rebase_source : f84b8b66c41f6271d165ed721571ad9a26e96c30
moz-v2v-gh pushed a commit that referenced this pull request Jul 8, 2025
cmd/dbtool/dbtool.c
cmd/lib/pk11table.c
- add knowledge of the pkcs trust attributes for the dbtool.

lib/dev/ckhelper.c
lib/dev/ckhelper.h
- add pkcs CKT_TRUST values to the trust to STAN conversion tables.
- handle transparently fetching the appropriate attributes from the trust
  objects:
    - Use CKA_PKCS_TRUST for CKO_TRUST objects and CKA_NSS_TRUST for
      CKO_NSS_TRUST objects.
    - Fetch that hash from CKA_HASH_OF_CERTIFICATE for CKO_TRUST and
      CKA_NSS_CERT_SHA1_HASH for CKO_NSS_TRUST.
    - The actual hash mechanism is now variable, so we need to pass the
      hash mechanism with the hash.

lib/dev/devt.h
- space to store the actual object type so we can later reference it when
  fetching attributes.

lib/dev/devtoken.c
- nssToken_UsePKCS11Trust()
  - use the token's function table version to decide which type of trust
    object to store in the token.
- nssToken_ImportTrust()
  - use the token type to choose the flavor of CK_TRUCT values stored in the
    attributes.
  - make the two hashBufs generic. for CKO_TRUST (PKCSTrust), we'll use SHA256,
    for the CKO_NSS_TRUST (NSSTrust) we use SHA1 and MD5. We use the new
    NSSAlgorithm_DigestBuff which takes a PKCS #11 mechanism to decide which
    hash function to use.
- nssToken_FindTrustForCertificate()
  - search for CKO_TRUST first, then search for CKO_NSS_TRUST. Record the actual
    trust object in the trust structure for ckhelper.c to find.
- nssToken_Digest()
   - update the rvOpt->size with the actual hash result size.
lib/dev/devutil.c
- nssCryptokiObject_create
   - initialize trustType to CKM_INVALID_MECHANISM so we don't get confused
     about the type of the object if we happend to be called with an object
     that didn't go through nssToken_FindTrustForCertificate().
- create_trust()
   - use the trusttype to decide what attributes are appropriate for the
     object we are going to create.
- NSSAlgorithmAndParameters_CreateDigest()
   - remove the very hash specific versions of CreateDigest() with a generic
     version that takes a hash value.
- NSSAlgorithm_DigestBuf()
    - this function hashes an NSSItem (input) and places the result in another
      NSS item, output. Output should already allocate space for the hash in
      output->data. The amount of space is in output->size.

lib/dev/nssdev.h
- Add NSSAlgorithmAndParameters_CreateDigest() and NSSAlgorithm_DigestBuf()

lib/pk11wrap/debug_module.c
- Update debug data with the new Trust Attributes, Objects and CKT_TRUST values

lib/pk11wrap/pk11merge.c
- Merge two trust objects into a target database. The two objects could be of
  different types (CKO_TRUST or CKO_NSS_TRUST). If the resulting trust is to
  update  the target value, the target's trust object type is used on write,
  otherwise the source's type is used. Potential TODO:  if the copy fails
  from the sources type we probably should retry with the opposite trust type.

lib/pk11wrap/pk11nobj.c
- replace the hand lookup of the trust object with the existing stan code,
  which uses the correct full token search for the trust object.

lib/pki/certificate.c
- nssTrustIsValidHash()
  - we now have to deal with potential different hashes. The old code hashed
    the certificate once with SHA-1. In order to keep that performance if the
    hashes are all the same, we keep a cache of the last hash value and what
    mechanism was used to hash it. If the new hash to compare is a different
    mechanism, we hash the cert (potentially again) with that new algorithm and
    cache the result.
  - we return true if the hashes match.
- nssTrust_Create()
  - use generic names for the hashbuf (since they may or may not be sha-1
    hashes).
  - hashMech == to CKM_INVALID_MECHANISM is the equivalent of no hash present

lib/pki/pki3hack.c
lib/pki/pki3hack.h
- get_nss3trust_from_nss4trust()
    - CERTDB_NSS_TRUSTED_CA was set whenever the cert was trusted in
      pk11_HandleTrustObject(), preserve this semenatic even when it's calling
      into stan code.
- nssTrust_HandleTrustForCERTCert()
    - new function of pk11_HandleTrustObject() to call

Differential Revision: https://phabricator.services.mozilla.com/D252972

--HG--
extra : rebase_source : f53a5f10631e6248e9b6f168020532d0d06e8f8d
moz-v2v-gh pushed a commit that referenced this pull request Jul 8, 2025
lib/softoken/legacydb/lgattr.c
lib/softoken/legacydb/lgcreate.c
lib/softoken/legacydb/lgdb.h
lib/softoken/legacydb/lgdbdestroy.c
lib/softoken/legacydb/lgfind.c
   - Update legacydb to handle PKCS #11 trust objects:
   - writing CKO_TRUST will update the database trust normally.
   - change the code to allow searching for CKO_TRUST and CKO_NSS_TRUST and
   return the same object as both types.
   - Understand both versions of CKA_TRUST_* attributes (CKA_NSS_TRUST and
   CKA_PKCS_TRUST). Return the approriate CKT_ values for the given trust
   object.
   - On create or set, accept both CKA_NSS_TRUST* and CKA_PKCS_TRUST* and
   their respective CKT_ values.
   - return SHA1 hashs for both CKA_NSS_CERT_SHA1_HASH and
   CKA_HASH_OF_CERTIFICATE.
   (ignore hash on write, hash is always generated from a certificate)
lib/softoken/sdb.c
    - Add PKCS #11 v3.2 attributes to the known attribute list. export the
    list so we can use it in sftkdb.c rather than recplicating it there.
lib/softoken/sftkdb.c
    - use the proper explicit names for CKA_TRUST_* (so CKA_PKCS_TRUST_*
    and CK_NSS_TRUST_* for those labels that collide.
    - map everything to CKO_TRUST (PKCS#11 trust) internally for merges.
lib/softoken/sftkdbti.h
    - include external defines for the known attributes.
lib/softoken/sftkpwd.c
    - update the CKA_TRUST names and add the PKCS attributes.

Differential Revision: https://phabricator.services.mozilla.com/D252971
moz-v2v-gh pushed a commit that referenced this pull request Jul 9, 2025
…r=rrelyea

patch by frantisek.
Handle the move the the PKCS #11 CK_PKCS5_PBKD2_PARAMS in a compatible way.
Look at the bug for the extensive discussions.
moz-v2v-gh pushed a commit that referenced this pull request Jul 23, 2025
lib/softoken/fipsaudt.c
lib/softoken/softoken.h
lib/softoken/softoknt.h
- Add new audit functions for encapsulate and decapsulate

lib/softoken/fipstokn.c
- update pkcs11 3.0 function table to a specific name.
- add pkcs11 3.2 function table.
- add FIPS versions of the new Signature, Encaps/Decaps, GetSeesionValidationFlags,
  Async and authenticated key wrap functions.

lib/softoken/kem.c
- update kem functions to understand the new PKCS #11 version names.
- add option to disable Kyber to kem functions.
- update kem functions to get the parameter from the key.
- implement pkcs #11 C_EncapsulateKey and C_DecapsulateKey with the PKCS #11 argument order.
- return the old NSS EncapsualteKey and Decapsulate key with it's order for compatibility. The
  old API just calls the new functions, so even the old API will get the new PKCS #11 mechanism.

lib/softoken/pkcs11.c
- update pkcs11 3.0 function table to be a specific name.
- add PKCS11 3.2 function table.
- update NSS_INTERFACE_COUNT to automatically get the correct array size.
- add the PKCS #11 attribute for ML_KEM
- add Unsupported Async stubs.
- add NSC_GetSessionValidationFlags using the already existing nsc_NSSGetFIPSStatus flag.
- add NSC_VerifySignature* functions. Currently there isn't any algorithms that don't
  work with the old interface, so this functions simply cache the signature and use the old
  inteferface to implement the NSC_VerifySignature* function.
- CK_NSS_KEM_PARAMETER_SET_TYPE fetching of paremeter set, make it generic since lots of
  algorithms will have a CK_ULONG CKA_PARAMETER_SET value in the keys.
- add unsupported stubs for WrapKey and UnwrapKey Authenticated.

lib/softoken/pkcs11i.h
- add signature item for VerifySignature algorithms.
- add defines for the FIPS_FLAG

lib/softoken/pkcs11u.c
- add signature item for VerifySignature algorithms.
- update sftk_CreateValidationObjects to create real PKCS #11 v3.2 validation objects.

Differential Revision: https://phabricator.services.mozilla.com/D253179

--HG--
extra : rebase_source : 8ab7efd0364b1753fe29e56b3f030e28d709b0b4
moz-v2v-gh pushed a commit that referenced this pull request Jul 28, 2025
…ects.

cmd/validation/validation.c
 - add support for reading the new validation object. automatically select the new objects for reading if the token is PKCS #11v3.2 or greater.
 - supply options to override that selection.

lib/freebl/stubs.c
lib/freebl/stubs.h
 - fix mispelling in stubs (causes the FIPS-140-3 build option to fail)

lib/nss/nssd.def
lib/pk11wrap/pk11cxt.c
lib/pk11wrap/pk11pub.h
 - Add a general function to help select the PKCS #11 version for a token.
   - There are 2 places in a PKCS #11 module where there is a version number:
     1) as the result of C_GetInfo - this states the general version of the module and the appropriate for checking general functionality.
     2) the version field that the start of the function list. This tells us the version of the function list. It's possible (though unlikely) to have an older function list while still having an up-to-date PKCS #11 module. Use this to determine if it's safe to call a particular function.

lib/pk11wrap/pk11slot.c
 - implement PK11CheckPKCS11Version described above.
 - use the Validation objects to FIPS flags for this slot (pk11_GetValidationFlags and PK11_InitToken0
 - Map the new PKCS #11 calls to the exported NSS interface if the token is PKCS #11 v3.2 or new.
   - The PKCS #11 interface uses an attribute to show the indicators (called validation flags) on an object.
   - It used the new C_GetSessionValidationFlags to get the indicator from the session.
   - In practice there will likely be only once FIPS validation object and one FIPS validation flag, but if there are more than one we return true if any of the flags are on.

lib/pk11wrap/secmodi.h
 - update the returned function pointer so we can call the new C_GetSessionValidationFlags

lib/pk11wrap/secmodti.h
 - place to store the slot's FIPS validation flags.

lib/softoken/pkcs11.c
 - implement the indicators as an attribute.
    -  We create a pseudo attribute so that it doesn't get stored on the database.
    - The attribute is stored in the object structure, replacing the isFIPS flag.
    - Special functions sftk_setFIPS and sftk_hasFIPS access the flag as if it were a bool. (This would allow a future we we make it a full attribute that is stored in the DB.
    - The sftk_template_hasAttribute allows us to handle the case where we are checking the token by skipping the bypass so we don't need to give sftkdb_ layer calls the knowledge of the attribute.
 - fix bug where the PKCS #11 Validation objects were being added to the slot.

Differential Revision: https://phabricator.services.mozilla.com/D258777

--HG--
extra : amend_source : fb6e52e4bbd18c547680fc56f92f620cb365e8c0
moz-v2v-gh pushed a commit that referenced this pull request Aug 18, 2025
Use the PKCS #11 v3.2 functions and mechanism to do ML_KEM.

lib/pk11wrap/pk11akey.c
- use CKA_PARAMETER_SET rather then CKA_NSS_PARAMETER_SET. retry with the former if we fail.
- accept CKK_ML_KEM as well as the two vendor specific key types.
- add support for CKA_ENACAPSULATE and CKA_DECAPSULATE when creating keys.
- if we are using an 3.2 or later function list, use the PKCS #11 C_Encapsulate and C_Decapsulate call.
- for Encapsulate, use the normal PKCS #11 protocol to get the ciphertext length rather than "Just knowing it".
 - We make the Encapsulate/Decapsulate more generic so it can work with KEMs other than ML-KEM.

lib/softoken/kem.c
- update softoken to accept CKA_PARAMETER_SET as well as CKA_NSS_PARAMETER_SET for the old mechanisms.

lib/softoken/pkcs11.c
- export the ENCAPSULATE/DECAPSULATE mechanism flags for our KEM mechanisms.
- add the same support for CKA_ENCAPSULSATE/CKA_DECAPSULATE and CKA_*PARMETER_SET in pkaakey in softoken.

lib/softoken/pkcs11c.c
- add pairwise consistency check for CKM_ML_KEM_GENERATE_KEY_PAIR. The CKM_NSS version still will skip the pairwise check so ssl can keep using that in FIPS mode (like the special ECC KEY_GEN).

lib/ssl/tls13con.c
- update tls to use the new mechanism and parameter sets.
- retry the keygen with more secure keys if the first key gen fails. This happens in FIPS mode (obviously).
- do the same than for PK11_Encapsulate and PK11_Decapsulate

lib/util/kyber.h
- Add defines for the max key sizes for ml_kem (will update when mlkem1024 gets added.

tests/ssl/ssl.sh
- add tests for mlkem to the ssl coverage tests.

Differential Revision: https://phabricator.services.mozilla.com/D259698

--HG--
extra : rebase_source : 26eb79c80de1dac25d7149b612c4902f65b92d5f
moz-v2v-gh pushed a commit that referenced this pull request Sep 2, 2025
lib/cryptohi/secvfy.c
- if we are using 3.2 function tables, then use the PKCS #11 Signature
  functions. We just need to do this at Context create time and the context
  code will use the context time to determin which PKCS #11 functions to call.
  It uses a new PK11_CreateSignatureContextByPubKey().
lib/nss/nss.def
lib/pk11wrap/pk11pub.h
- add PK11_CreateSignatureContectByPubKey().
lib/pk11wrap/pk11cxt.c
- Add PK11_CreateSignatureContextByPubKey() which takes a signature. It's basically the same as PK11_CreateContextByPubKey(), but carries the signature down to context_init where it can be passed to C_VerifySignatureInit(). The the PK11_CreateContextByPubKey just calls PK11_CreateSignatureContextByPubKey() with a NULL
signature.
- Add C_VerifySignature to our context. CKA_NSS_VERIFY_SIGNATURE is a new fake Attribute that is used to make VerifySignature Contexts.
lib/pk11wrap/pk11obj.c
- add C_VerifySignature to PK11_VerifyWithMechanism.
lib/softoken/pkcs11c.c
- fix bugs in NSC_VerifySignatureInit and NSC_VerifySignature. These functions don't require streaming specifically.
lib/util/pkcs11n.h
- Define CKA_NSS_VERIFY_SIGNATURE fake attribute.

Differential Revision: https://phabricator.services.mozilla.com/D261181
moz-v2v-gh pushed a commit that referenced this pull request Sep 9, 2025
lib/softoken/pkcs11c.c
lib/softoken/pkcs11.c
 - add support for CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE and CKM_TLS_EXTENDED_MASTER_KEY_DERIVE_DH
   The standard mechanism are based on our Vendor specific mechanism (I submitted the vendor specific mechanism to the PKCS #11 working group.), so the support is basically "do what CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE does".

lib/ssl/ssl3con.c
 - use CKM_HKDF_DATA as the mechanism to check for KDF support for ssl_auth_psk.
 - add support for CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE and CKM_TLS_EXTENDED_MASTER_KEY_DERIVE_DH
   In this case we want to fall back to the CKM_NSS_ mechanism if the CKM_TLS mechanism don't exist.

lib/util/pkcs11n.h
 - CK_TLS12_EXTENDED_MASTER_KEY_DERIVE_PARAMS is identical to CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS. Just make the latter an alias for the former.
lib/util/secoid.c
  - use CK_AES_KEY_WRAP and CKM_CHACHA20_POLY10305. Both of those have been implemented
  in NSS for quite some time.



 -

Differential Revision: https://phabricator.services.mozilla.com/D260079

--HG--
extra : rebase_source : b1e6c1af007178daa816ab125dd2d851a8522993
moz-v2v-gh pushed a commit that referenced this pull request Sep 12, 2025
…11wrap and cryptohi

overall: colapse several repeated use of keyType uses.

certutil.c, sign.c, keyhi.h, seckey.c: move the the string function to seckey (and make it safe for future versions).

crmfcont.c, pk11akey.c, p12d.c, pk11pub.h, make the public function  PK11_GetPublicValueFromPublicKey to handle all the cases that needs to get the public value from the key.

several, propagate const for public_key caused by the above fix (all these cases were const all along, but not declared as such).

crmfcont.c, pk11akey.c pk11obj.c, pk11pub.h Add PK11_UnwrapPrivKeyByKeyType which find the PKCS #11 attributes by keyType and KeyUsage.

pk11mech.c, pk11skey.c secmodi.h The above uses existing pk11_mapXXXKeyType functions, regularize their names (private ones with lower case and public ones with upper case) and add the missing one (pk11_mapDeriveKeyType).

pk11skey.c Default the non derive keys to fail in PK11_PubDerive and PK11_PubDeriveWithKDF.

Differential Revision: https://phabricator.services.mozilla.com/D263781
moz-v2v-gh pushed a commit that referenced this pull request Sep 16, 2025
Prep - create a FindOidTagBy description function and replace all the one off in other libraries and tools in NSS.

Most uses are tooking for crypto algorithms, so in that case we'll filter by the existance of a PKCS #11 mechanism. The function can also take an optional len, so we do a strncmp. This allows comparing a substring .

Differential Revision: https://phabricator.services.mozilla.com/D263588
moz-v2v-gh pushed a commit that referenced this pull request Sep 16, 2025
move tls 1.3 to use streaming signatures rather than hash and sign.

Motivations

1) All the new signing algorithms use signatures that don't separate the signature portion from the hash portion. There are also cases where we want to use the combined hash-signature interfaces for our traditional signatures (some tokens only support the hash-signature interface).

2) the ssl_SignHashesWithPrivKey carry a lot of ssl3 and tls1.x x<=2 specific semantics that are no longer applies to tls1.3. TLS 1.3 redefined their signing algortithms so we we a full signature over the handshake hashes specifically to allow signing of the full tls hashes with streaming signatures.

3) secsign and secvfy already have the ability to determine if we need to do combined hash & sign or separate hash and sign.

This patch uses the SecAlgorithmID of the secsign and secvfy interfaces to do hash and sign. The use of SecAlgorithmID is useful in many other interfaces because the SecAlgorithmID is usually then sent directly to ASN.1 encoder, but that step is not necessary for SSL. I would be fine creatine new special SGN_NewContext and VFY_NewContext which just takes AlgTags and a PKCS #11 mechanism params. The latter is necessary for RSA PSS (there is already and interface that takes encoded params, but that's just one step closer to using full SECAlgorithmIDs).

The primary new tls functions are the tlsSignOrVerify interface, which can either sign or verify depending on the context. Using a combined interace allows us to keep the tls context encoding in a single common function and calling tls_SignOrVerifyUpdate() instead of the hashUpdate function. So tls13_AddContextToHashes becomes tls13_SignOrVerifyHashWithContext which either creates or verifies the signature (depending if we are signing or verifying).

This patch depends on https://phabricator.services.mozilla.com/D263657, but if we add new interfaces for SGN_NewContext and VFY_CreateContext that tke PKCS #11 mechanism parameters, that dependency can be dropped

Differential Revision: https://phabricator.services.mozilla.com/D263840
moz-v2v-gh pushed a commit that referenced this pull request Mar 31, 2026
Currently, NSS can only deal with ephemeral ml-kem kems. This is primarily because1 1) we currently only use ml-kem in ephemeral hybrid mode in TLS and IPSec. and 2) when we added the keys there were not oids or definitions for pkcs #12 transport of the keys.

Now our Certificate Server team needs to start using ML-KEM as a key transport key, which requires storing and moving the keys. They eventually want to store the keys in a certificate (which is a prereq for CMS/Smime usage).

This patch includes:
  1) updates to pk11table to add the remaining pkcs #11 v3.2 attributes that were missing
  2) Support for printing ML-KEM keys in secu_PrintSubjectPublicKeyInfo (so we can print certs with mlkem keys
  3) add ml-kem to the pk11importtest.c
  4) New internal functions to map OID, pkcs11, and internal version of ml-kem parameters.
  5) add ml-kem oids
  6) add missing kyberKey switches and ML-KEM-OID switches to seckey and pk11skey functions.
  7) ml-kem-512 to the NSS parsing. This patch does not add ml-kem-512 to softoken, so we can handle ml-kem-512 objects in NSS space, but softoken can't do anything with them.
  7) in softoken
      7a) add support of unwrapping private keys.
      7b) converting private keys to public keys.
      7c) saving the seed from the key.
      7d) regenerating a private key from the seed.
      7e) converting lowprivatekey and lowpublic key objects to and from pkcs #11 objects.
  8) add test cases (importing openssl generated ml-kem keys and certs)

  I did not update certutil to handle ml-kem CSRs because certutil can only handle signed CSRs and, of course, ml-kem can't sign anything.

Differential Revision: https://phabricator.services.mozilla.com/D286907
moz-v2v-gh pushed a commit that referenced this pull request Apr 1, 2026
1. add CKA_ENCAPSULATE to the mlDsaPubTemplate.
2. cadd code to detect runtime template overflows.

This is basically a sanity check. CKA_ENACAPSULATE isn't added to an mlDsa key because currently we only add CKA_ENCAPSULATE when we set it to true because the attribute is new for PKCS #11 3.2, so most tokens won't understand it. mlDsa will have the attribute set to false because it's a signing key, we never actually added it to the template. Putting it in, and expecially, checking that we haven't overrun out key template will guard against when we decide to include CKA_ENCAPSULATE unconditionally.

Differential Revision: https://phabricator.services.mozilla.com/D284477

--HG--
extra : rebase_source : cb0d93137e10a8edba1df395a0b95ba526352449
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants