...

Source file src/github.com/googleapis/enterprise-certificate-proxy/internal/signer/linux/signer.go

Documentation: github.com/googleapis/enterprise-certificate-proxy/internal/signer/linux

     1  // Copyright 2022 Google LLC.
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  //     https://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // Signer.go is a net/rpc server that listens on stdin/stdout, exposing
    15  // methods that perform device certificate signing for Linux using PKCS11
    16  // shared library.
    17  // This server is intended to be launched as a subprocess by the signer client,
    18  // and should not be launched manually as a stand-alone process.
    19  package main
    20  
    21  import (
    22  	"crypto"
    23  	"crypto/rsa"
    24  	"crypto/x509"
    25  	"encoding/gob"
    26  	"io"
    27  	"log"
    28  	"net/rpc"
    29  	"os"
    30  	"time"
    31  
    32  	"github.com/googleapis/enterprise-certificate-proxy/internal/signer/linux/pkcs11"
    33  	"github.com/googleapis/enterprise-certificate-proxy/internal/signer/util"
    34  )
    35  
    36  // If ECP Logging is enabled return true
    37  // Otherwise return false
    38  func enableECPLogging() bool {
    39  	if os.Getenv("ENABLE_ENTERPRISE_CERTIFICATE_LOGS") != "" {
    40  		return true
    41  	}
    42  
    43  	log.SetOutput(io.Discard)
    44  	return false
    45  }
    46  
    47  func init() {
    48  	gob.Register(crypto.SHA256)
    49  	gob.Register(crypto.SHA384)
    50  	gob.Register(crypto.SHA512)
    51  	gob.Register(&rsa.PSSOptions{})
    52  	gob.Register(&rsa.OAEPOptions{})
    53  }
    54  
    55  // SignArgs contains arguments for a Sign API call.
    56  type SignArgs struct {
    57  	Digest []byte            // The content to sign.
    58  	Opts   crypto.SignerOpts // Options for signing. Must implement HashFunc().
    59  }
    60  
    61  // EncryptArgs contains arguments for an Encrypt API call.
    62  type EncryptArgs struct {
    63  	Plaintext []byte // The plaintext to encrypt.
    64  	Opts      any    // Options for encryption. Ex: an instance of crypto.Hash.
    65  }
    66  
    67  // DecryptArgs contains arguments to for a Decrypt API call.
    68  type DecryptArgs struct {
    69  	Ciphertext []byte               // The ciphertext to decrypt.
    70  	Opts       crypto.DecrypterOpts // Options for decryption. Ex: an instance of *rsa.OAEPOptions.
    71  }
    72  
    73  // A EnterpriseCertSigner exports RPC methods for signing.
    74  type EnterpriseCertSigner struct {
    75  	key *pkcs11.Key
    76  }
    77  
    78  // A Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser.
    79  type Connection struct {
    80  	io.ReadCloser
    81  	io.WriteCloser
    82  }
    83  
    84  // Close closes c's underlying ReadCloser and WriteCloser.
    85  func (c *Connection) Close() error {
    86  	rerr := c.ReadCloser.Close()
    87  	werr := c.WriteCloser.Close()
    88  	if rerr != nil {
    89  		return rerr
    90  	}
    91  	return werr
    92  }
    93  
    94  // CertificateChain returns the credential as a raw X509 cert chain. This
    95  // contains the public key.
    96  func (k *EnterpriseCertSigner) CertificateChain(ignored struct{}, certificateChain *[][]byte) (err error) {
    97  	*certificateChain = k.key.CertificateChain()
    98  	return nil
    99  }
   100  
   101  // Public returns the corresponding public key for this Key, in ASN.1 DER form.
   102  func (k *EnterpriseCertSigner) Public(ignored struct{}, publicKey *[]byte) (err error) {
   103  	*publicKey, err = x509.MarshalPKIXPublicKey(k.key.Public())
   104  	return
   105  }
   106  
   107  // Sign signs a message digest. Stores result in "resp".
   108  func (k *EnterpriseCertSigner) Sign(args SignArgs, resp *[]byte) (err error) {
   109  	*resp, err = k.key.Sign(nil, args.Digest, args.Opts)
   110  	return
   111  }
   112  
   113  // Encrypt encrypts a plaintext msg. Stores result in "resp".
   114  func (k *EnterpriseCertSigner) Encrypt(args EncryptArgs, resp *[]byte) (err error) {
   115  	*resp, err = k.key.Encrypt(args.Plaintext, args.Opts)
   116  	return
   117  }
   118  
   119  // Decrypt decrypts a ciphertext msg. Stores result in "resp".
   120  func (k *EnterpriseCertSigner) Decrypt(args DecryptArgs, resp *[]byte) (err error) {
   121  	*resp, err = k.key.Decrypt(args.Ciphertext, args.Opts)
   122  	return
   123  }
   124  
   125  func main() {
   126  	enableECPLogging()
   127  	if len(os.Args) != 2 {
   128  		log.Fatalln("Signer is not meant to be invoked manually, exiting...")
   129  	}
   130  	configFilePath := os.Args[1]
   131  	config, err := util.LoadConfig(configFilePath)
   132  	if err != nil {
   133  		log.Fatalf("Failed to load enterprise cert config: %v", err)
   134  	}
   135  
   136  	enterpriseCertSigner := new(EnterpriseCertSigner)
   137  	enterpriseCertSigner.key, err = pkcs11.Cred(config.CertConfigs.PKCS11.PKCS11Module, config.CertConfigs.PKCS11.Slot, config.CertConfigs.PKCS11.Label, config.CertConfigs.PKCS11.UserPin)
   138  	if err != nil {
   139  		log.Fatalf("Failed to initialize enterprise cert signer using pkcs11: %v", err)
   140  	}
   141  
   142  	if err := rpc.Register(enterpriseCertSigner); err != nil {
   143  		log.Fatalf("Failed to register enterprise cert signer with net/rpc: %v", err)
   144  	}
   145  
   146  	// If the parent process dies, we should exit.
   147  	// We can detect this by periodically checking if the PID of the parent
   148  	// process is 1 (https://stackoverflow.com/a/2035683).
   149  	go func() {
   150  		for {
   151  			if os.Getppid() == 1 {
   152  				log.Fatalln("Enterprise cert signer's parent process died, exiting...")
   153  			}
   154  			time.Sleep(time.Second)
   155  		}
   156  	}()
   157  
   158  	rpc.ServeConn(&Connection{os.Stdin, os.Stdout})
   159  }
   160  

View as plain text