sshkey.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package sshkey provides functionality for generating SSH key pairs.
  14. package sshkey
  15. import (
  16. "context"
  17. "crypto/ed25519"
  18. "crypto/rand"
  19. "crypto/rsa"
  20. "encoding/pem"
  21. "errors"
  22. "fmt"
  23. "golang.org/x/crypto/ssh"
  24. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  25. "sigs.k8s.io/controller-runtime/pkg/client"
  26. "sigs.k8s.io/yaml"
  27. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  28. )
  29. // Generator implements SSH key pair generation functionality.
  30. type Generator struct{}
  31. const (
  32. defaultKeyType = "rsa"
  33. defaultKeySize = 2048
  34. errNoSpec = "no config spec provided"
  35. errParseSpec = "unable to parse spec: %w"
  36. errGenerateKey = "unable to generate SSH key: %w"
  37. errUnsupported = "unsupported key type: %s"
  38. )
  39. type generateFunc func(keyType string, keySize *int, comment string) (privateKey, publicKey []byte, err error)
  40. // Generate creates a new SSH key pair.
  41. func (g *Generator) Generate(_ context.Context, jsonSpec *apiextensions.JSON, _ client.Client, _ string) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  42. return g.generate(
  43. jsonSpec,
  44. generateSSHKey,
  45. )
  46. }
  47. // Cleanup performs any necessary cleanup after key generation.
  48. func (g *Generator) Cleanup(_ context.Context, _ *apiextensions.JSON, _ genv1alpha1.GeneratorProviderState, _ client.Client, _ string) error {
  49. return nil
  50. }
  51. func (g *Generator) generate(jsonSpec *apiextensions.JSON, keyGen generateFunc) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  52. if jsonSpec == nil {
  53. return nil, nil, errors.New(errNoSpec)
  54. }
  55. res, err := parseSpec(jsonSpec.Raw)
  56. if err != nil {
  57. return nil, nil, fmt.Errorf(errParseSpec, err)
  58. }
  59. keyType := defaultKeyType
  60. if res.Spec.KeyType != "" {
  61. keyType = res.Spec.KeyType
  62. }
  63. privateKey, publicKey, err := keyGen(keyType, res.Spec.KeySize, res.Spec.Comment)
  64. if err != nil {
  65. return nil, nil, fmt.Errorf(errGenerateKey, err)
  66. }
  67. return map[string][]byte{
  68. "privateKey": privateKey,
  69. "publicKey": publicKey,
  70. }, nil, nil
  71. }
  72. func generateSSHKey(keyType string, keySize *int, comment string) (privateKey, publicKey []byte, err error) {
  73. switch keyType {
  74. case "rsa":
  75. bits := 2048
  76. if keySize != nil {
  77. bits = *keySize
  78. }
  79. return generateRSAKey(bits, comment)
  80. case "ed25519":
  81. return generateEd25519Key(comment)
  82. default:
  83. return nil, nil, fmt.Errorf(errUnsupported, keyType)
  84. }
  85. }
  86. func generateRSAKey(keySize int, comment string) (privateKey, publicKey []byte, err error) {
  87. // Generate RSA private key
  88. rsaKey, err := rsa.GenerateKey(rand.Reader, keySize)
  89. if err != nil {
  90. return nil, nil, err
  91. }
  92. // Create SSH private key in OpenSSH format
  93. sshPrivateKey, err := ssh.MarshalPrivateKey(rsaKey, comment)
  94. if err != nil {
  95. return nil, nil, err
  96. }
  97. // Create SSH public key
  98. sshPublicKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)
  99. if err != nil {
  100. return nil, nil, err
  101. }
  102. publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
  103. if comment != "" {
  104. // Remove the newline and add comment
  105. publicKeyStr := string(publicKeyBytes[:len(publicKeyBytes)-1]) + " " + comment + "\n"
  106. publicKeyBytes = []byte(publicKeyStr)
  107. }
  108. return pem.EncodeToMemory(sshPrivateKey), publicKeyBytes, nil
  109. }
  110. func generateEd25519Key(comment string) (privateKey, publicKey []byte, err error) {
  111. // Generate Ed25519 private key
  112. _, ed25519PrivateKey, err := ed25519.GenerateKey(rand.Reader)
  113. if err != nil {
  114. return nil, nil, err
  115. }
  116. // Create SSH private key in OpenSSH format
  117. sshPrivateKey, err := ssh.MarshalPrivateKey(ed25519PrivateKey, comment)
  118. if err != nil {
  119. return nil, nil, err
  120. }
  121. // Create SSH public key
  122. sshPublicKey, err := ssh.NewPublicKey(ed25519PrivateKey.Public())
  123. if err != nil {
  124. return nil, nil, err
  125. }
  126. publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
  127. if comment != "" {
  128. // Remove the newline and add comment
  129. publicKeyStr := string(publicKeyBytes[:len(publicKeyBytes)-1]) + " " + comment + "\n"
  130. publicKeyBytes = []byte(publicKeyStr)
  131. }
  132. return pem.EncodeToMemory(sshPrivateKey), publicKeyBytes, nil
  133. }
  134. func parseSpec(data []byte) (*genv1alpha1.SSHKey, error) {
  135. var spec genv1alpha1.SSHKey
  136. err := yaml.Unmarshal(data, &spec)
  137. return &spec, err
  138. }
  139. func init() {
  140. genv1alpha1.Register(genv1alpha1.SSHKeyKind, &Generator{})
  141. }