/* 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" "log" "os" "strings" "syscall" "github.com/ThalesIgnite/crypto11" "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) 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.infoLog.Printf("using PKCS#11 module %s", p11Config.Path) a.infoLog.Printf("looking for token with label %s", p11Config.TokenLabel) p11Config.Pin, err = getPin(p11Config, a.infoLog) if err != nil { return nil, err } p11Context, err = crypto11.Configure(p11Config) if err != nil { return nil, fmt.Errorf("could not configure PKCS#11 library: %w", err) } return p11Context, nil } func getPin(p11Config *crypto11.Config, infoLog *log.Logger) (string, error) { 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 { infoLog.Printf("environment variable %s has not been set", tokenPinEnv) if !term.IsTerminal(syscall.Stdin) { return "", errors.New("stdin is not a terminal") } _, 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 { return "", fmt.Errorf("could not read PIN: %w", err) } _, 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 }