-
Notifications
You must be signed in to change notification settings - Fork 5
/
encoding.go
290 lines (255 loc) · 7.04 KB
/
encoding.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
package lastpass
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
"github.com/ansd/lastpass-go/ecb"
)
// LastPass blob chunk is made up of 4-byte ID,
// big endian 4-byte size and payload of that size.
//
// Example:
// 0000: "IDID"
// 0004: 4
// 0008: 0xDE 0xAD 0xBE 0xEF
// 000C: --- Next chunk ---
func extractChunks(r io.Reader) ([]*chunk, error) {
chunks := make([]*chunk, 0)
for {
chunkID, err := readID(r)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
payload, err := readItem(r)
if err != nil {
return nil, err
}
c := &chunk{chunkID, payload}
chunks = append(chunks, c)
}
return chunks, nil
}
func readID(r io.Reader) (uint32, error) {
var b [4]byte
_, err := r.Read(b[:])
if err != nil {
return 0, err
}
return chunkIDFromBytes(b), nil
}
func readItem(r io.Reader) ([]byte, error) {
size, err := readSize(r)
if err != nil {
return nil, err
}
b := make([]byte, size)
n, err := r.Read(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
func readSize(r io.Reader) (uint32, error) {
var b [4]byte
_, err := r.Read(b[:])
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(b[:]), nil
}
func skipItem(r io.Reader) error {
readSize, err := readSize(r)
if err != nil {
return err
}
b := make([]byte, readSize)
_, err = r.Read(b)
return err
}
func chunkIDFromBytes(b [4]byte) uint32 {
return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
}
func chunkIDFromString(s string) uint32 {
b := []byte(s)
return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
}
func encryptAESCBC(plaintext string, encryptionKey []byte) (string, error) {
if len(plaintext) == 0 {
return "", nil
}
padded := pkcs7Pad([]byte(plaintext), aes.BlockSize)
ciphertext := make([]byte, aes.BlockSize+len(padded))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return "", err
}
enc := cipher.NewCBCEncrypter(block, iv)
enc.CryptBlocks(ciphertext[aes.BlockSize:], padded)
ivBase64 := encodeBase64(iv)
ciphertextBase64 := encodeBase64(ciphertext[aes.BlockSize:])
// use the same format as the CLI does it in (v1.3.3)
// https://github.com/lastpass/lastpass-cli/blob/a84aa9629957033082c5930968dda7fbed751dfa/cipher.c#L296
return fmt.Sprintf("!%s|%s", ivBase64, ciphertextBase64), nil
}
func decryptItem(data, encryptionKey []byte) (string, error) {
size := len(data)
if size == 0 {
return "", nil
}
size16 := size % 16
size64 := size % 64
switch {
case aes256CBCPlain(data, size16):
data = data[1:]
iv, in := data[:aes.BlockSize], data[aes.BlockSize:]
return decryptAES256CBC(iv, in, encryptionKey)
case aes256CBCBase64(data, size64):
ivBase64 := data[1:25]
iv, err := decodeBase64(ivBase64)
if err != nil {
return "", err
}
inBase64 := data[26:]
in, err := decodeBase64(inBase64)
if err != nil {
return "", err
}
return decryptAES256CBC(iv, in, encryptionKey)
case aes256ECBPlain(size16):
return decryptAES256ECB(data, encryptionKey)
case aes256ECBBase64(size64):
data, err := decodeBase64(data)
if err != nil {
return "", err
}
return decryptAES256ECB(data, encryptionKey)
}
return "", errors.New("input doesn't seem to be AES-256 encrypted")
}
func aes256CBCPlain(data []byte, size16 int) bool {
return data[0] == '!' && size16 == 1
}
func aes256CBCBase64(data []byte, size64 int) bool {
return data[0] == '!' && data[25] == '|' && (size64 == 6 || size64 == 26 || size64 == 50)
}
func aes256ECBPlain(size16 int) bool {
return size16 == 0
}
func aes256ECBBase64(size64 int) bool {
return size64 == 0 || size64 == 24 || size64 == 44
}
// decrypt user's private key with user's encryption key
//
// Background:
// The first time, the user logs into LastPass using any LastPass client
// a key pair gets created. The public key is uploaded unencrypted to LastPass so that
// other users can encrypt data for the user (e.g. sharing keys).
// The private key gets encrypted locally with the user's encryption key and also
// uploaded to LastPass.
func decryptPrivateKey(privateKeyEncrypted string, encryptionKey []byte) (*rsa.PrivateKey, error) {
if privateKeyEncrypted == "" {
// Key pair is not yet created. This happens for example when the account got created via
// https://lastpass.com/create-account.php but the user has never logged in.
// https://support.lastpass.com/help/why-am-i-seeing-an-error-no-private-key-cannot-decrypt-pending-shares-message-lp010147
return nil, nil
}
privateKeyAESEncrypted, err := hex.DecodeString(privateKeyEncrypted)
if err != nil {
return nil, err
}
iv := encryptionKey[:aes.BlockSize]
keyAnnotated, err := decryptAES256CBC(iv, privateKeyAESEncrypted, encryptionKey)
if err != nil {
return nil, err
}
keyTrimmed := strings.TrimPrefix(keyAnnotated, "LastPassPrivateKey<")
keyTrimmed = strings.TrimSuffix(keyTrimmed, ">LastPassPrivateKey")
keyPlain, err := hex.DecodeString(keyTrimmed)
if err != nil {
return nil, err
}
keyParsed, err := x509.ParsePKCS8PrivateKey(keyPlain)
if err != nil {
return nil, err
}
rsaPrivateKey, ok := keyParsed.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("did not find RSA private key type in PKCS#8 wrapping")
}
return rsaPrivateKey, nil
}
func decryptAES256CBC(iv, in, encryptionKey []byte) (string, error) {
lenIn := len(in)
if lenIn < aes.BlockSize {
return "", fmt.Errorf("input is only %d bytes; expected at least %d bytes", lenIn, aes.BlockSize)
}
if lenIn%aes.BlockSize != 0 {
return "", fmt.Errorf("input size (%d bytes) is not a multilpe of %d bytes", lenIn, aes.BlockSize)
}
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return "", err
}
dec := cipher.NewCBCDecrypter(block, iv)
out := make([]byte, lenIn)
dec.CryptBlocks(out, in)
return string(pkcs7Unpad(out)), nil
}
func decryptAES256ECB(in, encryptionKey []byte) (string, error) {
block, err := aes.NewCipher(encryptionKey)
if err != nil {
return "", err
}
dec := ecb.NewECBDecrypter(block)
out := make([]byte, len(in))
dec.CryptBlocks(out, in)
return string(pkcs7Unpad(out)), nil
}
func encodeBase64(b []byte) []byte {
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(b)))
base64.StdEncoding.Encode(encoded, b)
return encoded
}
func decodeBase64(b []byte) ([]byte, error) {
d := make([]byte, len(b))
n, err := base64.StdEncoding.Decode(d, b)
if err != nil {
return nil, err
}
return d[:n], nil
}
func decodeHex(src []byte) ([]byte, error) {
dst := make([]byte, hex.DecodedLen(len(src)))
_, err := hex.Decode(dst, src)
if err != nil {
return nil, err
}
return dst, nil
}
func pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padtext...)
}
func pkcs7Unpad(data []byte) []byte {
size := len(data)
unpadding := int(data[size-1])
return data[:(size - unpadding)]
}