ykpiv

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2019 License: MIT Imports: 17 Imported by: 0

README

go-ykpiv

go-ykpiv is a high level cgo wrapper around libykpiv.so.1 that implements an idiomatic go API fit for use when applications need to communicate with a Yubikey in PIV mode.

What's PIV?

PIV Cards are cards defined by FIPS 201, a Federal US Government standard defining the ID cards employees use. At its core, it's a set of x509 Certificates and corresponding private keys in a configuration that is standardized across implementations.

For more details on how PIV Tokens can be used, the FICAM (Federal Identity, Credential, and Access Management) team at GSA (General Services Administration) has published some guides on GitHub under GSA/piv-guides

How is this different than OpenSC?

Most PIV tokens, Yubikeys included, can be used as a PKCS#11 device using OpenSC, and Yubikeys are even capable of doing Signing and Decryption through that interface. However, some management functions are not exposed in the PKCS#11 OpenSC interface, so this library may be of use when one wants to write a new Certificate, or set PINs.

Development

Testing

To run the tests, you'll need to find a Yubikey that you're willing to wipe clean, and destroy all data on it. After you've found such a key, remove all other Yubikeys from your machine.

The tests will panic if the YKPIV_YES_DESTROY_MY_KEY environment variable is unset.

Running the tests will reset your Yubikey a few times (once per test), and you will wind up with a key with the default PIN, PUK and Management Key.

Installation

Debian

sudo apt install build-essential libykpiv-dev
go get github.com/artemisc/go-ykpiv

MacOS X

brew install yubico-piv-tool
go get github.com/artemisc/go-ykpiv

Examples

package main

import (
	"fmt"

	"github.com/artemisc/go-ykpiv"
)

func main() {
	yubikey, err := ykpiv.New(ykpiv.Options{
		// Verbose: true,
		Reader: "Yubico Yubikey NEO U2F+CCID 01 00",
	})
	if err != nil {
		panic(err)
	}
	defer yubikey.Close()

	version, err := yubikey.Version()
	if err != nil {
		panic(err)
	}
	fmt.Printf("Application version %s found.\n", version)
}

Running on Windows

  1. Download yubico-piv-tool-1.7.0-win64.zip from the official site
  2. Create directory win in the root of the project
  3. Copy lib and include directories from the downloaded archive to the win directory
  4. Copy all DLLs from the bin directory in the archive to the root of your project
  5. Copy libwinpthread-1.dll from C:\TDM-GCC-64\bin to the root of your project

LICENSE

Copyright (c) Paul R. Tagliamonte <paultag@gmail.com>, 2017

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	TouchPolicyNull   TouchPolicy = 0
	TouchPolicyNever              = TouchPolicy(C.YKPIV_TOUCHPOLICY_NEVER)
	TouchPolicyAlways             = TouchPolicy(C.YKPIV_TOUCHPOLICY_ALWAYS)
	TouchPolicyCached             = TouchPolicy(C.YKPIV_TOUCHPOLICY_CACHED)
)
View Source
const (
	PinPolicyNull   PinPolicy = 0
	PinPolicyNever            = PinPolicy(C.YKPIV_PINPOLICY_NEVER)
	PinPolicyOnce             = PinPolicy(C.YKPIV_PINPOLICY_ONCE)
	PinPolicyAlways           = PinPolicy(C.YKPIV_PINPOLICY_ALWAYS)
)

Variables

View Source
var (
	MemoryError         = Error{Code: C.YKPIV_MEMORY_ERROR, Message: "Memory Error"}
	PCSCError           = Error{Code: C.YKPIV_PCSC_ERROR, Message: "PKCS Error"}
	SizeError           = Error{Code: C.YKPIV_SIZE_ERROR, Message: "Size Error"}
	AppletError         = Error{Code: C.YKPIV_APPLET_ERROR, Message: "Applet Error"}
	AuthenticationError = Error{Code: C.YKPIV_AUTHENTICATION_ERROR, Message: "Authentication Error"}
	RandomnessError     = Error{Code: C.YKPIV_RANDOMNESS_ERROR, Message: "Randomness Error"}
	GenericError        = Error{Code: C.YKPIV_GENERIC_ERROR, Message: "Generic Error"}
	KeyError            = Error{Code: C.YKPIV_KEY_ERROR, Message: "Key Error"}
	ParseError          = Error{Code: C.YKPIV_PARSE_ERROR, Message: "Parse Error"}
	WrongPIN            = Error{Code: C.YKPIV_WRONG_PIN, Message: "Wrong PIN"}
	InvalidObject       = Error{Code: C.YKPIV_INVALID_OBJECT, Message: "Invalid Object"}
	AlgorithmError      = Error{Code: C.YKPIV_ALGORITHM_ERROR, Message: "Algorithm Error"}
	PINLockedError      = Error{Code: C.YKPIV_PIN_LOCKED, Message: "PIN Locked"}

	SecurityStatusError = Error{Code: C.SW_ERR_SECURITY_STATUS, Message: "Security Status Error"}
	AuthBlocked         = Error{Code: C.SW_ERR_AUTH_BLOCKED, Message: "Auth Blocked"}
	IncorrectParam      = Error{Code: C.SW_ERR_INCORRECT_PARAM, Message: "Incorrect Param"}
	IncorrectSlot       = Error{Code: C.SW_ERR_INCORRECT_SLOT, Message: "Incorrect Slot"}
)

Functions

func Readers

func Readers() ([]string, error)

Get a list of strings that the ykpiv library has identified as unique ways to fetch every reader attached to the system. This can be handy to define a "Reader" argument in ykpiv.Options, and may include things ykpiv can't talk to.

func VerifyAttestation

func VerifyAttestation(attestationCert, attestedCert *x509.Certificate) ([][]*x509.Certificate, error)

Verify that the attestion certificate is correctly signed by the Yubikey root (provided with this package), as well as verifying that the Attestion Certificate is signed by that slot correctly.

The `attestationCert` is the Certificate from the Yubikey Attestion slot, signed by the Yubico roots.

The `attestedCert` is the Certificate signed by the Attestion slot asserting that the public key was generated on-chip.

Types

type AttestionCertificate

type AttestionCertificate struct {
	x509.Certificate

	// Version of the Yubikey Firmware that generated this key.
	FirmwareVersion *[3]byte

	// Serial Number of the Yubikey in question.
	SerialNumber *int

	//
	PinPolicy   *byte
	TouchPolicy *byte
}

Struct with an anonymous member (`x509.Certificate`) that allows you to both access the regular fields for ease of use, as well as handle the Yubikey particular fields.

func NewAttestionCertificate

func NewAttestionCertificate(cert *x509.Certificate) (*AttestionCertificate, error)

Parse the Yubikey specific Extensions from the x509.Certificate, and place them into a struct for use by end users.

type Error

type Error struct {

	// int representing the underlying error code as ykpiv had given us. The
	// exact numbers can be found in your local ykpiv.h, inside the ykpiv_rc
	// enum.
	Code int

	// Human readable message regarding what happened.
	Message string
	// contains filtered or unexported fields
}

Go wrapper around the internal C ykpiv error integers. Error codes as they exist in ykpiv.h are brought into Go, since we can add some additional context around them, as well as implement the Error interface.

func (Error) Equal

func (e Error) Equal(err error) bool

Check to see if another Error is the same as our struct. This compares the underlying Code integer.

func (Error) Error

func (e Error) Error() string

Error interface. This will sprintf a string containing where this error came from, the human message, and the underlying ykpiv code, to aid with debugging.

type Options

type Options struct {

	// When true, this will cause the underlying ykpiv library to emit additional
	// information to stderr. This can be helpful when debugging why something
	// isn't working as expected.
	Verbose bool

	// String to be used when searching for a Yubikey. The comparison
	// will be against the output you can observe from
	// `yubico-piv-tool -a list-readers`.
	Reader string

	// PIN is the pin that will be used when logging in
	PIN *string

	// PUK is the PUK to be used when logging in
	PUK *string

	// ManagementKey is the Management Key to be used for key operations
	ManagementKey []byte

	// Flag to let ykpiv know if this PIV token has a ManagementKey that was
	// set by pivman, which is a PBKDF2 SHA1 key derived with a salt held on
	// chip in the internal pivman data.
	//
	// If this is `true`, ManagementKey will be ignored in favor of deriving
	// the key from the PIN.
	ManagementKeyIsPIN bool
}

Configuration for initialization of the Yubikey, as well as options that may be used during runtime.

func (Options) GetManagementKey

func (o Options) GetManagementKey(y Yubikey) ([]byte, error)

Get the Management Key.

On some configurations, users have set the Management Key to a PBKDF2 SHA1 key derived from the PIN, so this may return one of two things:

If `ManagementKeyIsPIN` is false, the `ManagementKey` byte array will be returned.

If `ManagementKeyIsPIN` is true, the `PIN` will be used, in conjunction with a salt held within the PIVMON object address to compute the ManagementKey. If PIN is nil, this will result in an error being returned.

func (Options) GetPIN

func (o Options) GetPIN() (string, error)

Get the user defined PIN. This will return an error if PUK is nil.

func (Options) GetPUK

func (o Options) GetPUK() (string, error)

Get the user defined PUK. This will return an error if PUK is nil.

type PinPolicy

type PinPolicy byte

type Slot

type Slot struct {
	Id          SlotId
	PublicKey   crypto.PublicKey
	Certificate *x509.Certificate
	// contains filtered or unexported fields
}

Slot abstracts a public key, private key, and x509 Certificate stored on the PIV device.

Internally, this keeps track of the Yubikey this came from, the underlying object identifiers for the Certificate and Key we care about, as well as other bits and bobs of state.

func (Slot) Attest

func (y Slot) Attest() (*x509.Certificate, error)

Attest the key in this slot and get the attestation certificate

func (Slot) Decrypt

func (s Slot) Decrypt(rand io.Reader, msg []byte, opts crypto.DecrypterOpts) ([]byte, error)

Decrypt decrypts ciphertext with the private key backing the Slot we're operating on. This implements the crypto.Decrypter interface.

The `rand` argument is disregarded in favor of the on-chip RNG on the Yubikey The `opts` argument is not used at this time, but may in the future.

func (Slot) GetCertificate

func (y Slot) GetCertificate() (*x509.Certificate, error)

Get the x509.Certificate stored in the PIV Slot off the chip

func (Slot) Public

func (s Slot) Public() crypto.PublicKey

Return the crypto.PublicKey that we know corresponds to the Certificate we have on hand.

func (Slot) Sign

func (s Slot) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign implements the crypto.Signer.Sign interface.

Unlike other Sign implementations, `rand` will be completely discarded in favor of the on-chip RNG.

The output will be a PKCS#1 v1.5 signature (for RSA) or ECDSA signature (for EC keys) over the digest.

func (Slot) TLSCertificate

func (slot Slot) TLSCertificate() tls.Certificate

Create a tls.Certificate fit for use in crypto/tls applications, such as net/http, or grpc.

func (*Slot) Update

func (y *Slot) Update(cert x509.Certificate) error

Write the x509 Certificate to the Yubikey.

type SlotId

type SlotId struct {
	Certificate int32
	Key         int32
	Name        string
}

SlotId encapsulates the Identifiers required to preform key operations on the Yubikey. The identifier most people would know (if this is a thing that people do who don't write PIV aware applications) would be the `Key` Id, something like 0x9A.

var (
	// PIV Authentication, which is a certificate and key pair and can be used
	// to verify that the PIV credential was issued by an authorized entity,
	// has not expired, has not been revoked, and holder of the credential
	// (YOU) is the same individual it was issued to.
	Authentication SlotId = SlotId{
		Certificate: C.YKPIV_OBJ_AUTHENTICATION,
		Key:         C.YKPIV_KEY_AUTHENTICATION,
		Name:        "Authentication",
	}

	// Digital Signature, which is a certificate and key pair allows the YOU to
	// digitally sign a document or email, providing both integrity and
	// non-repudiation.
	Signature SlotId = SlotId{
		Certificate: C.YKPIV_OBJ_SIGNATURE,
		Key:         C.YKPIV_KEY_SIGNATURE,
		Name:        "Digital Signature",
	}

	// Card Authentication, which is a certificate and key pair that can be
	// used to verify that the PIV credential was issued by an authorized
	// entity, has not expired, and has not been revoked.
	CardAuthentication SlotId = SlotId{
		Certificate: C.YKPIV_OBJ_CARD_AUTH,
		Key:         C.YKPIV_KEY_CARDAUTH,
		Name:        "Card Authentication",
	}

	KeyManagement SlotId = SlotId{
		Certificate: C.YKPIV_OBJ_KEY_MANAGEMENT,
		Key:         C.YKPIV_KEY_KEYMGM,
		Name:        "Key Management",
	}

	// Attestation, which contains a certificate issued by the Yubico CA
	// and can be used to attest keys generated in the other slots.
	// Requires YubiKey 4.3 or later.
	// NB: if this key or cert is overwritten it cannot be brought back!
	Attestation SlotId = SlotId{
		Certificate: C.YKPIV_OBJ_ATTESTATION,
		Key:         C.YKPIV_KEY_ATTESTATION,
		Name:        "Attestation",
	}
)

More information regarding the basic PIV slots can be founnd at the FICAM piv-gude: https://piv.idmanagement.gov/elements/

func (SlotId) String

func (s SlotId) String() string

Return a human readable string mostly useful for debugging which Slot you might have your hands on. Since most people (for some value of "most") would want the Key, this only includes that.

type TouchPolicy

type TouchPolicy byte

type Yubikey

type Yubikey struct {
	// contains filtered or unexported fields
}

Encapsulation of the ykpiv internal state object, and the configuration in new. This needs to be initalized through `ykpiv.New` to ensure the internal state is brought up correctly.

This object represents a single physical yubikey that we've connected to. This object provides a number of helper functions hanging off the struct to avoid keeping and passing the internal ykpiv state object in C.

`.Close()` must be called, or this will leak memory.

func New

func New(opts Options) (*Yubikey, error)

Create a new Yubikey.

This will use the options in the given `ykpiv.Options` struct to find the correct Yubikey, initialize the underlying state, and ensure the right bits are set.

func (Yubikey) Attest

func (y Yubikey) Attest(slotId SlotId) (*x509.Certificate, error)

Attest returns an *x509.Certificate attesting the key in slotId. Use it with the attestation certificate in the Attestation slot and the Yubico PIV Root CA certificate to verify attestation.

func (Yubikey) Authenticate

func (y Yubikey) Authenticate() error

Authenticate to the Yubikey using the Management Key. This key is a 24 byte key that's used as a 3DES key internally to write new Certificates, or create a new keypair.

func (Yubikey) Authentication

func (y Yubikey) Authentication() (*Slot, error)

Get the PIV Authentication Slot off the Yubikey. This is identical to invoking `yubikey.Slot(ykpiv.Authentication)`.

func (Yubikey) CardAuthentication

func (y Yubikey) CardAuthentication() (*Slot, error)

Get the PIV Card Authentication Slot off the Yubikey. This is identical to invoking `yubikey.Slot(ykpiv.CardAuthentication)`

func (Yubikey) ChangePIN

func (y Yubikey) ChangePIN(oldPin, newPin string) error

Change your PIN on the Yubikey from the oldPin to the newPin.

func (Yubikey) ChangePUK

func (y Yubikey) ChangePUK(newPuk string) error

Change the PUK.

func (Yubikey) Close

func (y Yubikey) Close() error

Close the Yubikey object, and preform any finization needed to avoid leaking memory or holding locks.

func (Yubikey) GenerateEC

func (y Yubikey) GenerateEC(slot SlotId, bits int) (*Slot, error)

func (Yubikey) GenerateECWithPolicies

func (y Yubikey) GenerateECWithPolicies(slot SlotId, bits int, pinPolicy PinPolicy, touchPolicy TouchPolicy) (*Slot, error)

func (Yubikey) GenerateRSA

func (y Yubikey) GenerateRSA(id SlotId, bits int) (*Slot, error)

Generate an RSA Keypair in slot `id` (using a modulus size of `bits`), and construct a Certificate-less Slot. This Slot can not be recovered later, so it should be used to sign a CSR or Self-Signed Certificate before we lose the key material.

func (Yubikey) GenerateRSAWithPolicies

func (y Yubikey) GenerateRSAWithPolicies(id SlotId, bits int, pinPolicy PinPolicy, touchPolicy TouchPolicy) (*Slot, error)

The same as GenerateRSAWithPolicies, but with additional parameters to specify the pin policy and touch policy to be assigned to the generated key.

func (Yubikey) GetCertificate

func (y Yubikey) GetCertificate(slotId SlotId) (*x509.Certificate, error)

func (Yubikey) GetObject

func (y Yubikey) GetObject(id int) ([]byte, error)

Get the raw bytes out of a slot stored on the Yubikey. Callers to this function should only do so if they understand exactly what data they're reading, what the data should look like, and avoid rebuilding existing interfaces if at all possible.

The related method, SaveObject, can be used to write data to be read back later. Care must be taken to ensure the `id` is *not* being used by any other applications.

func (Yubikey) ImportKey

func (y Yubikey) ImportKey(slotID SlotId, privKey crypto.PrivateKey) (*Slot, error)

ImportKey function imports a private key to the specified slot

func (Yubikey) KeyManagement

func (y Yubikey) KeyManagement() (*Slot, error)

Get the PIV Key Management Slot off the Yubikey. This is identical to invoking `yubikey.Slot(ykpiv.KeyManagement)`

func (Yubikey) Login

func (y Yubikey) Login() error

Log into the Yubikey using the user PIN.

func (Yubikey) PINRetries

func (y Yubikey) PINRetries() (int, error)

PIN Retries

func (Yubikey) Reset

func (y Yubikey) Reset() error

Reset the Yubikey.

This can only be done if both the PIN and PUK have been blocked, and will wipe all data on the Key. This includes all Certificates, public and private key material.

func (Yubikey) SaveCertificate

func (y Yubikey) SaveCertificate(slotId SlotId, cert x509.Certificate) error

Write the x509 Certificate to the Yubikey.

func (Yubikey) SaveObject

func (y Yubikey) SaveObject(id int32, data []byte) error

Write the raw bytes out of a slot stored on the Yubikey. Callers to this function should only do so if they understand exactly what data they're writnig, what the data should look like, and avoid rebuilding existing interfaces if at all possible.

The related method, GetObject, can be used to read data later. Care must be taken to ensure the `id` is *not* being used by any other applications.

func (Yubikey) Serial

func (y Yubikey) Serial() (uint32, error)

func (Yubikey) SetMGMKey

func (y Yubikey) SetMGMKey(key []byte) error

Set the Yubikey Management Key. The Management key is a 24 byte key that's used as a 3DES key internally to preform key operations, such as Certificate import, or keypair generation.

func (Yubikey) Signature

func (y Yubikey) Signature() (*Slot, error)

Get the Digital Signature Slot off the Yubikey. This is identical to invoking `yubikey.Slot(ykpiv.Signature)`

func (Yubikey) Slot

func (y Yubikey) Slot(id SlotId) (*Slot, error)

Get a Slot off of the Yubikey by the SlotId.

This will trigger an attempt to get (and parse) the x509 Certificate for this slot. Only slots with an x509 Certificate can be used.

func (Yubikey) UnblockPIN

func (y Yubikey) UnblockPIN(newPin string) error

Using the PUK, unblock the PIN, resetting the retry counter.

func (Yubikey) Version

func (y Yubikey) Version() ([]byte, error)

Return the ykpiv application version. This is expected to be in the format of '1.2.3', but is up to the underlying ykpiv application code.

Directories

Path Synopsis
cmd
internal

Jump to

Keyboard shortcuts

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