Semaphore/db/AccessKey.go

308 lines
7.0 KiB
Go
Raw Normal View History

2017-02-23 06:12:16 +01:00
package db
2016-04-04 01:10:12 +02:00
import (
2021-08-31 01:02:41 +02:00
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
2021-09-01 16:38:28 +02:00
"encoding/json"
2021-08-31 01:02:41 +02:00
"fmt"
"io"
"io/ioutil"
"strconv"
"github.com/ansible-semaphore/semaphore/util"
)
2021-08-30 16:24:20 +02:00
const (
2021-09-01 16:38:28 +02:00
AccessKeySSH = "ssh"
AccessKeyNone = "none"
AccessKeyLoginPassword = "login_password"
2021-08-30 16:24:20 +02:00
)
// AccessKey represents a key used to access a machine with ansible from semaphore
2016-04-04 01:10:12 +02:00
type AccessKey struct {
ID int `db:"id" json:"id"`
Name string `db:"name" json:"name" binding:"required"`
2021-09-01 16:38:28 +02:00
// 'ssh/login_password/none'
2016-04-04 01:10:12 +02:00
Type string `db:"type" json:"type" binding:"required"`
2021-09-01 16:38:28 +02:00
ProjectID *int `db:"project_id" json:"project_id"`
// Secret used internally, do not assign this field.
// You should use methods SerializeSecret to fill this field.
Secret *string `db:"secret" json:"-"`
Removed bool `db:"removed" json:"removed"`
2021-09-01 16:38:28 +02:00
LoginPassword LoginPassword `db:"-" json:"login_password"`
SshKey SshKey `db:"-" json:"ssh"`
OverrideSecret bool `db:"-" json:"override_secret"`
2021-09-01 16:38:28 +02:00
}
type LoginPassword struct {
Login string `json:"login"`
Password string `json:"password"`
}
type SshKey struct {
Login string `json:"login"`
2021-09-01 16:38:28 +02:00
Passphrase string `json:"passphrase"`
PrivateKey string `json:"private_key"`
2016-04-04 01:10:12 +02:00
}
type AccessKeyUsage int
const (
AccessKeyUsageAnsibleUser = iota
AccessKeyUsageAnsibleBecomeUser
AccessKeyUsagePrivateKey
AccessKeyUsageVault
)
func (key AccessKey) Install(usage AccessKeyUsage) error {
if key.Type == AccessKeyNone {
return nil
}
path := key.GetPath()
err := key.DeserializeSecret()
if err != nil {
return err
}
switch usage {
case AccessKeyUsagePrivateKey:
if key.SshKey.Passphrase != "" {
return fmt.Errorf("ssh key with passphrase not supported")
}
return ioutil.WriteFile(path, []byte(key.SshKey.PrivateKey + "\n"), 0600)
case AccessKeyUsageVault:
switch key.Type {
case AccessKeyLoginPassword:
return ioutil.WriteFile(path, []byte(key.LoginPassword.Password), 0600)
}
case AccessKeyUsageAnsibleBecomeUser:
switch key.Type {
case AccessKeyLoginPassword:
2021-09-17 01:17:19 +02:00
content := make(map[string]string)
content["ansible_become_user"] = key.LoginPassword.Login
content["ansible_become_password"] = key.LoginPassword.Password
var bytes []byte
bytes, err = json.Marshal(content)
if err != nil {
return err
}
return ioutil.WriteFile(path, bytes, 0600)
default:
return fmt.Errorf("access key type not supported for ansible user")
}
case AccessKeyUsageAnsibleUser:
switch key.Type {
case AccessKeySSH:
if key.SshKey.Passphrase != "" {
return fmt.Errorf("ssh key with passphrase not supported")
}
return ioutil.WriteFile(path, []byte(key.SshKey.PrivateKey + "\n"), 0600)
case AccessKeyLoginPassword:
2021-09-17 01:17:19 +02:00
content := make(map[string]string)
content["ansible_user"] = key.LoginPassword.Login
content["ansible_password"] = key.LoginPassword.Password
var bytes []byte
bytes, err = json.Marshal(content)
if err != nil {
return err
}
return ioutil.WriteFile(path, bytes, 0600)
default:
return fmt.Errorf("access key type not supported for ansible user")
}
}
return nil
}
// GetPath returns the location of the access key once written to disk
func (key AccessKey) GetPath() string {
return util.Config.TmpPath + "/access_key_" + strconv.Itoa(key.ID)
}
2021-08-31 01:02:41 +02:00
func (key AccessKey) GetSshCommand() string {
if key.Type != AccessKeySSH {
panic("type must be ssh")
}
args := "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i " + key.GetPath()
if util.Config.SshConfigPath != "" {
args += " -F " + util.Config.SshConfigPath
}
return args
}
2021-09-01 16:38:28 +02:00
func (key AccessKey) Validate(validateSecretFields bool) error {
if key.Name == "" {
return fmt.Errorf("name can not be empty")
}
if !validateSecretFields {
return nil
}
switch key.Type {
case AccessKeySSH:
if key.SshKey.PrivateKey == "" {
return fmt.Errorf("private key can not be empty")
}
case AccessKeyLoginPassword:
if key.LoginPassword.Password == "" {
return fmt.Errorf("password can not be empty")
}
}
2021-09-01 16:38:28 +02:00
return nil
}
func (key *AccessKey) SerializeSecret() error {
var plaintext []byte
var err error
switch key.Type {
case AccessKeySSH:
plaintext, err = json.Marshal(key.SshKey)
if err != nil {
return err
}
case AccessKeyLoginPassword:
plaintext, err = json.Marshal(key.LoginPassword)
if err != nil {
return err
}
default:
key.Secret = nil
2021-08-31 01:02:41 +02:00
return nil
}
if util.Config.AccessKeyEncryption == "" {
2021-09-01 16:38:28 +02:00
secret := base64.StdEncoding.EncodeToString(plaintext)
key.Secret = &secret
return nil
}
2021-08-31 01:02:41 +02:00
encryption, err := base64.StdEncoding.DecodeString(util.Config.AccessKeyEncryption)
2021-08-31 01:02:41 +02:00
if err != nil {
return err
}
c, err := aes.NewCipher(encryption)
if err != nil {
return err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return err
}
secret := base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, plaintext, nil))
2021-08-31 01:02:41 +02:00
key.Secret = &secret
return nil
}
2021-09-01 16:38:28 +02:00
func (key *AccessKey) unmarshalAppropriateField(secret []byte) (err error) {
switch key.Type {
case AccessKeySSH:
sshKey := SshKey{}
err = json.Unmarshal(secret, &sshKey)
if err == nil {
key.SshKey = sshKey
}
case AccessKeyLoginPassword:
loginPass := LoginPassword{}
err = json.Unmarshal(secret, &loginPass)
if err == nil {
key.LoginPassword = loginPass
}
2021-08-31 01:02:41 +02:00
}
2021-09-01 16:38:28 +02:00
return
}
2021-08-31 01:02:41 +02:00
2021-09-01 16:38:28 +02:00
func (key *AccessKey) ResetSecret() {
//key.Secret = nil
2021-09-01 16:38:28 +02:00
key.LoginPassword = LoginPassword{}
key.SshKey = SshKey{}
}
2021-08-31 01:02:41 +02:00
2021-09-01 16:38:28 +02:00
func (key *AccessKey) DeserializeSecret() error {
if key.Secret == nil || *key.Secret == "" {
return nil
2021-08-31 01:02:41 +02:00
}
2021-09-01 16:38:28 +02:00
ciphertext := []byte(*key.Secret)
if ciphertext[len(*key.Secret)-1] == '\n' { // not encrypted private key, used for back compatibility
if key.Type != AccessKeySSH {
return fmt.Errorf("invalid access key type")
}
key.SshKey = SshKey{
PrivateKey: *key.Secret,
}
return nil
2021-08-31 01:02:41 +02:00
}
ciphertext, err := base64.StdEncoding.DecodeString(*key.Secret)
if err != nil {
2021-09-01 16:38:28 +02:00
return err
}
if util.Config.AccessKeyEncryption == "" {
err = key.unmarshalAppropriateField(ciphertext)
if _, ok := err.(*json.SyntaxError); ok {
err = fmt.Errorf("[ERR_INVALID_ENCRYPTION_KEY] Cannot decrypt access key, perhaps encryption key was changed")
}
return err
}
encryption, err := base64.StdEncoding.DecodeString(util.Config.AccessKeyEncryption)
2021-08-31 01:02:41 +02:00
if err != nil {
2021-09-01 16:38:28 +02:00
return err
2021-08-31 01:02:41 +02:00
}
c, err := aes.NewCipher(encryption)
if err != nil {
2021-09-01 16:38:28 +02:00
return err
2021-08-31 01:02:41 +02:00
}
gcm, err := cipher.NewGCM(c)
if err != nil {
2021-09-01 16:38:28 +02:00
return err
2021-08-31 01:02:41 +02:00
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
2021-09-01 16:38:28 +02:00
return fmt.Errorf("ciphertext too short")
2021-08-31 01:02:41 +02:00
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
2021-09-01 16:38:28 +02:00
ciphertext, err = gcm.Open(nil, nonce, ciphertext, nil)
2021-08-31 01:02:41 +02:00
if err != nil {
if err.Error() == "cipher: message authentication failed" {
err = fmt.Errorf("[ERR_INVALID_ENCRYPTION_KEY] Cannot decrypt access key, perhaps encryption key was changed")
}
2021-09-01 16:38:28 +02:00
return err
2021-08-31 01:02:41 +02:00
}
2021-09-01 16:38:28 +02:00
return key.unmarshalAppropriateField(ciphertext)
2021-08-31 01:02:41 +02:00
}