client.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. const encryptAPI = "EnterpriseCertSigner.Encrypt"
  35. const decryptAPI = "EnterpriseCertSigner.Decrypt"
  36. // A Connection wraps a pair of unidirectional streams as an io.ReadWriteCloser.
  37. type Connection struct {
  38. io.ReadCloser
  39. io.WriteCloser
  40. }
  41. // Close closes c's underlying ReadCloser and WriteCloser.
  42. func (c *Connection) Close() error {
  43. rerr := c.ReadCloser.Close()
  44. werr := c.WriteCloser.Close()
  45. if rerr != nil {
  46. return rerr
  47. }
  48. return werr
  49. }
  50. func init() {
  51. gob.Register(crypto.SHA256)
  52. gob.Register(crypto.SHA384)
  53. gob.Register(crypto.SHA512)
  54. gob.Register(&rsa.PSSOptions{})
  55. gob.Register(&rsa.OAEPOptions{})
  56. }
  57. // SignArgs contains arguments for a Sign API call.
  58. type SignArgs struct {
  59. Digest []byte // The content to sign.
  60. Opts crypto.SignerOpts // Options for signing. Must implement HashFunc().
  61. }
  62. // EncryptArgs contains arguments for an Encrypt API call.
  63. type EncryptArgs struct {
  64. Plaintext []byte // The plaintext to encrypt.
  65. Opts any // Options for encryption. Ex: an instance of crypto.Hash.
  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. // Key implements credential.Credential by holding the executed signer subprocess.
  73. type Key struct {
  74. cmd *exec.Cmd // Pointer to the signer subprocess.
  75. client *rpc.Client // Pointer to the rpc client that communicates with the signer subprocess.
  76. publicKey crypto.PublicKey // Public key of loaded certificate.
  77. chain [][]byte // Certificate chain of loaded certificate.
  78. }
  79. // CertificateChain returns the credential as a raw X509 cert chain. This contains the public key.
  80. func (k *Key) CertificateChain() [][]byte {
  81. return k.chain
  82. }
  83. // Close closes the RPC connection and kills the signer subprocess.
  84. // Call this to free up resources when the Key object is no longer needed.
  85. func (k *Key) Close() error {
  86. if err := k.cmd.Process.Kill(); err != nil {
  87. return fmt.Errorf("failed to kill signer process: %w", err)
  88. }
  89. // Wait for cmd to exit and release resources. Since the process is forcefully killed, this
  90. // will return a non-nil error (varies by OS), which we will ignore.
  91. _ = k.cmd.Wait()
  92. // The Pipes connecting the RPC client should have been closed when the signer subprocess was killed.
  93. // Calling `k.client.Close()` before `k.cmd.Process.Kill()` or `k.cmd.Wait()` _will_ cause a segfault.
  94. if err := k.client.Close(); err.Error() != "close |0: file already closed" {
  95. return fmt.Errorf("failed to close RPC connection: %w", err)
  96. }
  97. return nil
  98. }
  99. // Public returns the public key for this Key.
  100. func (k *Key) Public() crypto.PublicKey {
  101. return k.publicKey
  102. }
  103. // Sign signs a message digest, using the specified signer opts. Implements crypto.Signer interface.
  104. func (k *Key) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signed []byte, err error) {
  105. if opts != nil && opts.HashFunc() != 0 && len(digest) != opts.HashFunc().Size() {
  106. return nil, fmt.Errorf("Digest length of %v bytes does not match Hash function size of %v bytes", len(digest), opts.HashFunc().Size())
  107. }
  108. err = k.client.Call(signAPI, SignArgs{Digest: digest, Opts: opts}, &signed)
  109. return
  110. }
  111. // Encrypt encrypts a plaintext msg into ciphertext, using the specified encrypt opts.
  112. func (k *Key) Encrypt(_ io.Reader, msg []byte, opts any) (ciphertext []byte, err error) {
  113. err = k.client.Call(encryptAPI, EncryptArgs{Plaintext: msg, Opts: opts}, &ciphertext)
  114. return
  115. }
  116. // Decrypt decrypts a ciphertext msg into plaintext, using the specified decrypter opts. Implements crypto.Decrypter interface.
  117. func (k *Key) Decrypt(_ io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
  118. err = k.client.Call(decryptAPI, DecryptArgs{Ciphertext: msg, Opts: opts}, &plaintext)
  119. return
  120. }
  121. // ErrCredUnavailable is a sentinel error that indicates ECP Cred is unavailable,
  122. // possibly due to missing config or missing binary path.
  123. var ErrCredUnavailable = errors.New("Cred is unavailable")
  124. // Cred spawns a signer subprocess that listens on stdin/stdout to perform certificate
  125. // related operations, including signing messages with the private key.
  126. //
  127. // The signer binary path is read from the specified configFilePath, if provided.
  128. // Otherwise, use the default config file path.
  129. //
  130. // The config file also specifies which certificate the signer should use.
  131. func Cred(configFilePath string) (*Key, error) {
  132. if configFilePath == "" {
  133. envFilePath := util.GetConfigFilePathFromEnv()
  134. if envFilePath != "" {
  135. configFilePath = envFilePath
  136. } else {
  137. configFilePath = util.GetDefaultConfigFilePath()
  138. }
  139. }
  140. enterpriseCertSignerPath, err := util.LoadSignerBinaryPath(configFilePath)
  141. if err != nil {
  142. if errors.Is(err, util.ErrConfigUnavailable) {
  143. return nil, ErrCredUnavailable
  144. }
  145. return nil, err
  146. }
  147. k := &Key{
  148. cmd: exec.Command(enterpriseCertSignerPath, configFilePath),
  149. }
  150. // Redirect errors from subprocess to parent process.
  151. k.cmd.Stderr = os.Stderr
  152. // RPC client will communicate with subprocess over stdin/stdout.
  153. kin, err := k.cmd.StdinPipe()
  154. if err != nil {
  155. return nil, err
  156. }
  157. kout, err := k.cmd.StdoutPipe()
  158. if err != nil {
  159. return nil, err
  160. }
  161. k.client = rpc.NewClient(&Connection{kout, kin})
  162. if err := k.cmd.Start(); err != nil {
  163. return nil, fmt.Errorf("starting enterprise cert signer subprocess: %w", err)
  164. }
  165. if err := k.client.Call(certificateChainAPI, struct{}{}, &k.chain); err != nil {
  166. return nil, fmt.Errorf("failed to retrieve certificate chain: %w", err)
  167. }
  168. var publicKeyBytes []byte
  169. if err := k.client.Call(publicKeyAPI, struct{}{}, &publicKeyBytes); err != nil {
  170. return nil, fmt.Errorf("failed to retrieve public key: %w", err)
  171. }
  172. publicKey, err := x509.ParsePKIXPublicKey(publicKeyBytes)
  173. if err != nil {
  174. return nil, fmt.Errorf("failed to parse public key: %w", err)
  175. }
  176. var ok bool
  177. k.publicKey, ok = publicKey.(crypto.PublicKey)
  178. if !ok {
  179. return nil, fmt.Errorf("invalid public key type: %T", publicKey)
  180. }
  181. switch pub := k.publicKey.(type) {
  182. case *rsa.PublicKey:
  183. if pub.Size() < 256 {
  184. return nil, fmt.Errorf("RSA modulus size is less than 2048 bits: %v", pub.Size()*8)
  185. }
  186. case *ecdsa.PublicKey:
  187. default:
  188. return nil, fmt.Errorf("unsupported public key type: %v", pub)
  189. }
  190. return k, nil
  191. }