PKCS#11 (Cryptoki) client with a typed core and a dlopen driver
README.md

ocaml-pkcs11 #

A PKCS#11 (Cryptoki) client for OCaml.

A release signing key should live in a token that never lets it out. In production that token is a hardware security module or a smart card; in development it can be a software token such as SoftHSM2. PKCS#11 is the standard interface to every one of them, and nox-pkcs11 speaks it from OCaml through typed values, so no raw C structure reaches the caller.

The opam package is called nox-pkcs11 because pkcs11 on opam belongs to Cryptosense's bindings. The OCaml library it exposes is Pkcs11.

The package ships three libraries. The core, nox-pkcs11, does no I/O. It defines typed return values (Rv), object attributes (Attribute), mechanisms (Mechanism), slot, token and session descriptions, and RFC 7512 pkcs11: URIs (Uri). It also defines the Pkcs11.S module type, which is the part of the Cryptoki function list needed to enumerate tokens, manage sessions and objects, and sign.

Two libraries implement Pkcs11.S. The driver, nox-pkcs11.dl, loads a vendor PKCS#11 module (libsofthsm2.so, OpenSC, a vendor HSM library) with dlopen, through hand-written C stubs and without ctypes. Its calls release the OCaml runtime lock, so a slow token does not stall other domains. nox-pkcs11.fake is an in-memory token written in OCaml, with the specification's session state machine, an object store and the EC signing mechanisms. Code written against Pkcs11.S can be tested on it without hardware.

Cryptoki in one paragraph #

PKCS#11 (OASIS, v3.0) defines a C ABI. An application dlopens a vendor module, gets its CK_FUNCTION_LIST and calls the C_* entry points in it. Each token sits in a slot. The application opens a session on the token and logs in with a PIN. It then finds objects such as keys and certificates by matching an attribute template, and runs mechanisms such as CKM_ECDSA against their handles. The private key stays in the token, and the signature is computed there.

Installation #

Install with opam:

$ opam install nox-pkcs11

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-pkcs11

Example #

The same code drives hardware and the in-memory token. This example uses the fake, set up the way factory hardware is: C_InitToken as the security officer, then C_InitPIN for the user.

# Crypto_rng_unix.use_default ()
- : unit = ()
# open Pkcs11
# let m = Pkcs11_fake.v ()
val m : Pkcs11_fake.t = <abstr>
# let session =
    let ( let* ) = Result.bind in
    Result.get_ok
      (let* () = Pkcs11_fake.initialize m in
       let* slot =
         Result.map List.hd (Pkcs11_fake.slots m ~token_present:true)
       in
       let* () =
         Pkcs11_fake.init_token m slot ~so_pin:"so-pin" ~label:"demo"
       in
       let* s = Pkcs11_fake.open_session m slot ~read_write:true in
       let* () = Pkcs11_fake.login m s User_type.So ~pin:"so-pin" in
       let* () = Pkcs11_fake.init_pin m s ~pin:"1234" in
       let* () = Pkcs11_fake.logout m s in
       let* () = Pkcs11_fake.login m s User_type.User ~pin:"1234" in
       Ok s)
val session : Session.t = <abstr>
# let _public, key =
    Result.get_ok
      (Pkcs11_fake.generate_key_pair m session Mechanism.Ec_key_pair_gen
         ~public_template:[ Attribute.Ec_params (Ec.der_of_curve Ec.P256) ]
         ~private_template:[ Attribute.Label "release-key" ])
val _public : Object_handle.t = <abstr>
val key : Object_handle.t = <abstr>
# match Pkcs11_fake.sign m session Mechanism.Ecdsa_sha256 ~key "hello" with
  | Ok raw -> `Signature_bytes (String.length raw)
  | Error rv -> `Failed (Rv.name rv)
- : [> `Failed of string | `Signature_bytes of int ] = `Signature_bytes 64

An RFC 7512 URI names a key as text:

# match
    Uri.of_string "pkcs11:token=demo;object=release-key;type=private"
  with
  | Ok uri -> uri.Uri.object_label
  | Error (`Msg _) -> None
- : string option = Some "release-key"

On hardware, only the module changes. Once Pkcs11_dl.load returns, the calls are the same Pkcs11.S interface as in the example above.

# let with_module path f =
    match Pkcs11_dl.load path with
    | Error (`Msg _) as e -> e
    | Ok m ->
        Fun.protect ~finally:(fun () -> Pkcs11_dl.unload m) (fun () -> f m)
val with_module :
  string ->
  (Pkcs11_dl.t -> ('a, [> `Msg of string ] as 'b) result) -> ('a, 'b) result =
  <fun>

Testing #

The unit suites run against nox-pkcs11.fake and need no hardware. The driver's integration suite looks for a SoftHSM2 module in the Homebrew and Debian paths, or the one PKCS11_TEST_MODULE names, and skips itself when it finds none.

  • cryptosense/pkcs11 types the whole PKCS#11 API in OCaml, and its pkcs11-driver binds it with ctypes. This library types only what key management and signing need, and binds it with hand-written stubs, so it does not depend on ctypes.
  • p11-kit is the module loader and RPC layer of the C ecosystem. A client written purely in OCaml could speak its socket protocol, but that protocol is an undocumented detail of p11-kit. This library binds the standard C ABI instead.
  • SoftHSM2 is the software token the integration tests run against.

License #

ISC. See LICENSE.md.