cacert-gosigner/internal/hsm/storage.go

104 lines
2.5 KiB
Go
Raw Normal View History

2022-04-24 07:25:04 +00:00
/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hsm
import (
"errors"
"fmt"
"os"
"strings"
"syscall"
"github.com/ThalesIgnite/crypto11"
"github.com/sirupsen/logrus"
"golang.org/x/term"
)
func (a *Access) prepareCrypto11Context(label string) (*crypto11.Context, error) {
var (
err error
p11Context *crypto11.Context
)
storage, err := a.GetSignerConfig().GetKeyStorage(label)
2022-04-24 12:05:46 +00:00
if err != nil {
return nil, fmt.Errorf("key storage %s not available: %w", label, err)
}
p11Config := &crypto11.Config{
Path: storage.Module,
TokenLabel: storage.Label,
}
a.logger.Infof("using PKCS#11 module %s", p11Config.Path)
a.logger.Infof("looking for token with label %s", p11Config.TokenLabel)
p11Config.Pin, err = getPin(p11Config, a.logger)
if err != nil {
return nil, err
}
p11Context, err = crypto11.Configure(p11Config)
if err != nil {
2022-04-24 07:25:04 +00:00
return nil, fmt.Errorf("could not configure PKCS#11 library: %w", err)
}
return p11Context, nil
}
func getPin(p11Config *crypto11.Config, logger *logrus.Logger) (string, error) {
2022-04-24 07:25:04 +00:00
var err error
tokenPinEnv := strings.NewReplacer(
"-", "_",
" ", "_",
"(", "_",
")", "_",
).Replace(p11Config.TokenLabel)
tokenPinEnv = strings.ToUpper(tokenPinEnv)
tokenPinEnv = fmt.Sprintf("TOKEN_PIN_%s", tokenPinEnv)
pin, found := os.LookupEnv(tokenPinEnv)
if !found {
logger.Warnf("environment variable %s has not been set", tokenPinEnv)
if !term.IsTerminal(syscall.Stdin) {
return "", errors.New("stdin is not a terminal")
}
2022-04-24 07:25:04 +00:00
_, err = fmt.Fprintf(os.Stdout, "Enter PIN for token %s: ", p11Config.TokenLabel)
if err != nil {
return "", fmt.Errorf("could not write PIN prompt: %w", err)
}
bytePin, err := term.ReadPassword(syscall.Stdin)
if err != nil {
2022-04-24 07:25:04 +00:00
return "", fmt.Errorf("could not read PIN: %w", err)
}
2022-04-24 07:25:04 +00:00
_, err = fmt.Fprintln(os.Stdout)
if err != nil {
return "", fmt.Errorf("could not write to stdout: %w", err)
}
pin = string(bytePin)
}
return strings.TrimSpace(pin), nil
}