packet.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package packet implements parsing and serialization of OpenPGP packets, as
  5. // specified in RFC 4880.
  6. package packet // import "golang.org/x/crypto/openpgp/packet"
  7. import (
  8. "bufio"
  9. "crypto/aes"
  10. "crypto/cipher"
  11. "crypto/des"
  12. "crypto/rsa"
  13. "io"
  14. "math/big"
  15. "golang.org/x/crypto/cast5"
  16. "golang.org/x/crypto/openpgp/errors"
  17. )
  18. // readFull is the same as io.ReadFull except that reading zero bytes returns
  19. // ErrUnexpectedEOF rather than EOF.
  20. func readFull(r io.Reader, buf []byte) (n int, err error) {
  21. n, err = io.ReadFull(r, buf)
  22. if err == io.EOF {
  23. err = io.ErrUnexpectedEOF
  24. }
  25. return
  26. }
  27. // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
  28. func readLength(r io.Reader) (length int64, isPartial bool, err error) {
  29. var buf [4]byte
  30. _, err = readFull(r, buf[:1])
  31. if err != nil {
  32. return
  33. }
  34. switch {
  35. case buf[0] < 192:
  36. length = int64(buf[0])
  37. case buf[0] < 224:
  38. length = int64(buf[0]-192) << 8
  39. _, err = readFull(r, buf[0:1])
  40. if err != nil {
  41. return
  42. }
  43. length += int64(buf[0]) + 192
  44. case buf[0] < 255:
  45. length = int64(1) << (buf[0] & 0x1f)
  46. isPartial = true
  47. default:
  48. _, err = readFull(r, buf[0:4])
  49. if err != nil {
  50. return
  51. }
  52. length = int64(buf[0])<<24 |
  53. int64(buf[1])<<16 |
  54. int64(buf[2])<<8 |
  55. int64(buf[3])
  56. }
  57. return
  58. }
  59. // partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths.
  60. // The continuation lengths are parsed and removed from the stream and EOF is
  61. // returned at the end of the packet. See RFC 4880, section 4.2.2.4.
  62. type partialLengthReader struct {
  63. r io.Reader
  64. remaining int64
  65. isPartial bool
  66. }
  67. func (r *partialLengthReader) Read(p []byte) (n int, err error) {
  68. for r.remaining == 0 {
  69. if !r.isPartial {
  70. return 0, io.EOF
  71. }
  72. r.remaining, r.isPartial, err = readLength(r.r)
  73. if err != nil {
  74. return 0, err
  75. }
  76. }
  77. toRead := int64(len(p))
  78. if toRead > r.remaining {
  79. toRead = r.remaining
  80. }
  81. n, err = r.r.Read(p[:int(toRead)])
  82. r.remaining -= int64(n)
  83. if n < int(toRead) && err == io.EOF {
  84. err = io.ErrUnexpectedEOF
  85. }
  86. return
  87. }
  88. // partialLengthWriter writes a stream of data using OpenPGP partial lengths.
  89. // See RFC 4880, section 4.2.2.4.
  90. type partialLengthWriter struct {
  91. w io.WriteCloser
  92. lengthByte [1]byte
  93. }
  94. func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
  95. for len(p) > 0 {
  96. for power := uint(14); power < 32; power-- {
  97. l := 1 << power
  98. if len(p) >= l {
  99. w.lengthByte[0] = 224 + uint8(power)
  100. _, err = w.w.Write(w.lengthByte[:])
  101. if err != nil {
  102. return
  103. }
  104. var m int
  105. m, err = w.w.Write(p[:l])
  106. n += m
  107. if err != nil {
  108. return
  109. }
  110. p = p[l:]
  111. break
  112. }
  113. }
  114. }
  115. return
  116. }
  117. func (w *partialLengthWriter) Close() error {
  118. w.lengthByte[0] = 0
  119. _, err := w.w.Write(w.lengthByte[:])
  120. if err != nil {
  121. return err
  122. }
  123. return w.w.Close()
  124. }
  125. // A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the
  126. // underlying Reader returns EOF before the limit has been reached.
  127. type spanReader struct {
  128. r io.Reader
  129. n int64
  130. }
  131. func (l *spanReader) Read(p []byte) (n int, err error) {
  132. if l.n <= 0 {
  133. return 0, io.EOF
  134. }
  135. if int64(len(p)) > l.n {
  136. p = p[0:l.n]
  137. }
  138. n, err = l.r.Read(p)
  139. l.n -= int64(n)
  140. if l.n > 0 && err == io.EOF {
  141. err = io.ErrUnexpectedEOF
  142. }
  143. return
  144. }
  145. // readHeader parses a packet header and returns an io.Reader which will return
  146. // the contents of the packet. See RFC 4880, section 4.2.
  147. func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
  148. var buf [4]byte
  149. _, err = io.ReadFull(r, buf[:1])
  150. if err != nil {
  151. return
  152. }
  153. if buf[0]&0x80 == 0 {
  154. err = errors.StructuralError("tag byte does not have MSB set")
  155. return
  156. }
  157. if buf[0]&0x40 == 0 {
  158. // Old format packet
  159. tag = packetType((buf[0] & 0x3f) >> 2)
  160. lengthType := buf[0] & 3
  161. if lengthType == 3 {
  162. length = -1
  163. contents = r
  164. return
  165. }
  166. lengthBytes := 1 << lengthType
  167. _, err = readFull(r, buf[0:lengthBytes])
  168. if err != nil {
  169. return
  170. }
  171. for i := 0; i < lengthBytes; i++ {
  172. length <<= 8
  173. length |= int64(buf[i])
  174. }
  175. contents = &spanReader{r, length}
  176. return
  177. }
  178. // New format packet
  179. tag = packetType(buf[0] & 0x3f)
  180. length, isPartial, err := readLength(r)
  181. if err != nil {
  182. return
  183. }
  184. if isPartial {
  185. contents = &partialLengthReader{
  186. remaining: length,
  187. isPartial: true,
  188. r: r,
  189. }
  190. length = -1
  191. } else {
  192. contents = &spanReader{r, length}
  193. }
  194. return
  195. }
  196. // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
  197. // 4.2.
  198. func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
  199. var buf [6]byte
  200. var n int
  201. buf[0] = 0x80 | 0x40 | byte(ptype)
  202. if length < 192 {
  203. buf[1] = byte(length)
  204. n = 2
  205. } else if length < 8384 {
  206. length -= 192
  207. buf[1] = 192 + byte(length>>8)
  208. buf[2] = byte(length)
  209. n = 3
  210. } else {
  211. buf[1] = 255
  212. buf[2] = byte(length >> 24)
  213. buf[3] = byte(length >> 16)
  214. buf[4] = byte(length >> 8)
  215. buf[5] = byte(length)
  216. n = 6
  217. }
  218. _, err = w.Write(buf[:n])
  219. return
  220. }
  221. // serializeStreamHeader writes an OpenPGP packet header to w where the
  222. // length of the packet is unknown. It returns a io.WriteCloser which can be
  223. // used to write the contents of the packet. See RFC 4880, section 4.2.
  224. func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
  225. var buf [1]byte
  226. buf[0] = 0x80 | 0x40 | byte(ptype)
  227. _, err = w.Write(buf[:])
  228. if err != nil {
  229. return
  230. }
  231. out = &partialLengthWriter{w: w}
  232. return
  233. }
  234. // Packet represents an OpenPGP packet. Users are expected to try casting
  235. // instances of this interface to specific packet types.
  236. type Packet interface {
  237. parse(io.Reader) error
  238. }
  239. // consumeAll reads from the given Reader until error, returning the number of
  240. // bytes read.
  241. func consumeAll(r io.Reader) (n int64, err error) {
  242. var m int
  243. var buf [1024]byte
  244. for {
  245. m, err = r.Read(buf[:])
  246. n += int64(m)
  247. if err == io.EOF {
  248. err = nil
  249. return
  250. }
  251. if err != nil {
  252. return
  253. }
  254. }
  255. }
  256. // packetType represents the numeric ids of the different OpenPGP packet types. See
  257. // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2
  258. type packetType uint8
  259. const (
  260. packetTypeEncryptedKey packetType = 1
  261. packetTypeSignature packetType = 2
  262. packetTypeSymmetricKeyEncrypted packetType = 3
  263. packetTypeOnePassSignature packetType = 4
  264. packetTypePrivateKey packetType = 5
  265. packetTypePublicKey packetType = 6
  266. packetTypePrivateSubkey packetType = 7
  267. packetTypeCompressed packetType = 8
  268. packetTypeSymmetricallyEncrypted packetType = 9
  269. packetTypeLiteralData packetType = 11
  270. packetTypeUserId packetType = 13
  271. packetTypePublicSubkey packetType = 14
  272. packetTypeUserAttribute packetType = 17
  273. packetTypeSymmetricallyEncryptedMDC packetType = 18
  274. )
  275. // peekVersion detects the version of a public key packet about to
  276. // be read. A bufio.Reader at the original position of the io.Reader
  277. // is returned.
  278. func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) {
  279. bufr = bufio.NewReader(r)
  280. var verBuf []byte
  281. if verBuf, err = bufr.Peek(1); err != nil {
  282. return
  283. }
  284. ver = verBuf[0]
  285. return
  286. }
  287. // Read reads a single OpenPGP packet from the given io.Reader. If there is an
  288. // error parsing a packet, the whole packet is consumed from the input.
  289. func Read(r io.Reader) (p Packet, err error) {
  290. tag, _, contents, err := readHeader(r)
  291. if err != nil {
  292. return
  293. }
  294. switch tag {
  295. case packetTypeEncryptedKey:
  296. p = new(EncryptedKey)
  297. case packetTypeSignature:
  298. var version byte
  299. // Detect signature version
  300. if contents, version, err = peekVersion(contents); err != nil {
  301. return
  302. }
  303. if version < 4 {
  304. p = new(SignatureV3)
  305. } else {
  306. p = new(Signature)
  307. }
  308. case packetTypeSymmetricKeyEncrypted:
  309. p = new(SymmetricKeyEncrypted)
  310. case packetTypeOnePassSignature:
  311. p = new(OnePassSignature)
  312. case packetTypePrivateKey, packetTypePrivateSubkey:
  313. pk := new(PrivateKey)
  314. if tag == packetTypePrivateSubkey {
  315. pk.IsSubkey = true
  316. }
  317. p = pk
  318. case packetTypePublicKey, packetTypePublicSubkey:
  319. var version byte
  320. if contents, version, err = peekVersion(contents); err != nil {
  321. return
  322. }
  323. isSubkey := tag == packetTypePublicSubkey
  324. if version < 4 {
  325. p = &PublicKeyV3{IsSubkey: isSubkey}
  326. } else {
  327. p = &PublicKey{IsSubkey: isSubkey}
  328. }
  329. case packetTypeCompressed:
  330. p = new(Compressed)
  331. case packetTypeSymmetricallyEncrypted:
  332. p = new(SymmetricallyEncrypted)
  333. case packetTypeLiteralData:
  334. p = new(LiteralData)
  335. case packetTypeUserId:
  336. p = new(UserId)
  337. case packetTypeUserAttribute:
  338. p = new(UserAttribute)
  339. case packetTypeSymmetricallyEncryptedMDC:
  340. se := new(SymmetricallyEncrypted)
  341. se.MDC = true
  342. p = se
  343. default:
  344. err = errors.UnknownPacketTypeError(tag)
  345. }
  346. if p != nil {
  347. err = p.parse(contents)
  348. }
  349. if err != nil {
  350. consumeAll(contents)
  351. }
  352. return
  353. }
  354. // SignatureType represents the different semantic meanings of an OpenPGP
  355. // signature. See RFC 4880, section 5.2.1.
  356. type SignatureType uint8
  357. const (
  358. SigTypeBinary SignatureType = 0
  359. SigTypeText = 1
  360. SigTypeGenericCert = 0x10
  361. SigTypePersonaCert = 0x11
  362. SigTypeCasualCert = 0x12
  363. SigTypePositiveCert = 0x13
  364. SigTypeSubkeyBinding = 0x18
  365. SigTypePrimaryKeyBinding = 0x19
  366. SigTypeDirectSignature = 0x1F
  367. SigTypeKeyRevocation = 0x20
  368. SigTypeSubkeyRevocation = 0x28
  369. )
  370. // PublicKeyAlgorithm represents the different public key system specified for
  371. // OpenPGP. See
  372. // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12
  373. type PublicKeyAlgorithm uint8
  374. const (
  375. PubKeyAlgoRSA PublicKeyAlgorithm = 1
  376. PubKeyAlgoElGamal PublicKeyAlgorithm = 16
  377. PubKeyAlgoDSA PublicKeyAlgorithm = 17
  378. // RFC 6637, Section 5.
  379. PubKeyAlgoECDH PublicKeyAlgorithm = 18
  380. PubKeyAlgoECDSA PublicKeyAlgorithm = 19
  381. // Deprecated in RFC 4880, Section 13.5. Use key flags instead.
  382. PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2
  383. PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3
  384. )
  385. // CanEncrypt returns true if it's possible to encrypt a message to a public
  386. // key of the given type.
  387. func (pka PublicKeyAlgorithm) CanEncrypt() bool {
  388. switch pka {
  389. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal:
  390. return true
  391. }
  392. return false
  393. }
  394. // CanSign returns true if it's possible for a public key of the given type to
  395. // sign a message.
  396. func (pka PublicKeyAlgorithm) CanSign() bool {
  397. switch pka {
  398. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
  399. return true
  400. }
  401. return false
  402. }
  403. // CipherFunction represents the different block ciphers specified for OpenPGP. See
  404. // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13
  405. type CipherFunction uint8
  406. const (
  407. Cipher3DES CipherFunction = 2
  408. CipherCAST5 CipherFunction = 3
  409. CipherAES128 CipherFunction = 7
  410. CipherAES192 CipherFunction = 8
  411. CipherAES256 CipherFunction = 9
  412. )
  413. // KeySize returns the key size, in bytes, of cipher.
  414. func (cipher CipherFunction) KeySize() int {
  415. switch cipher {
  416. case Cipher3DES:
  417. return 24
  418. case CipherCAST5:
  419. return cast5.KeySize
  420. case CipherAES128:
  421. return 16
  422. case CipherAES192:
  423. return 24
  424. case CipherAES256:
  425. return 32
  426. }
  427. return 0
  428. }
  429. // blockSize returns the block size, in bytes, of cipher.
  430. func (cipher CipherFunction) blockSize() int {
  431. switch cipher {
  432. case Cipher3DES:
  433. return des.BlockSize
  434. case CipherCAST5:
  435. return 8
  436. case CipherAES128, CipherAES192, CipherAES256:
  437. return 16
  438. }
  439. return 0
  440. }
  441. // new returns a fresh instance of the given cipher.
  442. func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
  443. switch cipher {
  444. case Cipher3DES:
  445. block, _ = des.NewTripleDESCipher(key)
  446. case CipherCAST5:
  447. block, _ = cast5.NewCipher(key)
  448. case CipherAES128, CipherAES192, CipherAES256:
  449. block, _ = aes.NewCipher(key)
  450. }
  451. return
  452. }
  453. // readMPI reads a big integer from r. The bit length returned is the bit
  454. // length that was specified in r. This is preserved so that the integer can be
  455. // reserialized exactly.
  456. func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
  457. var buf [2]byte
  458. _, err = readFull(r, buf[0:])
  459. if err != nil {
  460. return
  461. }
  462. bitLength = uint16(buf[0])<<8 | uint16(buf[1])
  463. numBytes := (int(bitLength) + 7) / 8
  464. mpi = make([]byte, numBytes)
  465. _, err = readFull(r, mpi)
  466. // According to RFC 4880 3.2. we should check that the MPI has no leading
  467. // zeroes (at least when not an encrypted MPI?), but this implementation
  468. // does generate leading zeroes, so we keep accepting them.
  469. return
  470. }
  471. // writeMPI serializes a big integer to w.
  472. func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
  473. // Note that we can produce leading zeroes, in violation of RFC 4880 3.2.
  474. // Implementations seem to be tolerant of them, and stripping them would
  475. // make it complex to guarantee matching re-serialization.
  476. _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
  477. if err == nil {
  478. _, err = w.Write(mpiBytes)
  479. }
  480. return
  481. }
  482. // writeBig serializes a *big.Int to w.
  483. func writeBig(w io.Writer, i *big.Int) error {
  484. return writeMPI(w, uint16(i.BitLen()), i.Bytes())
  485. }
  486. // padToKeySize left-pads a MPI with zeroes to match the length of the
  487. // specified RSA public.
  488. func padToKeySize(pub *rsa.PublicKey, b []byte) []byte {
  489. k := (pub.N.BitLen() + 7) / 8
  490. if len(b) >= k {
  491. return b
  492. }
  493. bb := make([]byte, k)
  494. copy(bb[len(bb)-len(b):], b)
  495. return bb
  496. }
  497. // CompressionAlgo Represents the different compression algorithms
  498. // supported by OpenPGP (except for BZIP2, which is not currently
  499. // supported). See Section 9.3 of RFC 4880.
  500. type CompressionAlgo uint8
  501. const (
  502. CompressionNone CompressionAlgo = 0
  503. CompressionZIP CompressionAlgo = 1
  504. CompressionZLIB CompressionAlgo = 2
  505. )