sshkey.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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
  14. import (
  15. "context"
  16. "crypto/ed25519"
  17. "crypto/rand"
  18. "crypto/rsa"
  19. "encoding/pem"
  20. "errors"
  21. "fmt"
  22. "golang.org/x/crypto/ssh"
  23. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. "sigs.k8s.io/yaml"
  26. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  27. )
  28. type Generator struct{}
  29. const (
  30. defaultKeyType = "rsa"
  31. defaultKeySize = 2048
  32. errNoSpec = "no config spec provided"
  33. errParseSpec = "unable to parse spec: %w"
  34. errGenerateKey = "unable to generate SSH key: %w"
  35. errUnsupported = "unsupported key type: %s"
  36. )
  37. type generateFunc func(keyType string, keySize *int, comment string) (privateKey, publicKey []byte, err error)
  38. func (g *Generator) Generate(_ context.Context, jsonSpec *apiextensions.JSON, _ client.Client, _ string) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  39. return g.generate(
  40. jsonSpec,
  41. generateSSHKey,
  42. )
  43. }
  44. func (g *Generator) Cleanup(_ context.Context, jsonSpec *apiextensions.JSON, state genv1alpha1.GeneratorProviderState, _ client.Client, _ string) error {
  45. return nil
  46. }
  47. func (g *Generator) generate(jsonSpec *apiextensions.JSON, keyGen generateFunc) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  48. if jsonSpec == nil {
  49. return nil, nil, errors.New(errNoSpec)
  50. }
  51. res, err := parseSpec(jsonSpec.Raw)
  52. if err != nil {
  53. return nil, nil, fmt.Errorf(errParseSpec, err)
  54. }
  55. keyType := defaultKeyType
  56. if res.Spec.KeyType != "" {
  57. keyType = res.Spec.KeyType
  58. }
  59. privateKey, publicKey, err := keyGen(keyType, res.Spec.KeySize, res.Spec.Comment)
  60. if err != nil {
  61. return nil, nil, fmt.Errorf(errGenerateKey, err)
  62. }
  63. return map[string][]byte{
  64. "privateKey": privateKey,
  65. "publicKey": publicKey,
  66. }, nil, nil
  67. }
  68. func generateSSHKey(keyType string, keySize *int, comment string) (privateKey, publicKey []byte, err error) {
  69. switch keyType {
  70. case "rsa":
  71. bits := 2048
  72. if keySize != nil {
  73. bits = *keySize
  74. }
  75. return generateRSAKey(bits, comment)
  76. case "ed25519":
  77. return generateEd25519Key(comment)
  78. default:
  79. return nil, nil, fmt.Errorf(errUnsupported, keyType)
  80. }
  81. }
  82. func generateRSAKey(keySize int, comment string) (privateKey, publicKey []byte, err error) {
  83. // Generate RSA private key
  84. rsaKey, err := rsa.GenerateKey(rand.Reader, keySize)
  85. if err != nil {
  86. return nil, nil, err
  87. }
  88. // Create SSH private key in OpenSSH format
  89. sshPrivateKey, err := ssh.MarshalPrivateKey(rsaKey, comment)
  90. if err != nil {
  91. return nil, nil, err
  92. }
  93. // Create SSH public key
  94. sshPublicKey, err := ssh.NewPublicKey(&rsaKey.PublicKey)
  95. if err != nil {
  96. return nil, nil, err
  97. }
  98. publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
  99. if comment != "" {
  100. // Remove the newline and add comment
  101. publicKeyStr := string(publicKeyBytes[:len(publicKeyBytes)-1]) + " " + comment + "\n"
  102. publicKeyBytes = []byte(publicKeyStr)
  103. }
  104. return pem.EncodeToMemory(sshPrivateKey), publicKeyBytes, nil
  105. }
  106. func generateEd25519Key(comment string) (privateKey, publicKey []byte, err error) {
  107. // Generate Ed25519 private key
  108. _, ed25519PrivateKey, err := ed25519.GenerateKey(rand.Reader)
  109. if err != nil {
  110. return nil, nil, err
  111. }
  112. // Create SSH private key in OpenSSH format
  113. sshPrivateKey, err := ssh.MarshalPrivateKey(ed25519PrivateKey, comment)
  114. if err != nil {
  115. return nil, nil, err
  116. }
  117. // Create SSH public key
  118. sshPublicKey, err := ssh.NewPublicKey(ed25519PrivateKey.Public())
  119. if err != nil {
  120. return nil, nil, err
  121. }
  122. publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
  123. if comment != "" {
  124. // Remove the newline and add comment
  125. publicKeyStr := string(publicKeyBytes[:len(publicKeyBytes)-1]) + " " + comment + "\n"
  126. publicKeyBytes = []byte(publicKeyStr)
  127. }
  128. return pem.EncodeToMemory(sshPrivateKey), publicKeyBytes, nil
  129. }
  130. func parseSpec(data []byte) (*genv1alpha1.SSHKey, error) {
  131. var spec genv1alpha1.SSHKey
  132. err := yaml.Unmarshal(data, &spec)
  133. return &spec, err
  134. }
  135. func init() {
  136. genv1alpha1.Register(genv1alpha1.SSHKeyKind, &Generator{})
  137. }