...

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

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

     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 Mac OS using keychain utils.
    16  // This server is intended to be launched as a subprocess by the signer client,
    17  // and should not be launched manually as a stand-alone process.
    18  package main
    19  
    20  import (
    21  	"crypto"
    22  	"crypto/rsa"
    23  	"crypto/x509"
    24  	"encoding/gob"
    25  	"io"
    26  	"log"
    27  	"net/rpc"
    28  	"os"
    29  	"time"
    30  
    31  	"github.com/googleapis/enterprise-certificate-proxy/internal/signer/darwin/keychain"
    32  	"github.com/googleapis/enterprise-certificate-proxy/internal/signer/util"
    33  )
    34  
    35  // If ECP Logging is enabled return true
    36  // Otherwise return false
    37  func enableECPLogging() bool {
    38  	if os.Getenv("ENABLE_ENTERPRISE_CERTIFICATE_LOGS") != "" {
    39  		return true
    40  	}
    41  
    42  	log.SetOutput(io.Discard)
    43  	return false
    44  }
    45  
    46  func init() {
    47  	gob.Register(crypto.SHA256)
    48  	gob.Register(crypto.SHA384)
    49  	gob.Register(crypto.SHA512)
    50  	gob.Register(&rsa.PSSOptions{})
    51  	gob.Register(&rsa.OAEPOptions{})
    52  }
    53  
    54  // SignArgs contains arguments for a Sign API call.
    55  type SignArgs struct {
    56  	Digest []byte            // The content to sign.
    57  	Opts   crypto.SignerOpts // Options for signing. Must implement HashFunc().
    58  }
    59  
    60  // EncryptArgs contains arguments for an Encrypt API call.
    61  type EncryptArgs struct {
    62  	Plaintext []byte // The plaintext to encrypt.
    63  	Opts      any    // Options for encryption. Ex: an instance of crypto.Hash.
    64  }
    65  
    66  // DecryptArgs contains arguments to for a Decrypt API call.
    67  type DecryptArgs struct {
    68  	Ciphertext []byte               // The ciphertext to decrypt.
    69  	Opts       crypto.DecrypterOpts // Options for decryption. Ex: an instance of *rsa.OAEPOptions.
    70  }
    71  
    72  // A EnterpriseCertSigner exports RPC methods for signing.
    73  type EnterpriseCertSigner struct {
    74  	key *keychain.Key
    75  }
    76  
    77  // A Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser.
    78  type Connection struct {
    79  	io.ReadCloser
    80  	io.WriteCloser
    81  }
    82  
    83  // Close closes c's underlying ReadCloser and WriteCloser.
    84  func (c *Connection) Close() error {
    85  	rerr := c.ReadCloser.Close()
    86  	werr := c.WriteCloser.Close()
    87  	if rerr != nil {
    88  		return rerr
    89  	}
    90  	return werr
    91  }
    92  
    93  // CertificateChain returns the credential as a raw X509 cert chain. This
    94  // contains the public key.
    95  func (k *EnterpriseCertSigner) CertificateChain(ignored struct{}, certificateChain *[][]byte) error {
    96  	*certificateChain = k.key.CertificateChain()
    97  	return nil
    98  }
    99  
   100  // Public returns the corresponding public key for this Key, in ASN.1 DER form.
   101  func (k *EnterpriseCertSigner) Public(ignored struct{}, publicKey *[]byte) (err error) {
   102  	*publicKey, err = x509.MarshalPKIXPublicKey(k.key.Public())
   103  	return
   104  }
   105  
   106  // Sign signs a message digest. Stores result in "resp".
   107  func (k *EnterpriseCertSigner) Sign(args SignArgs, resp *[]byte) (err error) {
   108  	*resp, err = k.key.Sign(nil, args.Digest, args.Opts)
   109  	return
   110  }
   111  
   112  // Encrypt encrypts a plaintext message digest. Stores result in "resp".
   113  func (k *EnterpriseCertSigner) Encrypt(args EncryptArgs, resp *[]byte) (err error) {
   114  	*resp, err = k.key.Encrypt(args.Plaintext, args.Opts)
   115  	return
   116  }
   117  
   118  // Decrypt decrypts a ciphertext message digest. Stores result in "resp".
   119  func (k *EnterpriseCertSigner) Decrypt(args DecryptArgs, resp *[]byte) (err error) {
   120  	*resp, err = k.key.Decrypt(args.Ciphertext, args.Opts)
   121  	return
   122  }
   123  
   124  func main() {
   125  	enableECPLogging()
   126  	if len(os.Args) != 2 {
   127  		log.Fatalln("Signer is not meant to be invoked manually, exiting...")
   128  	}
   129  	configFilePath := os.Args[1]
   130  	config, err := util.LoadConfig(configFilePath)
   131  	if err != nil {
   132  		log.Fatalf("Failed to load enterprise cert config: %v", err)
   133  	}
   134  
   135  	enterpriseCertSigner := new(EnterpriseCertSigner)
   136  	enterpriseCertSigner.key, err = keychain.Cred(config.CertConfigs.MacOSKeychain.Issuer)
   137  	if err != nil {
   138  		log.Fatalf("Failed to initialize enterprise cert signer using keychain: %v", err)
   139  	}
   140  
   141  	if err := rpc.Register(enterpriseCertSigner); err != nil {
   142  		log.Fatalf("Failed to register enterprise cert signer with net/rpc: %v", err)
   143  	}
   144  
   145  	// If the parent process dies, we should exit.
   146  	// We can detect this by periodically checking if the PID of the parent
   147  	// process is 1 (https://stackoverflow.com/a/2035683).
   148  	go func() {
   149  		for {
   150  			if os.Getppid() == 1 {
   151  				log.Fatalln("Enterprise cert signer's parent process died, exiting...")
   152  			}
   153  			time.Sleep(time.Second)
   154  		}
   155  	}()
   156  
   157  	rpc.ServeConn(&Connection{os.Stdin, os.Stdout})
   158  }
   159  

View as plain text