github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/keys/yubikey_fake.go (about)

     1  //go:build pivtest
     2  
     3  /*
     4  Copyright 2024 Gravitational, Inc.
     5  Licensed under the Apache License, Version 2.0 (the "License");
     6  you may not use this file except in compliance with the License.
     7  You may obtain a copy of the License at
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package keys
    17  
    18  import (
    19  	"context"
    20  	"crypto"
    21  	"crypto/ed25519"
    22  	"crypto/rand"
    23  	"errors"
    24  
    25  	"github.com/gravitational/trace"
    26  )
    27  
    28  var errPIVUnavailable = errors.New("PIV is unavailable in current build")
    29  
    30  // Return a fake YubiKey private key.
    31  func getOrGenerateYubiKeyPrivateKey(_ context.Context, policy PrivateKeyPolicy, _ PIVSlot) (*PrivateKey, error) {
    32  	_, priv, err := ed25519.GenerateKey(rand.Reader)
    33  	if err != nil {
    34  		return nil, trace.Wrap(err)
    35  	}
    36  
    37  	keyPEM, err := MarshalPrivateKey(priv)
    38  	if err != nil {
    39  		return nil, trace.Wrap(err)
    40  	}
    41  
    42  	signer := &fakeYubiKeyPrivateKey{
    43  		Signer:           priv,
    44  		privateKeyPolicy: policy,
    45  	}
    46  
    47  	return NewPrivateKey(signer, keyPEM)
    48  }
    49  
    50  func parseYubiKeyPrivateKeyData(_ []byte) (*PrivateKey, error) {
    51  	// TODO(Joerger): add custom marshal/unmarshal logic for fakeYubiKeyPrivateKey (if necessary).
    52  	return nil, trace.Wrap(errPIVUnavailable)
    53  }
    54  
    55  func (s PIVSlot) validate() error {
    56  	return trace.Wrap(errPIVUnavailable)
    57  }
    58  
    59  type fakeYubiKeyPrivateKey struct {
    60  	crypto.Signer
    61  	privateKeyPolicy PrivateKeyPolicy
    62  }
    63  
    64  // GetAttestationStatement returns an AttestationStatement for this private key.
    65  func (y *fakeYubiKeyPrivateKey) GetAttestationStatement() *AttestationStatement {
    66  	// Since this is only used in tests, we will ignore the attestation statement in the end.
    67  	// We just need it to be non-nil so that it goes through the test modules implementation
    68  	// of AttestHardwareKey.
    69  	return &AttestationStatement{}
    70  }
    71  
    72  // GetPrivateKeyPolicy returns the PrivateKeyPolicy supported by this private key.
    73  func (y *fakeYubiKeyPrivateKey) GetPrivateKeyPolicy() PrivateKeyPolicy {
    74  	return y.privateKeyPolicy
    75  }