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.
 
 
 

550 lines
14 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. "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. PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2
  377. PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3
  378. PubKeyAlgoElGamal PublicKeyAlgorithm = 16
  379. PubKeyAlgoDSA PublicKeyAlgorithm = 17
  380. // RFC 6637, Section 5.
  381. PubKeyAlgoECDH PublicKeyAlgorithm = 18
  382. PubKeyAlgoECDSA PublicKeyAlgorithm = 19
  383. )
  384. // CanEncrypt returns true if it's possible to encrypt a message to a public
  385. // key of the given type.
  386. func (pka PublicKeyAlgorithm) CanEncrypt() bool {
  387. switch pka {
  388. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal:
  389. return true
  390. }
  391. return false
  392. }
  393. // CanSign returns true if it's possible for a public key of the given type to
  394. // sign a message.
  395. func (pka PublicKeyAlgorithm) CanSign() bool {
  396. switch pka {
  397. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
  398. return true
  399. }
  400. return false
  401. }
  402. // CipherFunction represents the different block ciphers specified for OpenPGP. See
  403. // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13
  404. type CipherFunction uint8
  405. const (
  406. Cipher3DES CipherFunction = 2
  407. CipherCAST5 CipherFunction = 3
  408. CipherAES128 CipherFunction = 7
  409. CipherAES192 CipherFunction = 8
  410. CipherAES256 CipherFunction = 9
  411. )
  412. // KeySize returns the key size, in bytes, of cipher.
  413. func (cipher CipherFunction) KeySize() int {
  414. switch cipher {
  415. case Cipher3DES:
  416. return 24
  417. case CipherCAST5:
  418. return cast5.KeySize
  419. case CipherAES128:
  420. return 16
  421. case CipherAES192:
  422. return 24
  423. case CipherAES256:
  424. return 32
  425. }
  426. return 0
  427. }
  428. // blockSize returns the block size, in bytes, of cipher.
  429. func (cipher CipherFunction) blockSize() int {
  430. switch cipher {
  431. case Cipher3DES:
  432. return des.BlockSize
  433. case CipherCAST5:
  434. return 8
  435. case CipherAES128, CipherAES192, CipherAES256:
  436. return 16
  437. }
  438. return 0
  439. }
  440. // new returns a fresh instance of the given cipher.
  441. func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
  442. switch cipher {
  443. case Cipher3DES:
  444. block, _ = des.NewTripleDESCipher(key)
  445. case CipherCAST5:
  446. block, _ = cast5.NewCipher(key)
  447. case CipherAES128, CipherAES192, CipherAES256:
  448. block, _ = aes.NewCipher(key)
  449. }
  450. return
  451. }
  452. // readMPI reads a big integer from r. The bit length returned is the bit
  453. // length that was specified in r. This is preserved so that the integer can be
  454. // reserialized exactly.
  455. func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
  456. var buf [2]byte
  457. _, err = readFull(r, buf[0:])
  458. if err != nil {
  459. return
  460. }
  461. bitLength = uint16(buf[0])<<8 | uint16(buf[1])
  462. numBytes := (int(bitLength) + 7) / 8
  463. mpi = make([]byte, numBytes)
  464. _, err = readFull(r, mpi)
  465. // According to RFC 4880 3.2. we should check that the MPI has no leading
  466. // zeroes (at least when not an encrypted MPI?), but this implementation
  467. // does generate leading zeroes, so we keep accepting them.
  468. return
  469. }
  470. // writeMPI serializes a big integer to w.
  471. func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
  472. // Note that we can produce leading zeroes, in violation of RFC 4880 3.2.
  473. // Implementations seem to be tolerant of them, and stripping them would
  474. // make it complex to guarantee matching re-serialization.
  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. // padToKeySize left-pads a MPI with zeroes to match the length of the
  486. // specified RSA public.
  487. func padToKeySize(pub *rsa.PublicKey, b []byte) []byte {
  488. k := (pub.N.BitLen() + 7) / 8
  489. if len(b) >= k {
  490. return b
  491. }
  492. bb := make([]byte, k)
  493. copy(bb[len(bb)-len(b):], b)
  494. return bb
  495. }
  496. // CompressionAlgo Represents the different compression algorithms
  497. // supported by OpenPGP (except for BZIP2, which is not currently
  498. // supported). See Section 9.3 of RFC 4880.
  499. type CompressionAlgo uint8
  500. const (
  501. CompressionNone CompressionAlgo = 0
  502. CompressionZIP CompressionAlgo = 1
  503. CompressionZLIB CompressionAlgo = 2
  504. )