client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. // Package client is a cross-platform client for the signer binary (a.k.a."EnterpriseCertSigner").
  14. //
  15. // The signer binary is OS-specific, but exposes a standard set of APIs for the client to use.
  16. package client
  17. import (
  18. "crypto"
  19. "crypto/ecdsa"
  20. "crypto/rsa"
  21. "crypto/x509"
  22. "encoding/gob"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net/rpc"
  27. "os"
  28. "os/exec"
  29. "github.com/googleapis/enterprise-certificate-proxy/client/util"
  30. )
  31. const signAPI = "EnterpriseCertSigner.Sign"
  32. const certificateChainAPI = "EnterpriseCertSigner.CertificateChain"
  33. const publicKeyAPI = "EnterpriseCertSigner.Public"
  34. // A Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser.
  35. type Connection struct {
  36. io.ReadCloser
  37. io.WriteCloser
  38. }
  39. // Close closes c's underlying ReadCloser and WriteCloser.
  40. func (c *Connection) Close() error {
  41. rerr := c.ReadCloser.Close()
  42. werr := c.WriteCloser.Close()
  43. if rerr != nil {
  44. return rerr
  45. }
  46. return werr
  47. }
  48. func init() {
  49. gob.Register(crypto.SHA256)
  50. gob.Register(&rsa.PSSOptions{})
  51. }
  52. // SignArgs contains arguments to a crypto Signer.Sign method.
  53. type SignArgs struct {
  54. Digest []byte // The content to sign.
  55. Opts crypto.SignerOpts // Options for signing, such as Hash identifier.
  56. }
  57. // Key implements credential.Credential by holding the executed signer subprocess.
  58. type Key struct {
  59. cmd *exec.Cmd // Pointer to the signer subprocess.
  60. client *rpc.Client // Pointer to the rpc client that communicates with the signer subprocess.
  61. publicKey crypto.PublicKey // Public key of loaded certificate.
  62. chain [][]byte // Certificate chain of loaded certificate.
  63. }
  64. // CertificateChain returns the credential as a raw X509 cert chain. This contains the public key.
  65. func (k *Key) CertificateChain() [][]byte {
  66. return k.chain
  67. }
  68. // Close closes the RPC connection and kills the signer subprocess.
  69. // Call this to free up resources when the Key object is no longer needed.
  70. func (k *Key) Close() error {
  71. if err := k.cmd.Process.Kill(); err != nil {
  72. return fmt.Errorf("failed to kill signer process: %w", err)
  73. }
  74. // Wait for cmd to exit and release resources. Since the process is forcefully killed, this
  75. // will return a non-nil error (varies by OS), which we will ignore.
  76. _ = k.cmd.Wait()
  77. // The Pipes connecting the RPC client should have been closed when the signer subprocess was killed.
  78. // Calling `k.client.Close()` before `k.cmd.Process.Kill()` or `k.cmd.Wait()` _will_ cause a segfault.
  79. if err := k.client.Close(); err.Error() != "close |0: file already closed" {
  80. return fmt.Errorf("failed to close RPC connection: %w", err)
  81. }
  82. return nil
  83. }
  84. // Public returns the public key for this Key.
  85. func (k *Key) Public() crypto.PublicKey {
  86. return k.publicKey
  87. }
  88. // Sign signs a message digest, using the specified signer options.
  89. func (k *Key) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signed []byte, err error) {
  90. if opts != nil && opts.HashFunc() != 0 && len(digest) != opts.HashFunc().Size() {
  91. return nil, fmt.Errorf("Digest length of %v bytes does not match Hash function size of %v bytes", len(digest), opts.HashFunc().Size())
  92. }
  93. err = k.client.Call(signAPI, SignArgs{Digest: digest, Opts: opts}, &signed)
  94. return
  95. }
  96. // ErrCredUnavailable is a sentinel error that indicates ECP Cred is unavailable,
  97. // possibly due to missing config or missing binary path.
  98. var ErrCredUnavailable = errors.New("Cred is unavailable")
  99. // Cred spawns a signer subprocess that listens on stdin/stdout to perform certificate
  100. // related operations, including signing messages with the private key.
  101. //
  102. // The signer binary path is read from the specified configFilePath, if provided.
  103. // Otherwise, use the default config file path.
  104. //
  105. // The config file also specifies which certificate the signer should use.
  106. func Cred(configFilePath string) (*Key, error) {
  107. if configFilePath == "" {
  108. configFilePath = util.GetDefaultConfigFilePath()
  109. }
  110. enterpriseCertSignerPath, err := util.LoadSignerBinaryPath(configFilePath)
  111. if err != nil {
  112. if errors.Is(err, util.ErrConfigUnavailable) {
  113. return nil, ErrCredUnavailable
  114. }
  115. return nil, err
  116. }
  117. k := &Key{
  118. cmd: exec.Command(enterpriseCertSignerPath, configFilePath),
  119. }
  120. // Redirect errors from subprocess to parent process.
  121. k.cmd.Stderr = os.Stderr
  122. // RPC client will communicate with subprocess over stdin/stdout.
  123. kin, err := k.cmd.StdinPipe()
  124. if err != nil {
  125. return nil, err
  126. }
  127. kout, err := k.cmd.StdoutPipe()
  128. if err != nil {
  129. return nil, err
  130. }
  131. k.client = rpc.NewClient(&Connection{kout, kin})
  132. if err := k.cmd.Start(); err != nil {
  133. return nil, fmt.Errorf("starting enterprise cert signer subprocess: %w", err)
  134. }
  135. if err := k.client.Call(certificateChainAPI, struct{}{}, &k.chain); err != nil {
  136. return nil, fmt.Errorf("failed to retrieve certificate chain: %w", err)
  137. }
  138. var publicKeyBytes []byte
  139. if err := k.client.Call(publicKeyAPI, struct{}{}, &publicKeyBytes); err != nil {
  140. return nil, fmt.Errorf("failed to retrieve public key: %w", err)
  141. }
  142. publicKey, err := x509.ParsePKIXPublicKey(publicKeyBytes)
  143. if err != nil {
  144. return nil, fmt.Errorf("failed to parse public key: %w", err)
  145. }
  146. var ok bool
  147. k.publicKey, ok = publicKey.(crypto.PublicKey)
  148. if !ok {
  149. return nil, fmt.Errorf("invalid public key type: %T", publicKey)
  150. }
  151. switch pub := k.publicKey.(type) {
  152. case *rsa.PublicKey:
  153. if pub.Size() < 256 {
  154. return nil, fmt.Errorf("RSA modulus size is less than 2048 bits: %v", pub.Size()*8)
  155. }
  156. case *ecdsa.PublicKey:
  157. default:
  158. return nil, fmt.Errorf("unsupported public key type: %v", pub)
  159. }
  160. return k, nil
  161. }