1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
|
// Copyright 2016, 2017 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 (
"encoding/json"
"fmt"
"log"
"math/rand"
"os"
"testing"
"time"
"github.com/miekg/pkcs11"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeysPersistAcrossContexts(t *testing.T) {
// Verify that close and re-open works.
ctx, err := ConfigureFromFile("config")
require.NoError(t, err)
id := randomBytes()
_, err = ctx.GenerateRSAKeyPair(id, rsaSize)
if err != nil {
_ = ctx.Close()
t.Fatal(err)
}
require.NoError(t, ctx.Close())
ctx, err = ConfigureFromFile("config")
require.NoError(t, err)
key2, err := ctx.FindKeyPair(id, nil)
require.NoError(t, err)
testRsaSigning(t, key2, false)
_ = key2.Delete()
require.NoError(t, ctx.Close())
}
func configureWithPin(t *testing.T) (*Context, error) {
cfg, err := getConfig("config")
if err != nil {
t.Fatal(err)
}
if cfg.Pin == "" {
t.Fatal("invalid configuration. configuration must have PIN non empty.")
}
ctx, err := Configure(cfg)
if err != nil {
t.Fatal("failed to configure service:", err)
}
return ctx, nil
}
func getConfig(configLocation string) (ctx *Config, err error) {
file, err := os.Open(configLocation)
if err != nil {
log.Printf("Could not open config file: %s", configLocation)
return nil, err
}
defer func() {
err = file.Close()
}()
configDecoder := json.NewDecoder(file)
config := &Config{}
err = configDecoder.Decode(config)
if err != nil {
log.Printf("Could decode config file: %s", err.Error())
return nil, err
}
return config, nil
}
func TestKeyPairDelete(t *testing.T) {
ctx, err := ConfigureFromFile("config")
require.NoError(t, err)
defer func() {
require.NoError(t, ctx.Close())
}()
id := randomBytes()
key, err := ctx.GenerateRSAKeyPair(id, 2048)
require.NoError(t, err)
// Check we can find it
_, err = ctx.FindKeyPair(id, nil)
require.NoError(t, err)
err = key.Delete()
require.NoError(t, err)
k, err := ctx.FindKeyPair(id, nil)
require.NoError(t, err)
require.Nil(t, k)
}
func TestKeyDelete(t *testing.T) {
ctx, err := ConfigureFromFile("config")
require.NoError(t, err)
defer func() {
require.NoError(t, ctx.Close())
}()
id := randomBytes()
key, err := ctx.GenerateSecretKey(id, 128, CipherAES)
require.NoError(t, err)
// Check we can find it
_, err = ctx.FindKey(id, nil)
require.NoError(t, err)
err = key.Delete()
require.NoError(t, err)
k, err := ctx.FindKey(id, nil)
require.NoError(t, err)
require.Nil(t, k)
}
func TestAmbiguousTokenConfig(t *testing.T) {
slotNum := 1
tests := []struct {
config *Config
err string
}{
{
config: &Config{TokenSerial: "serial", TokenLabel: "label"},
err: "config must specify exactly one way to select a token: token label, token serial number given",
},
{
config: &Config{TokenSerial: "serial", SlotNumber: &slotNum},
err: "config must specify exactly one way to select a token: slot number, token serial number given",
},
{
config: &Config{SlotNumber: &slotNum, TokenLabel: "label"},
err: "config must specify exactly one way to select a token: slot number, token label given",
},
{
config: &Config{},
err: "config must specify exactly one way to select a token: none given",
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("test_%d", i), func(t *testing.T) {
_, err := Configure(test.config)
if assert.Error(t, err) {
assert.Equal(t, test.err, err.Error())
}
})
}
}
func TestSelectBySlot(t *testing.T) {
config, err := loadConfigFromFile("config")
require.NoError(t, err)
// Look up slot number for label
ctx, err := Configure(config)
require.NoError(t, err)
slotNumber := int(ctx.slot)
t.Logf("Using slot %d", slotNumber)
err = ctx.Close()
require.NoError(t, err)
slotConfig := &Config{
SlotNumber: &slotNumber,
Pin: config.Pin,
Path: config.Path,
}
ctx, err = Configure(slotConfig)
require.NoError(t, err)
slotNumber2 := int(ctx.slot)
err = ctx.Close()
require.NoError(t, err)
assert.Equal(t, slotNumber, slotNumber2)
}
func TestSelectByNonExistingSlot(t *testing.T) {
config, err := loadConfigFromFile("config")
require.NoError(t, err)
rand.Seed(time.Now().UnixNano())
randomSlot := int(rand.Uint32())
config.TokenLabel = ""
config.TokenSerial = ""
config.SlotNumber = &randomSlot
// Look up slot number for label
_, err = Configure(config)
require.Equal(t, errTokenNotFound, err)
}
func TestAccessSameLibraryTwice(t *testing.T) {
ctx1, err := ConfigureFromFile("config")
require.NoError(t, err)
ctx2, err := ConfigureFromFile("config")
require.NoError(t, err)
// Close the first context, which shouldn't render the second
// context unusable
err = ctx1.Close()
require.NoError(t, err)
// Try to find a non-existant key. We are just checking that we can
// use the underlying P11 lib.
_, err = ctx2.FindKey(randomBytes(), nil)
require.NoError(t, err)
err = ctx2.Close()
require.NoError(t, err)
// Check we can open this again and use it without error
ctx3, err := ConfigureFromFile("config")
require.NoError(t, err)
// Try to find a non-existant key. We are just checking that we can
// use the underlying P11 lib.
_, err = ctx3.FindKey(randomBytes(), nil)
require.NoError(t, err)
err = ctx3.Close()
require.NoError(t, err)
}
func TestNoLogin(t *testing.T) {
// To test that no login is respected, we attempt to perform an operation on our
// SoftHSM HSM without logging in and check for the error.
cfg, err := getConfig("config")
require.NoError(t, err)
cfg.LoginNotSupported = true
ctx, err := Configure(cfg)
require.NoError(t, err)
_, err = ctx.GenerateSecretKey(randomBytes(), 256, CipherAES)
require.Error(t, err)
p11Err, ok := err.(pkcs11.Error)
require.True(t, ok)
assert.Equal(t, pkcs11.Error(pkcs11.CKR_USER_NOT_LOGGED_IN), p11Err)
}
func TestInvalidMaxSessions(t *testing.T) {
cfg, err := getConfig("config")
require.NoError(t, err)
cfg.MaxSessions = 1
_, err = Configure(cfg)
require.Error(t, err)
}
// randomBytes returns 32 random bytes.
func randomBytes() []byte {
result := make([]byte, 32)
rand.Read(result)
return result
}
func init() {
rand.Seed(time.Now().UnixNano())
}
|