nethsm

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

README

Go library for NetHSM

This is a Go library for working with the 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 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 is almost complete, but does not yet support tags for keys and descryption for asymmetric keys. These will be implemented if or when the need arises, but at the time of writing we have no use cases.

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")
)

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          string
	Password          string
	APIURL            string
	ServerCertificate []byte
	TLSMode           TLSMode
}

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.

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) 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) 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) 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

TODO(borud): should replace the api.UserData return value with a type from this package

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) 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 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 command
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