-
Notifications
You must be signed in to change notification settings - Fork 2
/
keyring.go
336 lines (279 loc) · 8.32 KB
/
keyring.go
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright (c) 2022 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package pmapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"io/ioutil"
"github.com/ProtonMail/gopenpgp/v2/crypto"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type PMKey struct {
ID string
Version int
Flags int
Fingerprint string
PrivateKey *crypto.Key
Primary int
Token string
Active Boolean
Signature string
}
type clearable []byte
func (c *clearable) UnmarshalJSON(b []byte) error {
b = bytes.Trim(b, "\"")
b = bytes.ReplaceAll(b, []byte("\\n"), []byte("\n"))
b = bytes.ReplaceAll(b, []byte("\\r"), []byte("\r"))
*c = b
return nil
}
func (c *clearable) clear() {
for i := range *c {
(*c)[i] = 0
}
}
func (key *PMKey) UnmarshalJSON(b []byte) (err error) {
type _PMKey PMKey
rawKey := struct {
_PMKey
PrivateKey clearable
}{}
defer rawKey.PrivateKey.clear()
if err = json.Unmarshal(b, &rawKey); err != nil {
return
}
*key = PMKey(rawKey._PMKey)
if key.PrivateKey, err = crypto.NewKeyFromArmoredReader(bytes.NewReader(rawKey.PrivateKey)); err != nil {
return errors.Wrap(err, "failed to create crypto key from armored private key")
}
return
}
func (key PMKey) getPassphraseFromToken(kr *crypto.KeyRing) (passphrase []byte, err error) {
if kr == nil {
return nil, errors.New("no user key was provided")
}
msg, err := crypto.NewPGPMessageFromArmored(key.Token)
if err != nil {
return
}
sig, err := crypto.NewPGPSignatureFromArmored(key.Signature)
if err != nil {
return
}
token, err := kr.Decrypt(msg, nil, 0)
if err != nil {
return
}
if err = kr.VerifyDetached(token, sig, 0); err != nil {
return
}
return token.GetBinary(), nil
}
func (key PMKey) unlock(passphrase []byte) (unlockedKey *crypto.Key, err error) {
if unlockedKey, err = key.PrivateKey.Unlock(passphrase); err != nil {
return
}
ok, err := unlockedKey.Check()
if err != nil {
return
}
if !ok {
err = errors.New("private and public keys do not match")
return
}
return
}
type PMKeys []PMKey
// UnlockAll goes through each key and unlocks it, returning a keyring containing all unlocked keys,
// or an error if no keys could be unlocked.
// The passphrase is used to unlock the key unless the key's token and signature are both non-nil,
// in which case the given userkey is used to deduce the passphrase.
func (keys *PMKeys) UnlockAll(passphrase []byte, userKey *crypto.KeyRing) (kr *crypto.KeyRing, err error) {
if kr, err = crypto.NewKeyRing(nil); err != nil {
return
}
for _, key := range *keys {
if !key.Active {
logrus.WithField("fingerprint", key.Fingerprint).Warn("Skipping inactive key")
continue
}
var secret []byte
if key.Token == "" || key.Signature == "" {
secret = passphrase
} else if secret, err = key.getPassphraseFromToken(userKey); err != nil {
return
}
k, unlockErr := key.unlock(secret)
if unlockErr != nil {
logrus.WithError(unlockErr).WithField("fingerprint", key.Fingerprint).Warn("Failed to unlock key")
continue
}
if addKeyErr := kr.AddKey(k); addKeyErr != nil {
logrus.WithError(addKeyErr).Warn("Failed to add key to keyring")
continue
}
}
if kr.CountEntities() == 0 {
err = errors.New("no keys could be unlocked")
return
}
return kr, err
}
// ErrNoKeyringAvailable represents an error caused by a keyring being nil or having no entities.
var ErrNoKeyringAvailable = errors.New("no keyring available")
func encrypt(encrypter *crypto.KeyRing, plain string, signer *crypto.KeyRing) (armored string, err error) {
if encrypter == nil {
return "", ErrNoKeyringAvailable
}
firstKey, err := encrypter.FirstKey()
if err != nil {
return "", err
}
plainMessage := crypto.NewPlainMessageFromString(plain)
// We use only primary key to encrypt the message. Our keyring contains all keys (primary, old and deacivated ones).
pgpMessage, err := firstKey.Encrypt(plainMessage, signer)
if err != nil {
return
}
return pgpMessage.GetArmored()
}
func (c *client) decrypt(armored string) (plain []byte, err error) {
return decrypt(c.userKeyRing, armored)
}
func decrypt(decrypter *crypto.KeyRing, armored string) (plainBody []byte, err error) {
if decrypter == nil {
return nil, ErrNoKeyringAvailable
}
pgpMessage, err := crypto.NewPGPMessageFromArmored(armored)
if err != nil {
return
}
plainMessage, err := decrypter.Decrypt(pgpMessage, nil, 0)
if err != nil {
return
}
return plainMessage.GetBinary(), nil
}
func (c *client) verify(plain, amroredSignature string) (err error) {
plainMessage := crypto.NewPlainMessageFromString(plain)
pgpSignature, err := crypto.NewPGPSignatureFromArmored(amroredSignature)
if err != nil {
return
}
verifyTime := int64(0) // By default it will use current timestamp.
return c.userKeyRing.VerifyDetached(plainMessage, pgpSignature, verifyTime)
}
func encryptAttachment(kr *crypto.KeyRing, data io.Reader, filename string) (encrypted io.Reader, err error) {
if kr == nil {
return nil, ErrNoKeyringAvailable
}
firstKey, err := kr.FirstKey()
if err != nil {
return nil, err
}
dataBytes, err := ioutil.ReadAll(data)
if err != nil {
return
}
plainMessage := crypto.NewPlainMessage(dataBytes)
// We use only primary key to encrypt the message. Our keyring contains all keys (primary, old and deacivated ones).
pgpSplitMessage, err := firstKey.EncryptAttachment(plainMessage, filename)
if err != nil {
return
}
packets := append(pgpSplitMessage.KeyPacket, pgpSplitMessage.DataPacket...) //nolint:gocritic
return bytes.NewReader(packets), nil
}
func decryptAttachment(kr *crypto.KeyRing, keyPackets []byte, data io.Reader) (decrypted io.Reader, err error) {
if kr == nil {
return nil, ErrNoKeyringAvailable
}
dataBytes, err := ioutil.ReadAll(data)
if err != nil {
return
}
pgpSplitMessage := crypto.NewPGPSplitMessage(keyPackets, dataBytes)
plainMessage, err := kr.DecryptAttachment(pgpSplitMessage)
if err != nil {
return
}
return plainMessage.NewReader(), nil
}
func signAttachment(encrypter *crypto.KeyRing, data io.Reader) (signature io.Reader, err error) {
if encrypter == nil {
return nil, ErrNoKeyringAvailable
}
dataBytes, err := ioutil.ReadAll(data)
if err != nil {
return
}
plainMessage := crypto.NewPlainMessage(dataBytes)
sig, err := encrypter.SignDetached(plainMessage)
if err != nil {
return
}
return bytes.NewReader(sig.GetBinary()), nil
}
func encryptAndEncodeSessionKeys(
pubkey *crypto.KeyRing,
bodyKey *crypto.SessionKey,
attkeys map[string]*crypto.SessionKey,
) (bodyPacket string, attachmentPackets map[string]string, err error) {
// Encrypt message body keys.
packetBytes, err := pubkey.EncryptSessionKey(bodyKey)
if err != nil {
return
}
bodyPacket = base64.StdEncoding.EncodeToString(packetBytes)
// Encrypt attachment keys.
attachmentPackets = make(map[string]string)
for id, attkey := range attkeys {
var packets []byte
if packets, err = pubkey.EncryptSessionKey(attkey); err != nil {
return
}
attachmentPackets[id] = base64.StdEncoding.EncodeToString(packets)
}
return
}
func encryptSymmDecryptKey(
kr *crypto.KeyRing,
textToEncrypt string,
) (decryptedKey *crypto.SessionKey, symEncryptedData []byte, err error) {
// We use only primary key to encrypt the message. Our keyring contains all keys (primary, old and deacivated ones).
firstKey, err := kr.FirstKey()
if err != nil {
return
}
pgpMessage, err := firstKey.Encrypt(crypto.NewPlainMessageFromString(textToEncrypt), kr)
if err != nil {
return
}
pgpSplitMessage, err := pgpMessage.SplitMessage()
if err != nil {
return
}
decryptedKey, err = kr.DecryptSessionKey(pgpSplitMessage.GetBinaryKeyPacket())
if err != nil {
return
}
symEncryptedData = pgpSplitMessage.GetBinaryDataPacket()
return
}