You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

537 lines
13 KiB

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