Skip to content

Commit

Permalink
Symmetric support (#8)
Browse files Browse the repository at this point in the history
* Implement cipher.Block for AES and DES3

re #6

* Fast CBC support

re #6

* Exercise GCM in tests

re #6

* HSM-native GCM

For testing with SoftHSM2 you need at least version 2.4.0, i.e. at least
Debian buster/sid or Ubuntu cosmic (or BYO).

This commit also updates our dependency on github.com/miekg/pkcs11 to
one with GCM support.

re #6

* HMAC implementation

re #7

* Finalized symmetric crypto interface

You can now have a crypto11.BlockModeCloser, and must call Close(),
or a cipher.BlockMode, but it has a finalizer.

re #6

* Expose CBC via cipher.AEAD

This is rather an abuse of the cipher.AEAD interface as the name
and description both indicate it provides authenticated encryption,
which is not the case for CBC. The risk of using it in a context
where authentication is required is mitigated only by documentation.

re #6

* Linter-driven cleanup

* Split symmetric support into separate files

re #6 re #7

* Documentation review

re #6

* Keep blockModeCloser alive during PKCS#11 calls

re #6

* Implement HMAC Reset() and make Sum() friendlier

re #7

* HMAC empty inputs without panicing

re #7

* update Gopkg.lock

We depend upon miekg/pkcs11#82.

* Query GCM capability rather than provider
  • Loading branch information
optnfast committed Oct 3, 2018
1 parent bdea25c commit f2a4754
Show file tree
Hide file tree
Showing 11 changed files with 1,569 additions and 7 deletions.
4 changes: 2 additions & 2 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ uses [PKCS#11](http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/errata01/os/p
* ECDSA signing.
* DSA signing.
* Random number generation.
* (Experimental) AES and DES3 encryption and decryption.
* (Experimental) HMAC support.

Signing is done through the
[crypto.Signer](https://golang.org/pkg/crypto/#Signer) interface and
Expand Down Expand Up @@ -89,6 +91,8 @@ To protect keys with the module only, use the 'accelerator' token:
"Pin" : "password"
}

(At time of writing) GCM is not implemented, so expect test skips.

Testing with SoftHSM
--------------------

Expand Down Expand Up @@ -147,7 +151,7 @@ The configuration looks like this:
"Pin" : "password"
}

(At time of writing) OAEP is only partial, so expect test skips.
(At time of writing) OAEP is only partial and HMAC is unsupported, so expect test skips.

Limitations
===========
Expand All @@ -156,6 +160,12 @@ Limitations
is not implemented and an error is returned if it is nonzero.
The reason for this is that it is not possible for crypto11 to guarantee the constant-time behavior in the specification.
See [issue #5](https://github.com/ThalesIgnite/crypto11/issues/5) for further discussion.
* Symmetric crypto support via [cipher.Block](https://golang.org/pkg/crypto/cipher/#Block) is very slow.
You can use the `BlockModeCloser` API
(over 400 times as fast on my computer)
but you must call the Close()
interface (not found in [cipher.BlockMode](https://golang.org/pkg/crypto/cipher/#BlockMode)).
See [issue #6](https://github.com/ThalesIgnite/crypto11/issues/6) for further discussion.

Wishlist
========
Expand All @@ -168,7 +178,7 @@ Copyright

MIT License.

Copyright 2016, 2017 Thales e-Security, Inc
Copyright 2016-2018 Thales e-Security, Inc

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Expand Down
162 changes: 162 additions & 0 deletions aead.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// Copyright 2018 Thales e-Security, Inc
//
// 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.

package crypto11

import (
"crypto/cipher"
"errors"
"fmt"
"github.com/miekg/pkcs11"
)

// cipher.AEAD ----------------------------------------------------------

const (
// PaddingNone represents a block cipher with no padding. (See NewCBC.)
PaddingNone = iota

// PaddingPKCS represents a block cipher used with PKCS#7 padding. (See NewCBC.)
PaddingPKCS
)

type genericAead struct {
key *PKCS11SecretKey

overhead int

nonceSize int

makeMech func(nonce []byte, additionalData []byte) ([]*pkcs11.Mechanism, error)
}

// NewGCM returns a given cipher wrapped in Galois Counter Mode, with the standard
// nonce length.
//
// This depends on the HSM supporting the CKM_*_GCM mechanism. If it is not supported
// then you must use cipher.NewGCM; it will be slow.
func (key *PKCS11SecretKey) NewGCM() (g cipher.AEAD, err error) {
if key.Cipher.GCMMech == 0 {
err = fmt.Errorf("GCM not implemented for key type %#x", key.Cipher.GenParams[0].KeyType)
return
}
g = genericAead{
key: key,
overhead: 16,
nonceSize: 12,
makeMech: func(nonce []byte, additionalData []byte) (mech []*pkcs11.Mechanism, error error) {
params := pkcs11.NewGCMParams(nonce, additionalData, 16)
mech = []*pkcs11.Mechanism{pkcs11.NewMechanism(key.Cipher.GCMMech, params)}
return
},
}
return
}

// NewCBC returns a given cipher wrapped in CBC mode.
//
// Despite the cipher.AEAD return type, there is no support for additional data and no authentication.
// This method exists to provide a convenient way to do bulk (possibly padded) CBC encryption.
// Think carefully before passing the cipher.AEAD to any consumer that expects authentication.
func (key *PKCS11SecretKey) NewCBC(paddingMode int) (g cipher.AEAD, err error) {
g = genericAead{
key: key,
overhead: 0,
nonceSize: key.BlockSize(),
makeMech: func(nonce []byte, additionalData []byte) (mech []*pkcs11.Mechanism, error error) {
if len(additionalData) > 0 {
err = errors.New("additional data not supported for CBC mode")
}
var pkcsMech uint
switch paddingMode {
case PaddingNone:
pkcsMech = key.Cipher.CBCMech
case PaddingPKCS:
pkcsMech = key.Cipher.CBCPKCSMech
default:
err = errors.New("unrecognized padding mode")
return
}
if pkcsMech == 0 {
err = errors.New("unsupported padding mode")
return
}
mech = []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcsMech, nonce)}
return
},
}
return
}

func (g genericAead) NonceSize() int {
return g.nonceSize
}

func (g genericAead) Overhead() int {
return g.overhead
}

func (g genericAead) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
var result []byte
if err := withSession(g.key.Slot, func(session *PKCS11Session) (err error) {
var mech []*pkcs11.Mechanism
if mech, err = g.makeMech(nonce, additionalData); err != nil {
return
}
if err = session.Ctx.EncryptInit(session.Handle, mech, g.key.Handle); err != nil {
err = fmt.Errorf("C_EncryptInit: %v", err)
return
}
if result, err = session.Ctx.Encrypt(session.Handle, plaintext); err != nil {
err = fmt.Errorf("C_Encrypt: %v", err)
return
}
return
}); err != nil {
panic(err)
} else {
dst = append(dst, result...)
}
return dst
}

func (g genericAead) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
var result []byte
if err := withSession(g.key.Slot, func(session *PKCS11Session) (err error) {
var mech []*pkcs11.Mechanism
if mech, err = g.makeMech(nonce, additionalData); err != nil {
return
}
if err = session.Ctx.DecryptInit(session.Handle, mech, g.key.Handle); err != nil {
err = fmt.Errorf("C_DecryptInit: %v", err)
return
}
if result, err = session.Ctx.Decrypt(session.Handle, ciphertext); err != nil {
err = fmt.Errorf("C_Decrypt: %v", err)
return
}
return
}); err != nil {
return nil, err
}
dst = append(dst, result...)
return dst, nil
}
90 changes: 90 additions & 0 deletions block.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright 2018 Thales e-Security, Inc
//
// 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.

package crypto11

import (
"fmt"
"github.com/miekg/pkcs11"
)

// cipher.Block ---------------------------------------------------------

// BlockSize returns the cipher's block size in bytes.
func (key *PKCS11SecretKey) BlockSize() int {
return key.Cipher.BlockSize
}

// Decrypt decrypts the first block in src into dst.
// Dst and src must overlap entirely or not at all.
//
// Using this method for bulk operation is very inefficient, as it makes a round trip to the HSM
// (which may be network-connected) for each block.
// For more efficient operation, see NewCBCDecrypterCloser, NewCBCDecrypter or NewCBC.
func (key *PKCS11SecretKey) Decrypt(dst, src []byte) {
var result []byte
if err := withSession(key.Slot, func(session *PKCS11Session) (err error) {
mech := []*pkcs11.Mechanism{pkcs11.NewMechanism(key.Cipher.ECBMech, nil)}
if err = session.Ctx.DecryptInit(session.Handle, mech, key.Handle); err != nil {
return
}
if result, err = session.Ctx.Decrypt(session.Handle, src[:key.Cipher.BlockSize]); err != nil {
return
}
if len(result) != key.Cipher.BlockSize {
err = fmt.Errorf("C_Decrypt: returned %v bytes, wanted %v", len(result), key.Cipher.BlockSize)
return
}
return
}); err != nil {
panic(err)
} else {
copy(dst[:key.Cipher.BlockSize], result)
}
}

// Encrypt encrypts the first block in src into dst.
// Dst and src must overlap entirely or not at all.
//
// Using this method for bulk operation is very inefficient, as it makes a round trip to the HSM
// (which may be network-connected) for each block.
// For more efficient operation, see NewCBCEncrypterCloser, NewCBCEncrypter or NewCBC.
func (key *PKCS11SecretKey) Encrypt(dst, src []byte) {
var result []byte
if err := withSession(key.Slot, func(session *PKCS11Session) (err error) {
mech := []*pkcs11.Mechanism{pkcs11.NewMechanism(key.Cipher.ECBMech, nil)}
if err = session.Ctx.EncryptInit(session.Handle, mech, key.Handle); err != nil {
return
}
if result, err = session.Ctx.Encrypt(session.Handle, src[:key.Cipher.BlockSize]); err != nil {
return
}
if len(result) != key.Cipher.BlockSize {
err = fmt.Errorf("C_Encrypt: unexpectedly returned %v bytes, wanted %v", len(result), key.Cipher.BlockSize)
return
}
return
}); err != nil {
panic(err)
} else {
copy(dst[:key.Cipher.BlockSize], result)
}
}
Loading

0 comments on commit f2a4754

Please sign in to comment.