nethsm

package module
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

README

Go library for Nitrokey NetHSM

Go Reference

This is a Go library for working with the Nitrokey NetHSM. It provides a wrapper around the API types that are generated from the OpenAPI specification to make life a bit easier for those using Nitrokey NetHSM.

WARNING

Note that this is a work in progress. The API will have breaking changes before this reaches release version v1.0.0 so use this at your own risk.

Generated Types

Where it makes sense we use the generated types in the API rather than create our own. This results in less code to maintain, but may break things when new versions of the OpenAPI spec is published.

Usage example

This example shows how to get information about the NetHSM instance, create a key, get its public key and then remove it. Examples can be found in the examples directory.

package main

import (
    "log/slog"

    "github.com/borud/nethsm"
    "github.com/borud/nethsm/api"
)

func main() {
    session := nethsm.Session{
        Username:      "admin",
        Password:      "verysecret",
        APIURL:        "https://127.0.0.1:8443/api/v1",
        TLSMode:  nethsm.TLSModeSkipVerify,
    }

    // Get information about vendor and product
    info, err := session.GetInfo()
    if err != nil {
        slog.Error("error getting info", "err", err)
        return
    }
    slog.Info("Information about NetHSM", "product", info.Product, "vendor", info.Vendor)

    // Create an RSA key
    rsaKeyID := "myRSAKey"
    err = session.GenerateKey(
        rsaKeyID,
        api.KEYTYPE_RSA,
        []api.KeyMechanism{api.KEYMECHANISM_RSA_SIGNATURE_PSS_SHA512},
        2048)
    if err != nil {
        slog.Error("error creating key", "keyID", rsaKeyID, "err", err)
        return
    }
    slog.Info("created key", "keyID", rsaKeyID)

    // Get public key
    pub, err := session.GetPublicKey(rsaKeyID)
    if err != nil {
        slog.Error("error fetching public key", "keyID", rsaKeyID, "err", err)
        return
    }
    slog.Info("fetched public key", "keyID", rsaKeyID, "publicKey", pub)

    // Delete key
    err = session.DeleteKey(rsaKeyID)
    if err != nil {
        slog.Error("failed to delete key", "keyID", rsaKeyID, "err", err)
    }
    slog.Info("deleted key", "keyID", rsaKeyID)
}

Completeness

This library does not support

  • Tags
  • Network configuration
  • Reboot
  • Software update

Documentation

Overview

Package nethsm provides more convenient client library for the NetHSM

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrParsingPEM              = errors.New("error parsing PEM block")
	ErrPEMBlockNotCSR          = errors.New("PEM block was not a Certificate Signing Request")
	ErrParsingCSR              = errors.New("error parsing Certificate Signing Request")
	ErrInvalidCSRSignature     = errors.New("invalid Certificate Signing Request signature")
	ErrInvalidSigningAlgorithm = errors.New("invalid signature algorithm")
	ErrFailedToCreatePipe      = errors.New("failed to create pipe")
	ErrReadingCertificate      = errors.New("error reading certificate")
	ErrKeyIDTooShort           = errors.New("keyID is too short")
	ErrKeyIDTooLong            = errors.New("keyID is too long")
	ErrInvalidKeyID            = errors.New("invalid keyID, must match regexp " + keyIDRegexpString)
	ErrUnknownPublicKeyType    = errors.New("unknown public key type")
	ErrDecodingRSAPublicKey    = errors.New("error decoding RSA key public key")
	ErrDecodingECPublicKey     = errors.New("error decoding EC key public key")
	ErrDecodingEDPublicKey     = errors.New("error decoding ED key public key")
	ErrNotSupported            = errors.New("operation not supported for key")
	ErrNotECDSAPublicKey       = errors.New("not an ECDSA public key")
	ErrNotED25519PublicKey     = errors.New("not an ED25519 public key")
	ErrGeneratingSerialNumber  = errors.New("error generating serial number")
	ErrSerialTooShort          = errors.New("serial must be at least 64 bits")
	ErrSerialTooLong           = errors.New("serial must be 160 bits or less")
	ErrBase64Decode            = errors.New("error decoding base64")
	ErrInitialVectorMismatch   = errors.New("initial vector mismatch")
	ErrUnsupportedAlgorithm    = errors.New("unsupported algorithm")
	ErrAddingTLSCertificate    = errors.New("error adding TLS certificate")
	ErrTLSCertificateMismatch  = errors.New("NetHSM server TLS certificate mismatch")
	ErrUserCreateFailed        = errors.New("failed to create user")
	ErrUserGetFailed           = errors.New("failed to get user")
	ErrUserDeleteFailed        = errors.New("failed to delete user")
	ErrUsersListFailed         = errors.New("failed to list users")
)

Errors for nethsm package.

Functions

func GenerateSerialNumber added in v0.1.2

func GenerateSerialNumber(nbits ...uint) (*big.Int, error)

GenerateSerialNumber to be used in certificates. Produces a random *big.Int serial number. Optionally you can specify the number of bits to be used in the serial. The default length is defined by defaultSerialNumBits (128).

Collision probability for random values from crypto/rand follows the Birthday Problem: - 64-bit: A collision is likely after ~5 billion values. - 128-bit: A collision is likely after ~22 quintillion values. - 160-bit: Likely collision after ~1.5 x 10^24 values.

In practice 128 bit serial numbers should be safe to use for serial numbers.

func ValidateKeyID added in v0.1.2

func ValidateKeyID(id string) error

ValidateKeyID to make sure the key conforms to the NetHSM requirements referred here:

<https://nethsmdemo.nitrokey.com/api_docs/index.html#/default/post_keys_generate>

Types

type CSRSigningParameters added in v0.1.2

type CSRSigningParameters struct {
	SelfSign           bool
	SignatureAlgorithm x509.SignatureAlgorithm
	SigningKeyID       string
	CSRPEM             string
	KeyUsage           x509.KeyUsage
	ExtKeyUsage        []x509.ExtKeyUsage
	NotBefore          time.Time
	NotAfter           time.Time
	IsCA               bool
	MaxPathLen         int
	MaxPathLenZero     bool
}

CSRSigningParameters are the signing parameters for signing a CSR.

type Session added in v0.1.2

type Session struct {
	// Username we are logging into the NetHSM as.
	Username string
	// Password for the user we are logging in as
	Password string
	// APIURL of the NetHSM endpoint
	APIURL string
	// Server certificate of the NetHSM
	ServerCertificate []byte
	// TLSMode sets how we verify the server certificate
	TLSMode TLSMode
	// SSHTunnel is a list of hops on the form <username>@<host>:<sshport> to allow
	// for tunneling through intermediate hosts
	SSHTunnel []string
}

Session is a NetHSM session.

func (*Session) AddNamespace added in v0.1.2

func (s *Session) AddNamespace(name string) error

AddNamespace creates a namespace identified by name

func (*Session) AddUser added in v0.1.2

func (s *Session) AddUser(userID string, realname string, role string, passphrase string) error

AddUser creates a new user.

TODO(borud): replace role string type with api.UserRole

func (*Session) Backup added in v0.1.5

func (s *Session) Backup() (*os.File, error)

Backup initiates backup.

func (*Session) CreateCertificate added in v0.1.2

func (s *Session) CreateCertificate(param CSRSigningParameters) (string, error)

CreateCertificate is used to create a certificate given CertificateParameters. Note that you have to be careful about correctly populating the parameters. If you make a root CA you should not include ExtKeyUsage.

func (*Session) DecryptSymmetric added in v0.1.2

func (s *Session) DecryptSymmetric(keyID string, encipheredMessage []byte, initialVector []byte) ([]byte, error)

DecryptSymmetric decrypts enciphered message usig the key identified by keyID. This function takes care of unpadding the data before returning it.

func (*Session) DeleteCertificate added in v0.1.2

func (s *Session) DeleteCertificate(keyID string) error

DeleteCertificate deletes a certificate from the NetHSM

func (*Session) DeleteKey added in v0.1.2

func (s *Session) DeleteKey(keyID string) error

DeleteKey deletes a key from the NetHSM

func (*Session) DeleteNamespace added in v0.1.2

func (s *Session) DeleteNamespace(name string) error

DeleteNamespace removes a namespace identified by name.

func (*Session) DeleteUser added in v0.1.2

func (s *Session) DeleteUser(userID string) error

DeleteUser deletes user identified by userID.

func (*Session) EncryptSymmetric added in v0.1.2

func (s *Session) EncryptSymmetric(keyID string, message []byte, initialVector []byte) ([]byte, error)

EncryptSymmetric is used to encrypt data using a symmetric (AES) key identified by keyID. The only mode available is CBC. This function takes care of padding the data using blocksize of 16.

func (*Session) FactoryReset added in v0.1.7

func (s *Session) FactoryReset() error

FactoryReset performs a factory reset on the NetHSM. Use with care!

func (*Session) GenerateCSR added in v0.1.2

func (s *Session) GenerateCSR(keyID string, subject pkix.Name, email string) (string, error)

GenerateCSR for key identified by keyID with subject and email. We return the CSR as a string in PEM format since that is usually the most practical format users of this library will be interested in.

func (*Session) GenerateCSRUsingGoStdlib added in v0.1.7

func (s *Session) GenerateCSRUsingGoStdlib(keyID string, subject pkix.Name, email string, alg x509.SignatureAlgorithm) (string, error)

GenerateCSRUsingGoStdlib for key identified by keyID with subject and email. We return the CSR as a string in PEM format since that is usually the most practical format users of this library will be interested in.

This variant uses the Go standard library to create the certificate request rather than the CSR generation endpoint of the NetHSM. This is due to certain differences in how the NetHSM and the Go standard library encodes the subject/dn.

func (*Session) GenerateKey added in v0.1.2

func (s *Session) GenerateKey(keyID string, keyType api.KeyType, keyMechanisms []api.KeyMechanism, length int32) error

GenerateKey generates a key.

func (*Session) GenerateTLSCSR added in v0.1.2

func (s *Session) GenerateTLSCSR(dn api.DistinguishedName) (string, error)

GenerateTLSCSR generates a certificate signing request for the TLS key.

func (*Session) GenerateTLSKey added in v0.1.2

func (s *Session) GenerateTLSKey(keyType api.TlsKeyType, length int32) error

GenerateTLSKey generates a TLS key for the NetHSM.

func (*Session) GetCertificate added in v0.1.2

func (s *Session) GetCertificate(keyID string) (string, error)

GetCertificate returns the certificate for a given keyID

func (*Session) GetHealthAlive added in v0.1.2

func (s *Session) GetHealthAlive() (bool, error)

GetHealthAlive returns true if the NetHSM is alive, but not ready to accept traffic (implies Locked or Unprovisioned)

func (*Session) GetHealthReady added in v0.1.2

func (s *Session) GetHealthReady() (bool, error)

GetHealthReady returns true if the NetHSM is to accept traffic (implies "Operational" state)

func (*Session) GetHealthState added in v0.1.2

func (s *Session) GetHealthState() (api.SystemState, error)

GetHealthState of the NetHSM

func (*Session) GetInfo added in v0.1.2

func (s *Session) GetInfo() (*api.InfoData, error)

GetInfo returns vendor, product and an optional error.

func (*Session) GetKey added in v0.1.4

func (s *Session) GetKey(keyID string) (*api.PublicKey, error)

GetKey fetches the (public) key for keyID and returns the api.PublicKey type.

func (*Session) GetPublicKey added in v0.1.2

func (s *Session) GetPublicKey(keyID string) (crypto.PublicKey, error)

GetPublicKey fetches the public key for keyID from NetHSM.

func (*Session) GetTLSCertificate added in v0.1.2

func (s *Session) GetTLSCertificate() (string, error)

GetTLSCertificate retrieves the TLS Certificate for the NetHSM.

func (*Session) GetUser added in v0.1.2

func (s *Session) GetUser(userID string) (*api.UserData, error)

GetUser gets the user data for user identified by userID

func (*Session) ListKeys added in v0.1.2

func (s *Session) ListKeys() ([]string, error)

ListKeys returns an array of key names.

func (*Session) ListNamespaces added in v0.1.2

func (s *Session) ListNamespaces() ([]string, error)

ListNamespaces lists the available namespaces

func (*Session) ListUsers added in v0.1.2

func (s *Session) ListUsers() ([]string, error)

ListUsers lists usernames. If the namespace is set it lists the users for that namespace.

func (*Session) Lock added in v0.1.2

func (s *Session) Lock() error

Lock the NetHSM

func (*Session) Provision added in v0.1.2

func (s *Session) Provision(unlockPass string, adminPass string) error

Provision the NetHSM and set unlock and admin passphrases.

func (*Session) Restore added in v0.1.5

func (s *Session) Restore(backupPass string, backupFile *os.File) error

Restore backup from file.

func (*Session) SetBackupPassword added in v0.1.5

func (s *Session) SetBackupPassword(newPass, currentPass string) error

SetBackupPassword sets the backup password. If no password was set then provide the empty string for currentPass.

func (*Session) SetCertificate added in v0.1.2

func (s *Session) SetCertificate(keyID string, certPEM []byte) error

SetCertificate uploads a certificate for a given keyID.

func (*Session) SetTLSCertificate added in v0.1.2

func (s *Session) SetTLSCertificate(pem string) error

SetTLSCertificate sets the TLS certificate for the NetHSM.

func (*Session) Sign added in v0.1.2

func (s *Session) Sign(keyID string, signatureAlgorithm x509.SignatureAlgorithm, digest []byte) (string, error)

Sign the digest using the key with id keyID using signing mode given by signMode.

Valid values for signatureAlgorithm are:

  • x509.ECDSAWithSHA1
  • x509.ECDSAWithSHA256
  • x509.ECDSAWithSHA384
  • x509.ECDSAWithSHA512
  • x509.PureEd25519
  • x509.SHA256WithRSAPSS
  • x509.SHA384WithRSAPSS
  • x509.SHA512WithRSAPSS

func (*Session) UnLock added in v0.1.2

func (s *Session) UnLock(unlockPassphrase string) error

UnLock the NetHSM

type Signer added in v0.1.7

type Signer struct {
	KeyID              string
	SignatureAlgorithm x509.SignatureAlgorithm
	Session            *Session
}

Signer provides a crypto.Signer interface.

func (*Signer) Public added in v0.1.7

func (h *Signer) Public() crypto.PublicKey

Public returns the public key.

func (*Signer) Sign added in v0.1.7

func (h *Signer) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign signs the digest.

type TLSMode added in v0.1.2

type TLSMode uint8

TLSMode specifies what TLS checking we are going to do.

const (
	// TLSModeDefault uses the secure system defaults for TLS verification.
	TLSModeDefault TLSMode = iota
	// TLSModeSkipVerify skips verification of server certificate completely.
	TLSModeSkipVerify
	// TLSModeWithoutSANCheck ensures the server certificate provided in
	// ServerCertificate checks out, but makes no further verifications. This
	// is used to get around missing SAN fields.
	TLSModeWithoutSANCheck
)

Directories

Path Synopsis
Package dockerhsm provides a way to fire up the NetHSM docker image for use in tests.
Package dockerhsm provides a way to fire up the NetHSM docker image for use in tests.
examples
basic
Package main contains a basic example of how to use the NetHSM library.
Package main contains a basic example of how to use the NetHSM library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL