sshkey.go 4.5 KB

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