1
2
3
4
5
6
7
8
9
10
11
12
13 package packet
14
15 import (
16 "bufio"
17 "crypto/aes"
18 "crypto/cipher"
19 "crypto/des"
20 "crypto/rsa"
21 "io"
22 "math/big"
23 "math/bits"
24
25 "golang.org/x/crypto/cast5"
26 "golang.org/x/crypto/openpgp/errors"
27 )
28
29
30
31 func readFull(r io.Reader, buf []byte) (n int, err error) {
32 n, err = io.ReadFull(r, buf)
33 if err == io.EOF {
34 err = io.ErrUnexpectedEOF
35 }
36 return
37 }
38
39
40 func readLength(r io.Reader) (length int64, isPartial bool, err error) {
41 var buf [4]byte
42 _, err = readFull(r, buf[:1])
43 if err != nil {
44 return
45 }
46 switch {
47 case buf[0] < 192:
48 length = int64(buf[0])
49 case buf[0] < 224:
50 length = int64(buf[0]-192) << 8
51 _, err = readFull(r, buf[0:1])
52 if err != nil {
53 return
54 }
55 length += int64(buf[0]) + 192
56 case buf[0] < 255:
57 length = int64(1) << (buf[0] & 0x1f)
58 isPartial = true
59 default:
60 _, err = readFull(r, buf[0:4])
61 if err != nil {
62 return
63 }
64 length = int64(buf[0])<<24 |
65 int64(buf[1])<<16 |
66 int64(buf[2])<<8 |
67 int64(buf[3])
68 }
69 return
70 }
71
72
73
74
75 type partialLengthReader struct {
76 r io.Reader
77 remaining int64
78 isPartial bool
79 }
80
81 func (r *partialLengthReader) Read(p []byte) (n int, err error) {
82 for r.remaining == 0 {
83 if !r.isPartial {
84 return 0, io.EOF
85 }
86 r.remaining, r.isPartial, err = readLength(r.r)
87 if err != nil {
88 return 0, err
89 }
90 }
91
92 toRead := int64(len(p))
93 if toRead > r.remaining {
94 toRead = r.remaining
95 }
96
97 n, err = r.r.Read(p[:int(toRead)])
98 r.remaining -= int64(n)
99 if n < int(toRead) && err == io.EOF {
100 err = io.ErrUnexpectedEOF
101 }
102 return
103 }
104
105
106
107 type partialLengthWriter struct {
108 w io.WriteCloser
109 lengthByte [1]byte
110 sentFirst bool
111 buf []byte
112 }
113
114
115 const minFirstPartialWrite = 512
116
117 func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
118 off := 0
119 if !w.sentFirst {
120 if len(w.buf) > 0 || len(p) < minFirstPartialWrite {
121 off = len(w.buf)
122 w.buf = append(w.buf, p...)
123 if len(w.buf) < minFirstPartialWrite {
124 return len(p), nil
125 }
126 p = w.buf
127 w.buf = nil
128 }
129 w.sentFirst = true
130 }
131
132 power := uint8(30)
133 for len(p) > 0 {
134 l := 1 << power
135 if len(p) < l {
136 power = uint8(bits.Len32(uint32(len(p)))) - 1
137 l = 1 << power
138 }
139 w.lengthByte[0] = 224 + power
140 _, err = w.w.Write(w.lengthByte[:])
141 if err == nil {
142 var m int
143 m, err = w.w.Write(p[:l])
144 n += m
145 }
146 if err != nil {
147 if n < off {
148 return 0, err
149 }
150 return n - off, err
151 }
152 p = p[l:]
153 }
154 return n - off, nil
155 }
156
157 func (w *partialLengthWriter) Close() error {
158 if len(w.buf) > 0 {
159
160
161 p := w.buf
162 w.sentFirst = true
163 w.buf = nil
164 if _, err := w.Write(p); err != nil {
165 return err
166 }
167 }
168
169 w.lengthByte[0] = 0
170 _, err := w.w.Write(w.lengthByte[:])
171 if err != nil {
172 return err
173 }
174 return w.w.Close()
175 }
176
177
178
179 type spanReader struct {
180 r io.Reader
181 n int64
182 }
183
184 func (l *spanReader) Read(p []byte) (n int, err error) {
185 if l.n <= 0 {
186 return 0, io.EOF
187 }
188 if int64(len(p)) > l.n {
189 p = p[0:l.n]
190 }
191 n, err = l.r.Read(p)
192 l.n -= int64(n)
193 if l.n > 0 && err == io.EOF {
194 err = io.ErrUnexpectedEOF
195 }
196 return
197 }
198
199
200
201 func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
202 var buf [4]byte
203 _, err = io.ReadFull(r, buf[:1])
204 if err != nil {
205 return
206 }
207 if buf[0]&0x80 == 0 {
208 err = errors.StructuralError("tag byte does not have MSB set")
209 return
210 }
211 if buf[0]&0x40 == 0 {
212
213 tag = packetType((buf[0] & 0x3f) >> 2)
214 lengthType := buf[0] & 3
215 if lengthType == 3 {
216 length = -1
217 contents = r
218 return
219 }
220 lengthBytes := 1 << lengthType
221 _, err = readFull(r, buf[0:lengthBytes])
222 if err != nil {
223 return
224 }
225 for i := 0; i < lengthBytes; i++ {
226 length <<= 8
227 length |= int64(buf[i])
228 }
229 contents = &spanReader{r, length}
230 return
231 }
232
233
234 tag = packetType(buf[0] & 0x3f)
235 length, isPartial, err := readLength(r)
236 if err != nil {
237 return
238 }
239 if isPartial {
240 contents = &partialLengthReader{
241 remaining: length,
242 isPartial: true,
243 r: r,
244 }
245 length = -1
246 } else {
247 contents = &spanReader{r, length}
248 }
249 return
250 }
251
252
253
254 func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
255 var buf [6]byte
256 var n int
257
258 buf[0] = 0x80 | 0x40 | byte(ptype)
259 if length < 192 {
260 buf[1] = byte(length)
261 n = 2
262 } else if length < 8384 {
263 length -= 192
264 buf[1] = 192 + byte(length>>8)
265 buf[2] = byte(length)
266 n = 3
267 } else {
268 buf[1] = 255
269 buf[2] = byte(length >> 24)
270 buf[3] = byte(length >> 16)
271 buf[4] = byte(length >> 8)
272 buf[5] = byte(length)
273 n = 6
274 }
275
276 _, err = w.Write(buf[:n])
277 return
278 }
279
280
281
282
283 func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
284 var buf [1]byte
285 buf[0] = 0x80 | 0x40 | byte(ptype)
286 _, err = w.Write(buf[:])
287 if err != nil {
288 return
289 }
290 out = &partialLengthWriter{w: w}
291 return
292 }
293
294
295
296 type Packet interface {
297 parse(io.Reader) error
298 }
299
300
301
302 func consumeAll(r io.Reader) (n int64, err error) {
303 var m int
304 var buf [1024]byte
305
306 for {
307 m, err = r.Read(buf[:])
308 n += int64(m)
309 if err == io.EOF {
310 err = nil
311 return
312 }
313 if err != nil {
314 return
315 }
316 }
317 }
318
319
320
321 type packetType uint8
322
323 const (
324 packetTypeEncryptedKey packetType = 1
325 packetTypeSignature packetType = 2
326 packetTypeSymmetricKeyEncrypted packetType = 3
327 packetTypeOnePassSignature packetType = 4
328 packetTypePrivateKey packetType = 5
329 packetTypePublicKey packetType = 6
330 packetTypePrivateSubkey packetType = 7
331 packetTypeCompressed packetType = 8
332 packetTypeSymmetricallyEncrypted packetType = 9
333 packetTypeLiteralData packetType = 11
334 packetTypeUserId packetType = 13
335 packetTypePublicSubkey packetType = 14
336 packetTypeUserAttribute packetType = 17
337 packetTypeSymmetricallyEncryptedMDC packetType = 18
338 )
339
340
341
342
343 func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) {
344 bufr = bufio.NewReader(r)
345 var verBuf []byte
346 if verBuf, err = bufr.Peek(1); err != nil {
347 return
348 }
349 ver = verBuf[0]
350 return
351 }
352
353
354
355 func Read(r io.Reader) (p Packet, err error) {
356 tag, _, contents, err := readHeader(r)
357 if err != nil {
358 return
359 }
360
361 switch tag {
362 case packetTypeEncryptedKey:
363 p = new(EncryptedKey)
364 case packetTypeSignature:
365 var version byte
366
367 if contents, version, err = peekVersion(contents); err != nil {
368 return
369 }
370 if version < 4 {
371 p = new(SignatureV3)
372 } else {
373 p = new(Signature)
374 }
375 case packetTypeSymmetricKeyEncrypted:
376 p = new(SymmetricKeyEncrypted)
377 case packetTypeOnePassSignature:
378 p = new(OnePassSignature)
379 case packetTypePrivateKey, packetTypePrivateSubkey:
380 pk := new(PrivateKey)
381 if tag == packetTypePrivateSubkey {
382 pk.IsSubkey = true
383 }
384 p = pk
385 case packetTypePublicKey, packetTypePublicSubkey:
386 var version byte
387 if contents, version, err = peekVersion(contents); err != nil {
388 return
389 }
390 isSubkey := tag == packetTypePublicSubkey
391 if version < 4 {
392 p = &PublicKeyV3{IsSubkey: isSubkey}
393 } else {
394 p = &PublicKey{IsSubkey: isSubkey}
395 }
396 case packetTypeCompressed:
397 p = new(Compressed)
398 case packetTypeSymmetricallyEncrypted:
399 p = new(SymmetricallyEncrypted)
400 case packetTypeLiteralData:
401 p = new(LiteralData)
402 case packetTypeUserId:
403 p = new(UserId)
404 case packetTypeUserAttribute:
405 p = new(UserAttribute)
406 case packetTypeSymmetricallyEncryptedMDC:
407 se := new(SymmetricallyEncrypted)
408 se.MDC = true
409 p = se
410 default:
411 err = errors.UnknownPacketTypeError(tag)
412 }
413 if p != nil {
414 err = p.parse(contents)
415 }
416 if err != nil {
417 consumeAll(contents)
418 }
419 return
420 }
421
422
423
424 type SignatureType uint8
425
426 const (
427 SigTypeBinary SignatureType = 0
428 SigTypeText = 1
429 SigTypeGenericCert = 0x10
430 SigTypePersonaCert = 0x11
431 SigTypeCasualCert = 0x12
432 SigTypePositiveCert = 0x13
433 SigTypeSubkeyBinding = 0x18
434 SigTypePrimaryKeyBinding = 0x19
435 SigTypeDirectSignature = 0x1F
436 SigTypeKeyRevocation = 0x20
437 SigTypeSubkeyRevocation = 0x28
438 )
439
440
441
442
443 type PublicKeyAlgorithm uint8
444
445 const (
446 PubKeyAlgoRSA PublicKeyAlgorithm = 1
447 PubKeyAlgoElGamal PublicKeyAlgorithm = 16
448 PubKeyAlgoDSA PublicKeyAlgorithm = 17
449
450 PubKeyAlgoECDH PublicKeyAlgorithm = 18
451 PubKeyAlgoECDSA PublicKeyAlgorithm = 19
452
453
454 PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2
455 PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3
456 )
457
458
459
460 func (pka PublicKeyAlgorithm) CanEncrypt() bool {
461 switch pka {
462 case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal:
463 return true
464 }
465 return false
466 }
467
468
469
470 func (pka PublicKeyAlgorithm) CanSign() bool {
471 switch pka {
472 case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
473 return true
474 }
475 return false
476 }
477
478
479
480 type CipherFunction uint8
481
482 const (
483 Cipher3DES CipherFunction = 2
484 CipherCAST5 CipherFunction = 3
485 CipherAES128 CipherFunction = 7
486 CipherAES192 CipherFunction = 8
487 CipherAES256 CipherFunction = 9
488 )
489
490
491 func (cipher CipherFunction) KeySize() int {
492 switch cipher {
493 case Cipher3DES:
494 return 24
495 case CipherCAST5:
496 return cast5.KeySize
497 case CipherAES128:
498 return 16
499 case CipherAES192:
500 return 24
501 case CipherAES256:
502 return 32
503 }
504 return 0
505 }
506
507
508 func (cipher CipherFunction) blockSize() int {
509 switch cipher {
510 case Cipher3DES:
511 return des.BlockSize
512 case CipherCAST5:
513 return 8
514 case CipherAES128, CipherAES192, CipherAES256:
515 return 16
516 }
517 return 0
518 }
519
520
521 func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
522 switch cipher {
523 case Cipher3DES:
524 block, _ = des.NewTripleDESCipher(key)
525 case CipherCAST5:
526 block, _ = cast5.NewCipher(key)
527 case CipherAES128, CipherAES192, CipherAES256:
528 block, _ = aes.NewCipher(key)
529 }
530 return
531 }
532
533
534
535
536 func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
537 var buf [2]byte
538 _, err = readFull(r, buf[0:])
539 if err != nil {
540 return
541 }
542 bitLength = uint16(buf[0])<<8 | uint16(buf[1])
543 numBytes := (int(bitLength) + 7) / 8
544 mpi = make([]byte, numBytes)
545 _, err = readFull(r, mpi)
546
547
548
549 return
550 }
551
552
553 func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
554
555
556
557 _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
558 if err == nil {
559 _, err = w.Write(mpiBytes)
560 }
561 return
562 }
563
564
565 func writeBig(w io.Writer, i *big.Int) error {
566 return writeMPI(w, uint16(i.BitLen()), i.Bytes())
567 }
568
569
570
571 func padToKeySize(pub *rsa.PublicKey, b []byte) []byte {
572 k := (pub.N.BitLen() + 7) / 8
573 if len(b) >= k {
574 return b
575 }
576 bb := make([]byte, k)
577 copy(bb[len(bb)-len(b):], b)
578 return bb
579 }
580
581
582
583
584 type CompressionAlgo uint8
585
586 const (
587 CompressionNone CompressionAlgo = 0
588 CompressionZIP CompressionAlgo = 1
589 CompressionZLIB CompressionAlgo = 2
590 )
591
View as plain text