sshkeypairs.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2019 Yunion
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sshkeys
  15. import (
  16. "context"
  17. "yunion.io/x/pkg/utils"
  18. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  19. "yunion.io/x/onecloud/pkg/mcclient/auth"
  20. "yunion.io/x/onecloud/pkg/util/seclib2"
  21. )
  22. const (
  23. sshAdminPrivateKey = "admin-ssh-private-key"
  24. sshAdminPublicKey = "admin-ssh-public-key"
  25. sshPrivateKey = "project-ssh-private-key"
  26. sshPublicKey = "project-ssh-public-key"
  27. )
  28. func _getKeys(ctx context.Context, tenantId string, privateKey, publicKey string) (string, string, error) {
  29. tenant, err := db.TenantCacheManager.FetchTenantById(ctx, tenantId)
  30. if err != nil {
  31. return "", "", err
  32. }
  33. private := tenant.GetMetadata(ctx, privateKey, nil)
  34. public := tenant.GetMetadata(ctx, publicKey, nil)
  35. userCred := auth.AdminCredential()
  36. if len(private) == 0 || len(public) == 0 {
  37. private, public, _ = seclib2.GenerateRSASSHKeypair()
  38. private, _ = utils.EncryptAESBase64(tenantId, private)
  39. tenant.SetMetadata(ctx, privateKey, private, userCred)
  40. tenant.SetMetadata(ctx, publicKey, public, userCred)
  41. }
  42. private, _ = utils.DescryptAESBase64(tenantId, private)
  43. return private, public, nil
  44. }
  45. func GetSshProjectKeypair(ctx context.Context, tenantId string) (string, string, error) {
  46. return _getKeys(ctx, tenantId, sshPrivateKey, sshPublicKey)
  47. }
  48. func GetSshAdminKeypair(ctx context.Context) (string, string, error) {
  49. userCred := auth.AdminCredential()
  50. return _getKeys(ctx, userCred.GetProjectId(), sshAdminPrivateKey, sshAdminPublicKey)
  51. }