-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.go
More file actions
executable file
·190 lines (153 loc) · 4.71 KB
/
encryption.go
File metadata and controls
executable file
·190 lines (153 loc) · 4.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"strings"
)
func encryptAndPushToDB(hostname, column, password string) error {
if len(password) == 0 {
return fmt.Errorf("%s is empty", column)
}
if len(hostname) == 0 {
return fmt.Errorf("host is empty")
}
encryptedString, err := encrypt([]byte(password))
if err != nil {
err = fmt.Errorf("error encrypting %s: %v", column, err)
return err
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("failed to begin the db transaction for %s insertion:%w", column, err)
}
stmt, err := tx.Prepare(fmt.Sprintf("INSERT INTO sshprofiles(host,%s) VALUES(?,?) ON CONFLICT(host) DO UPDATE SET %s = excluded.%s;", column, column, column))
if err != nil {
return fmt.Errorf("failed to prepare the db for %s insertion:%w", column, err)
}
defer stmt.Close()
_, err = stmt.Exec(hostname, encryptedString)
if err != nil {
return fmt.Errorf("failed to insert the %s for the host %v: %w", column, hostname, err)
}
log.Printf("%s has been successfully added to the database!\n", column)
return tx.Commit()
}
func (s *AllConfigs) readAndDecryptFromDB(host, column string, needPass bool) (string, error) {
var password string
query := fmt.Sprintf("SELECT %s FROM sshprofiles WHERE host = ? AND %s IS NOT NULL", column, column)
row := db.QueryRow(query, host)
err := row.Scan(&password)
if err == sql.ErrNoRows {
return "", fmt.Errorf("no %s found for host: %s", column, host)
} else if err != nil {
return "", fmt.Errorf("read %s query failed: %w", column, err)
}
if needPass {
clearTextPassword, err := decrypt(password)
if err != nil {
return `''`, fmt.Errorf("error decrypting %s: %w", column, err)
}
return clearTextPassword, nil
} else {
return "ok", nil
}
}
func loadOrGenerateKey() ([]byte, error) {
var key []byte
// Attempt to read the key from the single-row table.
err := db.QueryRow("SELECT key FROM encryption_key WHERE id = 1").Scan(&key)
if err == nil {
return key, nil
}
// If no key was found, generate a new one.
if err == sql.ErrNoRows {
// if not keyfile exist, generate a new one
newKey := make([]byte, 32)
if _, err := rand.Read(newKey); err != nil {
return nil, fmt.Errorf("error generating new key: %w", err)
}
_, err = db.Exec("INSERT INTO encryption_key (id, key) VALUES (1, ?)", newKey)
if err != nil {
return nil, fmt.Errorf("error saving new key to database: %w", err)
}
fmt.Println("✅ New encryption key generated and saved to the database.")
return newKey, nil
}
// Handle other potential database errors.
return nil, fmt.Errorf("database error when retrieving key: %w", err)
}
func encrypt(plaintext []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
result := append(nonce, ciphertext...)
return base64.StdEncoding.EncodeToString(result), nil
}
func decrypt(ciphertext string) (string, error) {
decodedData, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := aesGCM.NonceSize()
if len(decodedData) < nonceSize {
return "", errors.New("ciphertext too short")
}
nonce, ciphertextBytes := decodedData[:nonceSize], decodedData[nonceSize:]
plaintext, err := aesGCM.Open(nil, nonce, ciphertextBytes, nil)
if err != nil {
if strings.Contains(err.Error(), "cipher: message authentication failed") {
pass, err := decrypt_legacy(ciphertext)
if err != nil {
return "", fmt.Errorf("failed to decrypt legacy format: %w", err)
}
return pass, nil
}
return "", err
}
return string(plaintext), nil
}
// decrypt_legacy is used to decrypt the passwords coming from the passwords.json file
// since the encryption mechanism was different and less secure.
func decrypt_legacy(ciphertext string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
if len(decodedCiphertext) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
iv := decodedCiphertext[:aes.BlockSize]
decodedCiphertext = decodedCiphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(decodedCiphertext, decodedCiphertext)
return string(decodedCiphertext), nil
}