-
Notifications
You must be signed in to change notification settings - Fork 15
/
reader.go
268 lines (225 loc) · 7.85 KB
/
reader.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
package pgpmail
import (
"bufio"
"bytes"
"crypto"
"fmt"
"hash"
"io"
"mime"
"strings"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/armor"
pgperrors "github.com/ProtonMail/go-crypto/openpgp/errors"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/emersion/go-message/textproto"
)
type Reader struct {
Header textproto.Header
MessageDetails *openpgp.MessageDetails
}
func NewReader(h textproto.Header, body io.Reader, keyring openpgp.KeyRing, prompt openpgp.PromptFunction, config *packet.Config) (*Reader, error) {
t, params, err := mime.ParseMediaType(h.Get("Content-Type"))
if err != nil {
return nil, err
}
if strings.EqualFold(t, "multipart/encrypted") && strings.EqualFold(params["protocol"], "application/pgp-encrypted") {
mr := textproto.NewMultipartReader(body, params["boundary"])
return newEncryptedReader(h, mr, keyring, prompt, config)
}
if strings.EqualFold(t, "multipart/signed") && strings.EqualFold(params["protocol"], "application/pgp-signature") {
micalg := params["micalg"]
mr := textproto.NewMultipartReader(body, params["boundary"])
return newSignedReader(h, mr, micalg, keyring, prompt, config)
}
var headerBuf bytes.Buffer
textproto.WriteHeader(&headerBuf, h)
return &Reader{
Header: h,
MessageDetails: &openpgp.MessageDetails{
UnverifiedBody: io.MultiReader(&headerBuf, body),
},
}, nil
}
func Read(r io.Reader, keyring openpgp.KeyRing, prompt openpgp.PromptFunction, config *packet.Config) (*Reader, error) {
br := bufio.NewReader(r)
h, err := textproto.ReadHeader(br)
if err != nil {
return nil, err
}
return NewReader(h, br, keyring, prompt, config)
}
func newEncryptedReader(h textproto.Header, mr *textproto.MultipartReader, keyring openpgp.KeyRing, prompt openpgp.PromptFunction, config *packet.Config) (*Reader, error) {
p, err := mr.NextPart()
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read first part in multipart/encrypted message: %v", err)
}
t, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to parse Content-Type of first part in multipart/encrypted message: %v", err)
}
if !strings.EqualFold(t, "application/pgp-encrypted") {
return nil, fmt.Errorf("pgpmail: first part in multipart/encrypted message has type %q, not application/pgp-encrypted", t)
}
metadata, err := textproto.ReadHeader(bufio.NewReader(p))
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to parse application/pgp-encrypted part: %v", err)
}
if s := metadata.Get("Version"); s != "1" {
return nil, fmt.Errorf("pgpmail: unsupported PGP/MIME version: %q", s)
}
p, err = mr.NextPart()
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read second part in multipart/encrypted message: %v", err)
}
t, _, err = mime.ParseMediaType(p.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to parse Content-Type of second part in multipart/encrypted message: %v", err)
}
if !strings.EqualFold(t, "application/octet-stream") {
return nil, fmt.Errorf("pgpmail: second part in multipart/encrypted message has type %q, not application/octet-stream", t)
}
block, err := armor.Decode(p)
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to parse encrypted armored data: %v", err)
}
md, err := openpgp.ReadMessage(block.Body, keyring, prompt, config)
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read PGP message: %v", err)
}
cleartext := bufio.NewReader(md.UnverifiedBody)
cleartextHeader, err := textproto.ReadHeader(cleartext)
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read encrypted header: %v", err)
}
t, params, err := mime.ParseMediaType(cleartextHeader.Get("Content-Type"))
if err != nil {
return nil, err
}
if md.IsEncrypted && !md.IsSigned && strings.EqualFold(t, "multipart/signed") && strings.EqualFold(params["protocol"], "application/pgp-signature") {
// RFC 1847 encapsulation, see RFC 3156 section 6.1
micalg := params["micalg"]
mr := textproto.NewMultipartReader(cleartext, params["boundary"])
sr, err := newSignedReader(cleartextHeader, mr, micalg, keyring, prompt, config)
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read encapsulated multipart/signed message: %v", err)
}
sr.MessageDetails.IsEncrypted = md.IsEncrypted
sr.MessageDetails.EncryptedToKeyIds = md.EncryptedToKeyIds
sr.MessageDetails.IsSymmetricallyEncrypted = md.IsSymmetricallyEncrypted
sr.MessageDetails.DecryptedWith = md.DecryptedWith
return sr, nil
}
var headerBuf bytes.Buffer
textproto.WriteHeader(&headerBuf, cleartextHeader)
md.UnverifiedBody = io.MultiReader(&headerBuf, cleartext)
return &Reader{
Header: h,
MessageDetails: md,
}, nil
}
type signedReader struct {
keyring openpgp.KeyRing
multipart *textproto.MultipartReader
signed io.Reader
hashFunc crypto.Hash
hash hash.Hash
md *openpgp.MessageDetails
}
func (r *signedReader) Read(b []byte) (int, error) {
n, err := r.signed.Read(b)
r.hash.Write(b[:n])
if err == io.EOF {
r.md.SignatureError = r.check()
}
return n, err
}
func (r *signedReader) check() error {
part, err := r.multipart.NextPart()
if err != nil {
return fmt.Errorf("pgpmail: failed to read signature part of multipart/signed message: %v", err)
}
t, _, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
if err != nil {
return fmt.Errorf("pgpmail: failed to parse Content-Type of signature part in multipart/encrypted message: %v", err)
}
if !strings.EqualFold(t, "application/pgp-signature") {
return fmt.Errorf("pgpmail: signature part in multipart/encrypted message has type %q, not application/pgp-signature", t)
}
block, err := armor.Decode(part)
if err != nil {
return fmt.Errorf("pgpmail: failed to read armored signature block: %v", err)
}
var p packet.Packet
var keys []openpgp.Key
var sigErr error
pr := packet.NewReader(block.Body)
for {
p, err = pr.Next()
if err == io.EOF {
break
} else if err != nil {
return fmt.Errorf("pgpmail: failed to read signature: %v", err)
}
sig, ok := p.(*packet.Signature)
if !ok {
return fmt.Errorf("pgpmail: non signature packet found")
}
if sig.IssuerKeyId == nil {
return fmt.Errorf("pgpmail: signature doesn't have an issuer")
}
issuerKeyId := *sig.IssuerKeyId
hashFunc := sig.Hash
r.md.SignedByKeyId = issuerKeyId
if hashFunc != r.hashFunc {
return fmt.Errorf("pgpmail: micalg mismatch: multipart header indicates %v but signature packet indicates %v", r.hashFunc, hashFunc)
}
keys = r.keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign)
if len(keys) == 0 {
continue
}
for i, key := range keys {
sigErr := key.PublicKey.VerifySignature(r.hash, sig)
if sigErr == nil {
r.md.SignedBy = &keys[i]
return nil
}
}
}
if sigErr != nil {
return sigErr
}
return pgperrors.ErrUnknownIssuer
}
func newSignedReader(h textproto.Header, mr *textproto.MultipartReader, micalg string, keyring openpgp.KeyRing, prompt openpgp.PromptFunction, config *packet.Config) (*Reader, error) {
micalg = strings.ToLower(micalg)
hashFunc, ok := hashAlgs[micalg]
if !ok {
return nil, fmt.Errorf("pgpmail: unsupported micalg %q", micalg)
}
if !hashFunc.Available() {
return nil, fmt.Errorf("pgpmail: micalg %q unavailable", micalg)
}
hash := hashFunc.New()
p, err := mr.NextPart()
if err != nil {
return nil, fmt.Errorf("pgpmail: failed to read signed part in multipart/signed message: %v", err)
}
var headerBuf bytes.Buffer
textproto.WriteHeader(&headerBuf, p.Header)
// TODO: convert line endings to CRLF
md := &openpgp.MessageDetails{IsSigned: true}
sr := &signedReader{
keyring: keyring,
multipart: mr,
signed: io.MultiReader(&headerBuf, p),
hashFunc: hashFunc,
hash: hash,
md: md,
}
md.UnverifiedBody = sr
return &Reader{
Header: h,
MessageDetails: md,
}, nil
}