PageRenderTime 24ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/golang.org/x/crypto/openpgp/packet/packet.go

https://gitlab.com/zanderwong/lantern
Go | 539 lines | 433 code | 45 blank | 61 comment | 87 complexity | 400f4ffed78112802580b36e05e5d481 MD5 | raw file
  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. panic("unreachable")
  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. return
  466. }
  467. // mpiLength returns the length of the given *big.Int when serialized as an
  468. // MPI.
  469. func mpiLength(n *big.Int) (mpiLengthInBytes int) {
  470. mpiLengthInBytes = 2 /* MPI length */
  471. mpiLengthInBytes += (n.BitLen() + 7) / 8
  472. return
  473. }
  474. // writeMPI serializes a big integer to w.
  475. func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
  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. // CompressionAlgo Represents the different compression algorithms
  487. // supported by OpenPGP (except for BZIP2, which is not currently
  488. // supported). See Section 9.3 of RFC 4880.
  489. type CompressionAlgo uint8
  490. const (
  491. CompressionNone CompressionAlgo = 0
  492. CompressionZIP CompressionAlgo = 1
  493. CompressionZLIB CompressionAlgo = 2
  494. )