kmip

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: MIT Imports: 18 Imported by: 11

README

kmip-go GoDoc Go Report Card Build

kmip-go is a go implemenation of KMIP protocol primitives. It supports marshaling data in TTLV, XML, or JSON encodings to and from go values and structs. It can be used to implement KMIP clients or servers.

Installation

go get github.com/gemalto/kmip-go

Or, to just install the ppkmip pretty printing tool:

go install github.com/gemalto/kmip-go/cmd/ppkmip

Packages

The ttlv package implements the core encoder and decoder logic.

The kmip14 package contains constants for all the tags, types, enumerations and bitmasks defined in the KMIP 1.4 specification. It also contains mappings from these values to the normalized names used in the JSON and XML encodings, and the canonical names used in Attribute structures.
The kmip14 definitions are all automatically registered with ttlv.DefaultRegistry.

The kmip20 package adds additional enumeration values from the 2.0 specification. It is meant to be registered on top of the 1.4 definitions.

The root package defines golang structures for some of the significant Structure definitions in the 1.4 specification, like Attributes, Request, Response, etc. It is incomplete, but can be used as an example for defining other structures. It also contains an example of a client and server.

cmd/kmipgen is a code generation tool which generates the tag and enum constants from a JSON specification input. It can also be used independently in your own code to generate additional tags and constants. make install to build and install the tool. See kmip14/kmip_1_4.go for an example of using the tool.

cmd/kmipgen is a tool for pretty printing kmip values. It can accept KMIP input from stdin or files, encoded in TTLV, XML, or JSON, and output in a variety of formats. make install to intall the tool, and ppkmip --help to see usage.

Contributing

To build, be sure to have a recent go SDK, and make. Run make tools to install other dependencies.

There is also a dockerized build, which only requires make and docker-compose: make docker. You can also do make fish or make bash to shell into the docker build container.

Merge requests are welcome! Before submitting, please run make and make sure all tests pass and there are no linter findings.

Documentation

Overview

Package kmip is a general purpose KMIP library for implementing KMIP services and clients.

The ttlv sub package contains the core logic for parsing the KMIP TTLV encoding formats, and marshaling them to and from golang structs.

This package defines structs for many of the structures defined in the KMIP Spec, such as the different types of managed objects, request and response bodies, etc. Not all Structures are represented here yet, but the ones that are can be used as examples.

There is also a partial implementation of a server, and an example of a client. There is currently no Client type for KMIP, but it is simple to open a socket overwhich you send and receive raw KMIP requests and responses.

Example (Client)
conn, err := net.DialTimeout("tcp", "localhost:5696", 3*time.Second)
if err != nil {
	panic(err)
}

biID := uuid.New()

msg := kmip.RequestMessage{
	RequestHeader: kmip.RequestHeader{
		ProtocolVersion: kmip.ProtocolVersion{
			ProtocolVersionMajor: 1,
			ProtocolVersionMinor: 2,
		},
		BatchCount: 1,
	},
	BatchItem: []kmip.RequestBatchItem{
		{
			UniqueBatchItemID: biID[:],
			Operation:         kmip14.OperationDiscoverVersions,
			RequestPayload: kmip.DiscoverVersionsRequestPayload{
				ProtocolVersion: []kmip.ProtocolVersion{
					{ProtocolVersionMajor: 1, ProtocolVersionMinor: 2},
				},
			},
		},
	},
}

req, err := ttlv.Marshal(msg)
if err != nil {
	panic(err)
}

fmt.Println(req)

_, err = conn.Write(req)
if err != nil {
	panic(err)
}

buf := make([]byte, 5000)
_, err = bufio.NewReader(conn).Read(buf)
if err != nil {
	panic(err)
}

resp := ttlv.TTLV(buf)
fmt.Println(resp)
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultErrorHandler = ErrorHandlerFunc(func(err error) *ResponseBatchItem {
	reason := GetResultReason(err)
	if reason == kmip14.ResultReason(0) {

		return nil
	}

	msg := merry.UserMessage(err)
	if msg == "" {
		msg = merry.Message(err)
	}
	return newFailedResponseBatchItem(reason, msg)
})

DefaultErrorHandler tries to map errors to ResultReasons.

View Source
var DefaultOperationMux = &OperationMux{}
View Source
var DefaultProtocolHandler = &StandardProtocolHandler{
	MessageHandler: DefaultOperationMux,
	ProtocolVersion: ProtocolVersion{
		ProtocolVersionMajor: 1,
		ProtocolVersionMinor: 4,
	},
}
View Source
var ErrInvalidTag = errors.New("invalid tag")
View Source
var ErrServerClosed = errors.New("http: Server closed")

ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe, and ListenAndServeTLS methods after a call to Shutdown or Close.

Functions

func Details

func Details(err error) string

func GetResultReason

func GetResultReason(err error) kmip14.ResultReason

func WithResultReason

func WithResultReason(err error, rr kmip14.ResultReason) error

Types

type AttestationCredentialValue

type AttestationCredentialValue struct {
	Nonce                  Nonce
	AttestationType        kmip14.AttestationType
	AttestationMeasurement []byte `ttlv:",omitempty"`
	AttestationAssertion   []byte `ttlv:",omitempty"`
}

AttestationCredentialValue 2.1.2 Table 6

If the Credential Type in the Credential is Attestation, then Credential Value is a structure as shown in Table 6. The Nonce Value is obtained from the key management server in a Nonce Object. The Attestation Credential Object can contain a measurement from the client or an assertion from a third party if the server is not capable or willing to verify the attestation data from the client. Neither type of attestation data (Attestation Measurement or Attestation Assertion) is necessary to allow the server to accept either. However, the client SHALL provide attestation data in either the Attestation Measurement or Attestation Assertion fields.

type Attribute

type Attribute struct {
	// AttributeName should contain the canonical name of a tag, e.g. "Cryptographic Algorithm"
	AttributeName string
	// AttributeIndex is typically 0 when clients use this struct to create objects or add attributes.  Clients
	// only need to set this if modifying or deleting an existing attribute.
	AttributeIndex int `ttlv:",omitempty"`
	AttributeValue interface{}
}

Attribute 2.1.1 Table 2

An Attribute object is a structure (see Table 2) used for sending and receiving Managed Object attributes. The Attribute Name is a text-string that is used to identify the attribute. The Attribute Index is an index number assigned by the key management server. The Attribute Index is used to identify the particular instance. Attribute Indices SHALL start with 0. The Attribute Index of an attribute SHALL NOT change when other instances are added or deleted. Single-instance Attributes (attributes which an object MAY only have at most one instance thereof) SHALL have an Attribute Index of 0. The Attribute Value is either a primitive data type or structured object, depending on the attribute.

When an Attribute structure is used to specify or return a particular instance of an Attribute and the Attribute Index is not specified it SHALL be assumed to be 0.

func NewAttributeFromTag added in v0.0.6

func NewAttributeFromTag(tag ttlv.Tag, idx int, val interface{}) Attribute

type Attributes

type Attributes struct {
	Attributes []Attribute
}

type Authentication

type Authentication struct {
	Credential []Credential
}

type Certificate

type Certificate struct {
	CertificateType  kmip14.CertificateType
	CertificateValue []byte
}

type CreateHandler

type CreateHandler struct {
	Create func(ctx context.Context, payload *CreateRequestPayload) (*CreateResponsePayload, error)
}

func (*CreateHandler) HandleItem

func (h *CreateHandler) HandleItem(ctx context.Context, req *Request) (*ResponseBatchItem, error)

type CreateKeyPairRequestPayload added in v0.0.6

type CreateKeyPairRequestPayload struct {
	CommonTemplateAttribute     *TemplateAttribute
	PrivateKeyTemplateAttribute *TemplateAttribute
	PublicKeyTemplateAttribute  *TemplateAttribute
}

CreateKeyPairRequestPayload 4.2 Create Key Pair This operation requests the server to generate a new public/private key pair and register the two corresponding new Managed Cryptographic Objects.

The request contains attributes to be assigned to the objects (e.g., Cryptographic Algorithm, Cryptographic Length, etc.). Attributes and Template Names MAY be specified for both keys at the same time by specifying a Common Template-Attribute object in the request. Attributes not common to both keys (e.g., Name, Cryptographic Usage Mask) MAY be specified using the Private Key Template-Attribute and Public Key Template-Attribute objects in the request, which take precedence over the Common Template-Attribute object.

The Template Managed Object is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. Individual Attributes SHOULD be used in operations which currently support use of a Name within a Template-Attribute to reference a Template.

For the Private Key, the server SHALL create a Link attribute of Link Type Public Key pointing to the Public Key. For the Public Key, the server SHALL create a Link attribute of Link Type Private Key pointing to the Private Key. The response contains the Unique Identifiers of both created objects. The ID Placeholder value SHALL be set to the Unique Identifier of the Private Key.

type CreateKeyPairResponsePayload added in v0.0.6

type CreateKeyPairResponsePayload struct {
	PrivateKeyUniqueIdentifier  string
	PublicKeyUniqueIdentifier   string
	PrivateKeyTemplateAttribute *TemplateAttribute
	PublicKeyTemplateAttribute  *TemplateAttribute
}

type CreateRequestPayload

type CreateRequestPayload struct {
	ObjectType        kmip14.ObjectType
	TemplateAttribute TemplateAttribute
}

CreateRequestPayload 4.1 Table 163

TemplateAttribute MUST include CryptographicAlgorithm (3.4) and CryptographicUsageMask (3.19).

type CreateResponsePayload

type CreateResponsePayload struct {
	ObjectType        kmip14.ObjectType
	UniqueIdentifier  string
	TemplateAttribute *TemplateAttribute
}

CreateResponsePayload 4.1 Table 164

type Credential

type Credential struct {
	CredentialType  kmip14.CredentialType
	CredentialValue interface{}
}

Credential 2.1.2 Table 3

A Credential is a structure (see Table 3) used for client identification purposes and is not managed by the key management system (e.g., user id/password pairs, Kerberos tokens, etc.). It MAY be used for authentication purposes as indicated in [KMIP-Prof].

TODO: add an unmarshal impl to Credential to handle decoding the right kind of credential based on the credential type value

type CryptographicParameters

type CryptographicParameters struct {
	BlockCipherMode               kmip14.BlockCipherMode           `ttlv:",omitempty"`
	PaddingMethod                 kmip14.PaddingMethod             `ttlv:",omitempty"`
	HashingAlgorithm              kmip14.HashingAlgorithm          `ttlv:",omitempty"`
	KeyRoleType                   kmip14.KeyRoleType               `ttlv:",omitempty"`
	DigitalSignatureAlgorithm     kmip14.DigitalSignatureAlgorithm `ttlv:",omitempty"`
	CryptographicAlgorithm        kmip14.CryptographicAlgorithm    `ttlv:",omitempty"`
	RandomIV                      bool                             `ttlv:",omitempty"`
	IVLength                      int                              `ttlv:",omitempty"`
	TagLength                     int                              `ttlv:",omitempty"`
	FixedFieldLength              int                              `ttlv:",omitempty"`
	InvocationFieldLength         int                              `ttlv:",omitempty"`
	CounterLength                 int                              `ttlv:",omitempty"`
	InitialCounterValue           int                              `ttlv:",omitempty"`
	SaltLength                    int                              `ttlv:",omitempty"`
	MaskGenerator                 kmip14.MaskGenerator             `ttlv:",omitempty" default:"1"` // defaults to MGF1
	MaskGeneratorHashingAlgorithm kmip14.HashingAlgorithm          `ttlv:",omitempty" default:"4"` // defaults to SHA-1
	PSource                       []byte                           `ttlv:",omitempty"`
	TrailerField                  int                              `ttlv:",omitempty"`
}

Cryptographic Parameters 3.6 Table 65

The Cryptographic Parameters attribute is a structure (see Table 65) that contains a set of OPTIONAL fields that describe certain cryptographic parameters to be used when performing cryptographic operations using the object. Specific fields MAY pertain only to certain types of Managed Cryptographic Objects. The Cryptographic Parameters attribute of a Certificate object identifies the cryptographic parameters of the public key contained within the Certificate.

The Cryptographic Algorithm is also used to specify the parameters for cryptographic operations. For operations involving digital signatures, either the Digital Signature Algorithm can be specified or the Cryptographic Algorithm and Hashing Algorithm combination can be specified.

Random IV can be used to request that the KMIP server generate an appropriate IV for a cryptographic operation that uses an IV. The generated Random IV is returned in the response to the cryptographic operation.

IV Length is the length of the Initialization Vector in bits. This parameter SHALL be provided when the specified Block Cipher Mode supports variable IV lengths such as CTR or GCM.

Tag Length is the length of the authentication tag in bytes. This parameter SHALL be provided when the Block Cipher Mode is GCM or CCM.

The IV used with counter modes of operation (e.g., CTR and GCM) cannot repeat for a given cryptographic key. To prevent an IV/key reuse, the IV is often constructed of three parts: a fixed field, an invocation field, and a counter as described in [SP800-38A] and [SP800-38D]. The Fixed Field Length is the length of the fixed field portion of the IV in bits. The Invocation Field Length is the length of the invocation field portion of the IV in bits. The Counter Length is the length of the counter portion of the IV in bits.

Initial Counter Value is the starting counter value for CTR mode (for [RFC3686] it is 1).

type DestroyHandler added in v0.0.6

type DestroyHandler struct {
	Destroy func(ctx context.Context, payload *DestroyRequestPayload) (*DestroyResponsePayload, error)
}

func (*DestroyHandler) HandleItem added in v0.0.6

func (h *DestroyHandler) HandleItem(ctx context.Context, req *Request) (*ResponseBatchItem, error)

type DestroyRequestPayload added in v0.0.6

type DestroyRequestPayload struct {
	UniqueIdentifier string
}

DestroyRequestPayload ////////////////////////////////////////

type DestroyResponsePayload added in v0.0.6

type DestroyResponsePayload struct {
	UniqueIdentifier string
}

DestroyResponsePayload

type DeviceCredentialValue

type DeviceCredentialValue struct {
	DeviceSerialNumber string `ttlv:",omitempty"`
	Password           string `ttlv:",omitempty"`
	DeviceIdentifier   string `ttlv:",omitempty"`
	NetworkIdentifier  string `ttlv:",omitempty"`
	MachineIdentifier  string `ttlv:",omitempty"`
	MediaIdentifier    string `ttlv:",omitempty"`
}

DeviceCredentialValue 2.1.2 Table 5

If the Credential Type in the Credential is Device, then Credential Value is a structure as shown in Table 5. One or a combination of the Device Serial Number, Network Identifier, Machine Identifier, and Media Identifier SHALL be unique. Server implementations MAY enforce policies on uniqueness for individual fields. A shared secret or password MAY also be used to authenticate the client. The client SHALL provide at least one field.

type DiscoverVersionsHandler

type DiscoverVersionsHandler struct {
	SupportedVersions []ProtocolVersion
}

func (*DiscoverVersionsHandler) HandleItem

func (h *DiscoverVersionsHandler) HandleItem(ctx context.Context, req *Request) (item *ResponseBatchItem, err error)

type DiscoverVersionsRequestPayload

type DiscoverVersionsRequestPayload struct {
	ProtocolVersion []ProtocolVersion
}

type DiscoverVersionsResponsePayload

type DiscoverVersionsResponsePayload struct {
	ProtocolVersion []ProtocolVersion
}

type EncryptionKeyInformation

type EncryptionKeyInformation struct {
	UniqueIdentifier        string
	CryptographicParameters *CryptographicParameters
}

EncryptionKeyInformation 2.1.5 Table 10

type ErrorHandler

type ErrorHandler interface {
	HandleError(err error) *ResponseBatchItem
}

ErrorHandler converts a golang error into a *ResponseBatchItem (which should hold information about the error to convey back to the client).

type ErrorHandlerFunc

type ErrorHandlerFunc func(err error) *ResponseBatchItem

func (ErrorHandlerFunc) HandleError

func (f ErrorHandlerFunc) HandleError(err error) *ResponseBatchItem

type GetHandler added in v0.0.6

type GetHandler struct {
	Get func(ctx context.Context, payload *GetRequestPayload) (*GetResponsePayload, error)
}

func (*GetHandler) HandleItem added in v0.0.6

func (h *GetHandler) HandleItem(ctx context.Context, req *Request) (*ResponseBatchItem, error)

type GetRequestPayload added in v0.0.6

type GetRequestPayload struct {
	UniqueIdentifier string
}

GetRequestPayload ////////////////////////////////////////

type GetResponsePayload added in v0.0.6

type GetResponsePayload struct {
	ObjectType       kmip14.ObjectType
	UniqueIdentifier string
	Certificate      *Certificate
	SymmetricKey     *SymmetricKey
	PrivateKey       *PrivateKey
	PublicKey        *PublicKey
	SplitKey         *SplitKey
	Template         *Template
	SecretData       *SecretData
	OpaqueObject     *OpaqueObject
}

GetResponsePayload

type ItemHandler

type ItemHandler interface {
	HandleItem(ctx context.Context, req *Request) (item *ResponseBatchItem, err error)
}

ItemHandler handles a single batch item in a KMIP request. The *Request object's CurrentItem field will be populated with item to be handled.

type ItemHandlerFunc

type ItemHandlerFunc func(context.Context, *Request) (*ResponseBatchItem, error)

func (ItemHandlerFunc) HandleItem

func (f ItemHandlerFunc) HandleItem(ctx context.Context, req *Request) (item *ResponseBatchItem, err error)

type KeyBlock

type KeyBlock struct {
	KeyFormatType          kmip14.KeyFormatType
	KeyCompressionType     kmip14.KeyCompressionType     `ttlv:",omitempty"`
	KeyValue               *KeyValue                     `ttlv:",omitempty"`
	CryptographicAlgorithm kmip14.CryptographicAlgorithm `ttlv:",omitempty"`
	CryptographicLength    int                           `ttlv:",omitempty"`
	KeyWrappingData        *KeyWrappingData
}

KeyBlock 2.1.3 Table 7

A Key Block object is a structure (see Table 7) used to encapsulate all of the information that is closely associated with a cryptographic key. It contains a Key Value of one of the following Key Format Types:

  • Raw – This is a key that contains only cryptographic key material, encoded as a string of bytes.
  • Opaque – This is an encoded key for which the encoding is unknown to the key management system. It is encoded as a string of bytes.
  • PKCS1 – This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#1 object.
  • PKCS8 – This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#8 object, supporting both the RSAPrivateKey syntax and EncryptedPrivateKey.
  • X.509 – This is an encoded object, expressed as a DER-encoded ASN.1 X.509 object.
  • ECPrivateKey – This is an ASN.1 encoded elliptic curve private key.
  • Several Transparent Key types – These are algorithm-specific structures containing defined values for the various key types, as defined in Section 2.1.7.
  • Extensions – These are vendor-specific extensions to allow for proprietary or legacy key formats.

The Key Block MAY contain the Key Compression Type, which indicates the format of the elliptic curve public key. By default, the public key is uncompressed.

The Key Block also has the Cryptographic Algorithm and the Cryptographic Length of the key contained in the Key Value field. Some example values are:

  • RSA keys are typically 1024, 2048 or 3072 bits in length.
  • 3DES keys are typically from 112 to 192 bits (depending upon key length and the presence of parity bits).
  • AES keys are 128, 192 or 256 bits in length.

The Key Block SHALL contain a Key Wrapping Data structure if the key in the Key Value field is wrapped (i.e., encrypted, or MACed/signed, or both).

type KeyValue

type KeyValue struct {
	// KeyMaterial should be []byte, one of the Transparent*Key structs, or a custom struct if KeyFormatType is
	// an extension.
	KeyMaterial interface{}
	Attribute   []Attribute
}

KeyValue 2.1.4 Table 8

The Key Value is used only inside a Key Block and is either a Byte String or a structure (see Table 8):

  • The Key Value structure contains the key material, either as a byte string or as a Transparent Key structure (see Section 2.1.7), and OPTIONAL attribute information that is associated and encapsulated with the key material. This attribute information differs from the attributes associated with Managed Objects, and is obtained via the Get Attributes operation, only by the fact that it is encapsulated with (and possibly wrapped with) the key material itself.
  • The Key Value Byte String is either the wrapped TTLV-encoded (see Section 9.1) Key Value structure, or the wrapped un-encoded value of the Byte String Key Material field.

TODO: Unmarshaler impl which unmarshals correct KeyMaterial type.

type KeyWrappingData

type KeyWrappingData struct {
	WrappingMethod             kmip14.WrappingMethod
	EncryptionKeyInformation   *EncryptionKeyInformation
	MACSignatureKeyInformation *MACSignatureKeyInformation
	MACSignature               []byte
	IVCounterNonce             []byte
	EncodingOption             kmip14.EncodingOption `ttlv:",omitempty" default:"TTLVEncoding"`
}

KeyWrappingData 2.1.5 Table 9

The Key Block MAY also supply OPTIONAL information about a cryptographic key wrapping mechanism used to wrap the Key Value. This consists of a Key Wrapping Data structure (see Table 9). It is only used inside a Key Block.

This structure contains fields for:

  • A Wrapping Method, which indicates the method used to wrap the Key Value.
  • Encryption Key Information, which contains the Unique Identifier (see 3.1) value of the encryption key and associated cryptographic parameters.
  • MAC/Signature Key Information, which contains the Unique Identifier value of the MAC/signature key and associated cryptographic parameters.
  • A MAC/Signature, which contains a MAC or signature of the Key Value.
  • An IV/Counter/Nonce, if REQUIRED by the wrapping method.
  • An Encoding Option, specifying the encoding of the Key Material within the Key Value structure of the Key Block that has been wrapped. If No Encoding is specified, then the Key Value structure SHALL NOT contain any attributes.

If wrapping is used, then the whole Key Value structure is wrapped unless otherwise specified by the Wrapping Method. The algorithms used for wrapping are given by the Cryptographic Algorithm attributes of the encryption key and/or MAC/signature key; the block-cipher mode, padding method, and hashing algorithm used for wrapping are given by the Cryptographic Parameters in the Encryption Key Information and/or MAC/Signature Key Information, or, if not present, from the Cryptographic Parameters attribute of the respective key(s). Either the Encryption Key Information or the MAC/Signature Key Information (or both) in the Key Wrapping Data structure SHALL be specified.

The following wrapping methods are currently defined:

  • Encrypt only (i.e., encryption using a symmetric key or public key, or authenticated encryption algorithms that use a single key).
  • MAC/sign only (i.e., either MACing the Key Value with a symmetric key, or signing the Key Value with a private key).
  • Encrypt then MAC/sign.
  • MAC/sign then encrypt.
  • TR-31.
  • Extensions.

The following encoding options are currently defined:

  • No Encoding (i.e., the wrapped un-encoded value of the Byte String Key Material field in the Key Value structure).
  • TTLV Encoding (i.e., the wrapped TTLV-encoded Key Value structure).

type MACSignatureKeyInformation

type MACSignatureKeyInformation struct {
	UniqueIdentifier        string
	CryptographicParameters *CryptographicParameters
}

MACSignatureKeyInformation 2.1.5 Table 11

type MessageExtension

type MessageExtension struct {
	VendorIdentification string
	CriticalityIndicator bool
	VendorExtension      interface{}
}

type MessageHandler

type MessageHandler interface {
	HandleMessage(ctx context.Context, req *Request, resp *Response)
}

MessageHandler handles KMIP requests which have already be decoded. The *Request object's Message field will be populated from the decoded TTLV. The *Response object will always be non-nil, and its ResponseHeader will be populated. The MessageHandler usually shouldn't modify the ResponseHeader: the ProtocolHandler is responsible for the header. The MessageHandler just needs to populate the response batch items.

The default implementation of MessageHandler is OperationMux.

type MessageHandlerFunc

type MessageHandlerFunc func(context.Context, *Request, *Response)

func (MessageHandlerFunc) HandleMessage

func (f MessageHandlerFunc) HandleMessage(ctx context.Context, req *Request, resp *Response)

type Name

type Name struct {
	NameValue string
	NameType  kmip14.NameType
}

Name 3.2 Table 57

The Name attribute is a structure (see Table 57) used to identify and locate an object. This attribute is assigned by the client, and the Name Value is intended to be in a form that humans are able to interpret. The key management system MAY specify rules by which the client creates valid names. Clients are informed of such rules by a mechanism that is not specified by this standard. Names SHALL be unique within a given key management domain, but are NOT REQUIRED to be globally unique.

type Nonce

type Nonce struct {
	NonceID    []byte
	NonceValue []byte
}

type OpaqueObject

type OpaqueObject struct {
	OpaqueDataType  kmip14.OpaqueDataType
	OpaqueDataValue []byte
}

type OperationMux

type OperationMux struct {

	// ErrorHandler defaults to the DefaultErrorHandler.
	ErrorHandler ErrorHandler
	// contains filtered or unexported fields
}

OperationMux is an implementation of MessageHandler which handles each batch item in the request by routing the operation to an ItemHandler. The ItemHandler performs the operation, and returns either a *ResponseBatchItem, or an error. If it returns an error, the error is passed to ErrorHandler, which converts it into a error *ResponseBatchItem. OperationMux handles correlating items in the request to items in the response.

func (*OperationMux) Handle

func (m *OperationMux) Handle(op kmip14.Operation, handler ItemHandler)

func (*OperationMux) HandleMessage

func (m *OperationMux) HandleMessage(ctx context.Context, req *Request, resp *Response)

type PGPKey

type PGPKey struct {
	PGPKeyVersion int
	KeyBlock      KeyBlock
}

type PrivateKey

type PrivateKey struct {
	KeyBlock KeyBlock
}

type ProtocolHandler

type ProtocolHandler interface {
	ServeKMIP(ctx context.Context, req *Request, resp ResponseWriter)
}

ProtocolHandler is responsible for handling raw requests read off the wire. The *Request object will only have TTLV field populated. The response should be written directly to the ResponseWriter.

The default implemention of ProtocolHandler is StandardProtocolHandler.

type ProtocolHandlerFunc

type ProtocolHandlerFunc func(context.Context, *Request, ResponseWriter)

func (ProtocolHandlerFunc) ServeKMIP

func (f ProtocolHandlerFunc) ServeKMIP(ctx context.Context, r *Request, w ResponseWriter)

type ProtocolVersion

type ProtocolVersion struct {
	ProtocolVersionMajor int
	ProtocolVersionMinor int
}

type PublicKey

type PublicKey struct {
	KeyBlock KeyBlock
}

type RegisterHandler

type RegisterHandler struct {
	SkipValidation bool
	RegisterFunc   func(context.Context, *RegisterRequestPayload) (*RegisterResponsePayload, error)
}

func (*RegisterHandler) HandleItem

func (h *RegisterHandler) HandleItem(ctx context.Context, req *Request) (item *ResponseBatchItem, err error)

type RegisterRequestPayload

type RegisterRequestPayload struct {
	ObjectType        kmip14.ObjectType
	TemplateAttribute TemplateAttribute
	Certificate       *Certificate
	SymmetricKey      *SymmetricKey
	PrivateKey        *PrivateKey
	PublicKey         *PublicKey
	SplitKey          *SplitKey
	Template          *Template
	SecretData        *SecretData
	OpaqueObject      *OpaqueObject
}

type RegisterResponsePayload

type RegisterResponsePayload struct {
	UniqueIdentifier  string
	TemplateAttribute TemplateAttribute
}

type Request

type Request struct {
	// TTLV will hold the entire body of the request.
	TTLV                ttlv.TTLV
	Message             *RequestMessage
	CurrentItem         *RequestBatchItem
	DisallowExtraValues bool

	// TLS holds the TLS state of the connection this request was received on.
	TLS        *tls.ConnectionState
	RemoteAddr string
	LocalAddr  string

	IDPlaceholder string
	// contains filtered or unexported fields
}

Request represents a KMIP request.

func (*Request) DecodePayload

func (r *Request) DecodePayload(v interface{}) error

func (*Request) Unmarshal

func (r *Request) Unmarshal(ttlv ttlv.TTLV, into interface{}) error

Unmarshal unmarshals ttlv into structures. Handlers should prefer this method over than their own Decoders or Unmarshal(). This method enforces rules about whether extra fields are allowed, and reuses buffers for efficiency.

type RequestBatchItem

type RequestBatchItem struct {
	Operation         kmip14.Operation
	UniqueBatchItemID []byte `ttlv:",omitempty"`
	RequestPayload    interface{}
	MessageExtension  *MessageExtension `ttlv:",omitempty"`
}

type RequestHeader

type RequestHeader struct {
	ProtocolVersion              ProtocolVersion
	MaximumResponseSize          int    `ttlv:",omitempty"`
	ClientCorrelationValue       string `ttlv:",omitempty"`
	ServerCorrelationValue       string `ttlv:",omitempty"`
	AsynchronousIndicator        bool   `ttlv:",omitempty"`
	AttestationCapableIndicator  bool   `ttlv:",omitempty"`
	AttestationType              []kmip14.AttestationType
	Authentication               *Authentication
	BatchErrorContinuationOption kmip14.BatchErrorContinuationOption `ttlv:",omitempty"`
	BatchOrderOption             bool                                `ttlv:",omitempty"`
	TimeStamp                    *time.Time
	BatchCount                   int
}

type RequestMessage

type RequestMessage struct {
	RequestHeader RequestHeader
	BatchItem     []RequestBatchItem
}

type Response

type Response struct {
	ResponseMessage
	// contains filtered or unexported fields
}

func (*Response) Bytes

func (r *Response) Bytes() []byte

type ResponseBatchItem

type ResponseBatchItem struct {
	Operation                    kmip14.Operation `ttlv:",omitempty"`
	UniqueBatchItemID            []byte           `ttlv:",omitempty"`
	ResultStatus                 kmip14.ResultStatus
	ResultReason                 kmip14.ResultReason `ttlv:",omitempty"`
	ResultMessage                string              `ttlv:",omitempty"`
	AsynchronousCorrelationValue []byte              `ttlv:",omitempty"`
	ResponsePayload              interface{}         `ttlv:",omitempty"`
	MessageExtension             *MessageExtension
}

type ResponseHeader

type ResponseHeader struct {
	ProtocolVersion        ProtocolVersion
	TimeStamp              time.Time
	Nonce                  *Nonce
	AttestationType        []kmip14.AttestationType
	ClientCorrelationValue string `ttlv:",omitempty"`
	ServerCorrelationValue string `ttlv:",omitempty"`
	BatchCount             int
}

type ResponseMessage

type ResponseMessage struct {
	ResponseHeader ResponseHeader
	BatchItem      []ResponseBatchItem
}

type ResponseWriter

type ResponseWriter interface {
	io.Writer
}

type SecretData

type SecretData struct {
	SecretDataType kmip14.SecretDataType
	KeyBlock       KeyBlock
}

type Server

type Server struct {
	Handler ProtocolHandler
	// contains filtered or unexported fields
}

Server serves KMIP protocol connections from a net.Listener. Because KMIP is a connection-oriented protocol, unlike HTTP, each connection ends up being serviced by a dedicated goroutine (rather than each request). For each KMIP connection, requests are processed serially. The handling of the request is delegated to the ProtocolHandler.

Limitations:

This implementation is functional (it can respond to KMIP requests), but incomplete. Some of the connection management features of the http package haven't been ported over, and also, there is currently no connection-context in which to store things like an authentication or session management. Since HTTP is an intrinsically stateless model, it makes sense for the http package to delegate session management to third party packages, but for KMIP, it would makes sense for there to be some first class support for a connection context.

This package also only handles the binary TTLV encoding for now. It may make sense for this server to detect or support the XML and JSON encodings as well. It may also makes sense to support KMIP requests over HTTP, perhaps by adapting ProtocolHandler to an http.Handler or something.

Example
listener, err := net.Listen("tcp", "0.0.0.0:5696")
if err != nil {
	panic(err)
}

kmip.DefaultProtocolHandler.LogTraffic = true

kmip.DefaultOperationMux.Handle(kmip14.OperationDiscoverVersions, &kmip.DiscoverVersionsHandler{
	SupportedVersions: []kmip.ProtocolVersion{
		{
			ProtocolVersionMajor: 1,
			ProtocolVersionMinor: 4,
		},
		{
			ProtocolVersionMajor: 1,
			ProtocolVersionMinor: 3,
		},
		{
			ProtocolVersionMajor: 1,
			ProtocolVersionMinor: 2,
		},
	},
})
srv := kmip.Server{}
panic(srv.Serve(listener))
Output:

func (*Server) Close

func (srv *Server) Close() error

Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.

Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.

Close returns any error returned from closing the Server's underlying Listener(s).

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.MessageHandler to reply to them.

Serve always returns a non-nil error and closes l. After Shutdown or Close, the returned error is ErrServerClosed.

func (*Server) Shutdown

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions.

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

type SplitKey

type SplitKey struct {
	SplitKeyParts     int
	KeyPartIdentifier int
	SplitKeyThreshold int
	SplitKeyMethod    kmip14.SplitKeyMethod
	PrimeFieldSize    *big.Int `ttlv:",omitempty"`
	KeyBlock          KeyBlock
}

type StandardProtocolHandler

type StandardProtocolHandler struct {
	ProtocolVersion ProtocolVersion
	MessageHandler  MessageHandler

	LogTraffic bool
}

StandardProtocolHandler is the default ProtocolHandler implementation. It handles decoding the request and encoding the response, as well as protocol level tasks like version negotiation and correlation values.

It delegates handling of the request to a MessageHandler.

func (*StandardProtocolHandler) ServeKMIP

func (h *StandardProtocolHandler) ServeKMIP(ctx context.Context, req *Request, writer ResponseWriter)

type SymmetricKey

type SymmetricKey struct {
	KeyBlock KeyBlock
}

type Template

type Template struct {
	Attribute []Attribute
}

type TemplateAttribute

type TemplateAttribute struct {
	Name      []Name
	Attribute []Attribute
}

TemplateAttribute 2.1.8 Table 29

The Template Managed Object is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. Individual Attributes SHOULD be used in operations which currently support use of a Name within a Template-Attribute to reference a Template.

These structures are used in various operations to provide the desired attribute values and/or template names in the request and to return the actual attribute values in the response.

The Template-Attribute, Common Template-Attribute, Private Key Template-Attribute, and Public Key Template-Attribute structures are defined identically as follows:

type TemplateAttribute struct {
	Attribute []Attribute
}

func (*TemplateAttribute) Append added in v0.0.6

func (t *TemplateAttribute) Append(tag ttlv.Tag, value interface{})

func (*TemplateAttribute) Get

func (t *TemplateAttribute) Get(s string) *Attribute

Get returns a reference to the first Attribute in the list matching the name. Returns nil if not found.

func (*TemplateAttribute) GetAll

func (t *TemplateAttribute) GetAll(s string) []Attribute

func (*TemplateAttribute) GetAllTag

func (t *TemplateAttribute) GetAllTag(tag ttlv.Tag) []Attribute

func (*TemplateAttribute) GetIdx added in v0.0.6

func (t *TemplateAttribute) GetIdx(s string, idx int) *Attribute

GetIdx returns a reference to the Attribute in the list matching the name and index. Returns nil if not found.

func (*TemplateAttribute) GetTag

func (t *TemplateAttribute) GetTag(tag ttlv.Tag) *Attribute

GetTag returns a reference to the first Attribute in the list matching the tag. Returns nil if not found.

func (*TemplateAttribute) GetTagIdx added in v0.0.6

func (t *TemplateAttribute) GetTagIdx(tag ttlv.Tag, idx int) *Attribute

GetTagIdx returns a reference to the first Attribute in the list matching the tag and index. Returns nil if not found.

type TransparentDHPrivateKey

type TransparentDHPrivateKey struct {
	P *big.Int `validate:"required"`
	Q *big.Int
	G *big.Int `validate:"required"`
	J *big.Int
	X *big.Int `validate:"required"`
}

TransparentDHPrivateKey 2.1.7.6 Table 19

If the Key Format Type in the Key Block is Transparent DH Private Key, then Key Material is a structure as shown in Table 19.

type TransparentDHPublicKey

type TransparentDHPublicKey struct {
	P *big.Int `validate:"required"`
	Q *big.Int
	G *big.Int `validate:"required"`
	J *big.Int
	Y *big.Int `validate:"required"`
}

TransparentDHPublicKey 2.1.7.7 Table 20

If the Key Format Type in the Key Block is Transparent DH Public Key, then Key Material is a structure as shown in Table 20.

P, G, and Y are required.

type TransparentDSAPrivateKey

type TransparentDSAPrivateKey struct {
	// TODO: should these be pointers?  big package deals entirely with pointers, but these are not optional values.
	P *big.Int `validate:"required"`
	Q *big.Int `validate:"required"`
	G *big.Int `validate:"required"`
	X *big.Int `validate:"required"`
}

TransparentDSAPrivateKey 2.1.7.2 Table 15

If the Key Format Type in the Key Block is Transparent DSA Private Key, then Key Material is a structure as shown in Table 15.

type TransparentDSAPublicKey

type TransparentDSAPublicKey struct {
	P *big.Int `validate:"required"`
	Q *big.Int `validate:"required"`
	G *big.Int `validate:"required"`
	Y *big.Int `validate:"required"`
}

TransparentDSAPublicKey 2.1.7.3 Table 16

If the Key Format Type in the Key Block is Transparent DSA Public Key, then Key Material is a structure as shown in Table 16.

type TransparentECDHPrivateKey

type TransparentECDHPrivateKey TransparentECPrivateKey

TransparentECDHPrivateKey 2.1.7.10 Table 23

The Transparent ECDH Private Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Private Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECDH Private Key, then Key Material is a structure as shown in Table 23.

type TransparentECDHPublicKey

type TransparentECDHPublicKey TransparentECPublicKey

TransparentECDHPublicKey 2.1.7.11 Table 24

The Transparent ECDH Public Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Public Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECDH Public Key, then Key Material is a structure as shown in Table 24.

type TransparentECDSAPrivateKey

type TransparentECDSAPrivateKey struct {
	RecommendedCurve kmip14.RecommendedCurve
	D                *big.Int `validate:"required"`
}

TransparentECDSAPrivateKey 2.1.7.8 Table 21

The Transparent ECDSA Private Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Private Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECDSA Private Key, then Key Material is a structure as shown in Table 21.

type TransparentECDSAPublicKey

type TransparentECDSAPublicKey struct {
	RecommendedCurve kmip14.RecommendedCurve
	QString          []byte `validate:"required"`
}

TransparentECDSAPublicKey 2.1.7.9 Table 22

The Transparent ECDSA Public Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Public Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECDSA Public Key, then Key Material is a structure as shown in Table 22.

type TransparentECMQVPrivateKey

type TransparentECMQVPrivateKey TransparentECPrivateKey

TransparentECMQVPrivateKey 2.1.7.12 Table 25

The Transparent ECMQV Private Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Private Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECMQV Private Key, then Key Material is a structure as shown in Table 25.

type TransparentECMQVPublicKey

type TransparentECMQVPublicKey TransparentECPublicKey

TransparentECMQVPublicKey 2.1.7.13 Table 26

The Transparent ECMQV Public Key structure is deprecated as of version 1.3 of this specification and MAY be removed from subsequent versions of the specification. The Transparent EC Public Key structure SHOULD be used as a replacement.

If the Key Format Type in the Key Block is Transparent ECMQV Public Key, then Key Material is a structure as shown in Table 26.

type TransparentECPrivateKey

type TransparentECPrivateKey struct {
	RecommendedCurve kmip14.RecommendedCurve
	D                *big.Int `validate:"required"`
}

TransparentECPrivateKey 2.1.7.14 Table 27

If the Key Format Type in the Key Block is Transparent EC Private Key, then Key Material is a structure as shown in Table 27.

type TransparentECPublicKey

type TransparentECPublicKey struct {
	RecommendedCurve kmip14.RecommendedCurve
	QString          []byte `validate:"required"`
}

TransparentECPublicKey 2.1.7.15 Table 28

If the Key Format Type in the Key Block is Transparent EC Public Key, then Key Material is a structure as shown in Table 28.

type TransparentRSAPrivateKey

type TransparentRSAPrivateKey struct {
	Modulus                         *big.Int `validate:"required"`
	PrivateExponent, PublicExponent *big.Int
	P, Q                            *big.Int
	PrimeExponentP, PrimeExponentQ  *big.Int
	CRTCoefficient                  *big.Int
}

TransparentRSAPrivateKey 2.1.7.4 Table 17

If the Key Format Type in the Key Block is Transparent RSA Private Key, then Key Material is a structure as shown in Table 17.

One of the following SHALL be present (refer to [PKCS#1]):

  • Private Exponent,
  • P and Q (the first two prime factors of Modulus), or
  • Prime Exponent P and Prime Exponent Q.

type TransparentRSAPublicKey

type TransparentRSAPublicKey struct {
	Modulus        *big.Int `validate:"required"`
	PublicExponent *big.Int `validate:"required"`
}

TransparentRSAPublicKey 2.1.7.5 Table 18

If the Key Format Type in the Key Block is Transparent RSA Public Key, then Key Material is a structure as shown in Table 18.

type TransparentSymmetricKey

type TransparentSymmetricKey struct {
	Key []byte `validate:"required"`
}

TransparentSymmetricKey 2.1.7.1 Table 14

If the Key Format Type in the Key Block is Transparent Symmetric Key, then Key Material is a structure as shown in Table 14.

type UsernameAndPasswordCredentialValue

type UsernameAndPasswordCredentialValue struct {
	Username string
	Password string `ttlv:",omitempty"`
}

UsernameAndPasswordCredentialValue 2.1.2 Table 4

If the Credential Type in the Credential is Username and Password, then Credential Value is a structure as shown in Table 4. The Username field identifies the client, and the Password field is a secret that authenticates the client.

Directories

Path Synopsis
cmd
internal
Package kmip14 contains tag and enumeration value definitions from the 1.4 specification.
Package kmip14 contains tag and enumeration value definitions from the 1.4 specification.
Package kmip20 contains definitions from the 2.0 specification.
Package kmip20 contains definitions from the 2.0 specification.
Package ttlv encodes and decodes the 3 wire formats defined in the KMIP specification:
Package ttlv encodes and decodes the 3 wire formats defined in the KMIP specification:

Jump to

Keyboard shortcuts

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