clearsign.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // Copyright 2012 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 clearsign generates and processes OpenPGP, clear-signed data. See
  5. // RFC 4880, section 7.
  6. //
  7. // Clearsigned messages are cryptographically signed, but the contents of the
  8. // message are kept in plaintext so that it can be read without special tools.
  9. package clearsign // import "golang.org/x/crypto/openpgp/clearsign"
  10. import (
  11. "bufio"
  12. "bytes"
  13. "crypto"
  14. "fmt"
  15. "hash"
  16. "io"
  17. "net/textproto"
  18. "strconv"
  19. "golang.org/x/crypto/openpgp/armor"
  20. "golang.org/x/crypto/openpgp/errors"
  21. "golang.org/x/crypto/openpgp/packet"
  22. )
  23. // A Block represents a clearsigned message. A signature on a Block can
  24. // be checked by passing Bytes into openpgp.CheckDetachedSignature.
  25. type Block struct {
  26. Headers textproto.MIMEHeader // Optional message headers
  27. Plaintext []byte // The original message text
  28. Bytes []byte // The signed message
  29. ArmoredSignature *armor.Block // The signature block
  30. }
  31. // start is the marker which denotes the beginning of a clearsigned message.
  32. var start = []byte("\n-----BEGIN PGP SIGNED MESSAGE-----")
  33. // dashEscape is prefixed to any lines that begin with a hyphen so that they
  34. // can't be confused with endText.
  35. var dashEscape = []byte("- ")
  36. // endText is a marker which denotes the end of the message and the start of
  37. // an armored signature.
  38. var endText = []byte("-----BEGIN PGP SIGNATURE-----")
  39. // end is a marker which denotes the end of the armored signature.
  40. var end = []byte("\n-----END PGP SIGNATURE-----")
  41. var crlf = []byte("\r\n")
  42. var lf = byte('\n')
  43. // getLine returns the first \r\n or \n delineated line from the given byte
  44. // array. The line does not include the \r\n or \n. The remainder of the byte
  45. // array (also not including the new line bytes) is also returned and this will
  46. // always be smaller than the original argument.
  47. func getLine(data []byte) (line, rest []byte) {
  48. i := bytes.Index(data, []byte{'\n'})
  49. var j int
  50. if i < 0 {
  51. i = len(data)
  52. j = i
  53. } else {
  54. j = i + 1
  55. if i > 0 && data[i-1] == '\r' {
  56. i--
  57. }
  58. }
  59. return data[0:i], data[j:]
  60. }
  61. // Decode finds the first clearsigned message in data and returns it, as well
  62. // as the suffix of data which remains after the message.
  63. func Decode(data []byte) (b *Block, rest []byte) {
  64. // start begins with a newline. However, at the very beginning of
  65. // the byte array, we'll accept the start string without it.
  66. rest = data
  67. if bytes.HasPrefix(data, start[1:]) {
  68. rest = rest[len(start)-1:]
  69. } else if i := bytes.Index(data, start); i >= 0 {
  70. rest = rest[i+len(start):]
  71. } else {
  72. return nil, data
  73. }
  74. // Consume the start line.
  75. _, rest = getLine(rest)
  76. var line []byte
  77. b = &Block{
  78. Headers: make(textproto.MIMEHeader),
  79. }
  80. // Next come a series of header lines.
  81. for {
  82. // This loop terminates because getLine's second result is
  83. // always smaller than its argument.
  84. if len(rest) == 0 {
  85. return nil, data
  86. }
  87. // An empty line marks the end of the headers.
  88. if line, rest = getLine(rest); len(line) == 0 {
  89. break
  90. }
  91. i := bytes.Index(line, []byte{':'})
  92. if i == -1 {
  93. return nil, data
  94. }
  95. key, val := line[0:i], line[i+1:]
  96. key = bytes.TrimSpace(key)
  97. val = bytes.TrimSpace(val)
  98. b.Headers.Add(string(key), string(val))
  99. }
  100. firstLine := true
  101. for {
  102. start := rest
  103. line, rest = getLine(rest)
  104. if len(line) == 0 && len(rest) == 0 {
  105. // No armored data was found, so this isn't a complete message.
  106. return nil, data
  107. }
  108. if bytes.Equal(line, endText) {
  109. // Back up to the start of the line because armor expects to see the
  110. // header line.
  111. rest = start
  112. break
  113. }
  114. // The final CRLF isn't included in the hash so we don't write it until
  115. // we've seen the next line.
  116. if firstLine {
  117. firstLine = false
  118. } else {
  119. b.Bytes = append(b.Bytes, crlf...)
  120. }
  121. if bytes.HasPrefix(line, dashEscape) {
  122. line = line[2:]
  123. }
  124. line = bytes.TrimRight(line, " \t")
  125. b.Bytes = append(b.Bytes, line...)
  126. b.Plaintext = append(b.Plaintext, line...)
  127. b.Plaintext = append(b.Plaintext, lf)
  128. }
  129. // We want to find the extent of the armored data (including any newlines at
  130. // the end).
  131. i := bytes.Index(rest, end)
  132. if i == -1 {
  133. return nil, data
  134. }
  135. i += len(end)
  136. for i < len(rest) && (rest[i] == '\r' || rest[i] == '\n') {
  137. i++
  138. }
  139. armored := rest[:i]
  140. rest = rest[i:]
  141. var err error
  142. b.ArmoredSignature, err = armor.Decode(bytes.NewBuffer(armored))
  143. if err != nil {
  144. return nil, data
  145. }
  146. return b, rest
  147. }
  148. // A dashEscaper is an io.WriteCloser which processes the body of a clear-signed
  149. // message. The clear-signed message is written to buffered and a hash, suitable
  150. // for signing, is maintained in h.
  151. //
  152. // When closed, an armored signature is created and written to complete the
  153. // message.
  154. type dashEscaper struct {
  155. buffered *bufio.Writer
  156. hashers []hash.Hash // one per key in privateKeys
  157. hashType crypto.Hash
  158. toHash io.Writer // writes to all the hashes in hashers
  159. atBeginningOfLine bool
  160. isFirstLine bool
  161. whitespace []byte
  162. byteBuf []byte // a one byte buffer to save allocations
  163. privateKeys []*packet.PrivateKey
  164. config *packet.Config
  165. }
  166. func (d *dashEscaper) Write(data []byte) (n int, err error) {
  167. for _, b := range data {
  168. d.byteBuf[0] = b
  169. if d.atBeginningOfLine {
  170. // The final CRLF isn't included in the hash so we have to wait
  171. // until this point (the start of the next line) before writing it.
  172. if !d.isFirstLine {
  173. d.toHash.Write(crlf)
  174. }
  175. d.isFirstLine = false
  176. }
  177. // Any whitespace at the end of the line has to be removed so we
  178. // buffer it until we find out whether there's more on this line.
  179. if b == ' ' || b == '\t' || b == '\r' {
  180. d.whitespace = append(d.whitespace, b)
  181. d.atBeginningOfLine = false
  182. continue
  183. }
  184. if d.atBeginningOfLine {
  185. // At the beginning of a line, hyphens have to be escaped.
  186. if b == '-' {
  187. // The signature isn't calculated over the dash-escaped text so
  188. // the escape is only written to buffered.
  189. if _, err = d.buffered.Write(dashEscape); err != nil {
  190. return
  191. }
  192. d.toHash.Write(d.byteBuf)
  193. d.atBeginningOfLine = false
  194. } else if b == '\n' {
  195. // Nothing to do because we delay writing CRLF to the hash.
  196. } else {
  197. d.toHash.Write(d.byteBuf)
  198. d.atBeginningOfLine = false
  199. }
  200. if err = d.buffered.WriteByte(b); err != nil {
  201. return
  202. }
  203. } else {
  204. if b == '\n' {
  205. // We got a raw \n. Drop any trailing whitespace and write a
  206. // CRLF.
  207. d.whitespace = d.whitespace[:0]
  208. // We delay writing CRLF to the hash until the start of the
  209. // next line.
  210. if err = d.buffered.WriteByte(b); err != nil {
  211. return
  212. }
  213. d.atBeginningOfLine = true
  214. } else {
  215. // Any buffered whitespace wasn't at the end of the line so
  216. // we need to write it out.
  217. if len(d.whitespace) > 0 {
  218. d.toHash.Write(d.whitespace)
  219. if _, err = d.buffered.Write(d.whitespace); err != nil {
  220. return
  221. }
  222. d.whitespace = d.whitespace[:0]
  223. }
  224. d.toHash.Write(d.byteBuf)
  225. if err = d.buffered.WriteByte(b); err != nil {
  226. return
  227. }
  228. }
  229. }
  230. }
  231. n = len(data)
  232. return
  233. }
  234. func (d *dashEscaper) Close() (err error) {
  235. if !d.atBeginningOfLine {
  236. if err = d.buffered.WriteByte(lf); err != nil {
  237. return
  238. }
  239. }
  240. out, err := armor.Encode(d.buffered, "PGP SIGNATURE", nil)
  241. if err != nil {
  242. return
  243. }
  244. t := d.config.Now()
  245. for i, k := range d.privateKeys {
  246. sig := new(packet.Signature)
  247. sig.SigType = packet.SigTypeText
  248. sig.PubKeyAlgo = k.PubKeyAlgo
  249. sig.Hash = d.hashType
  250. sig.CreationTime = t
  251. sig.IssuerKeyId = &k.KeyId
  252. if err = sig.Sign(d.hashers[i], k, d.config); err != nil {
  253. return
  254. }
  255. if err = sig.Serialize(out); err != nil {
  256. return
  257. }
  258. }
  259. if err = out.Close(); err != nil {
  260. return
  261. }
  262. if err = d.buffered.Flush(); err != nil {
  263. return
  264. }
  265. return
  266. }
  267. // Encode returns a WriteCloser which will clear-sign a message with privateKey
  268. // and write it to w. If config is nil, sensible defaults are used.
  269. func Encode(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) {
  270. return EncodeMulti(w, []*packet.PrivateKey{privateKey}, config)
  271. }
  272. // EncodeMulti returns a WriteCloser which will clear-sign a message with all the
  273. // private keys indicated and write it to w. If config is nil, sensible defaults
  274. // are used.
  275. func EncodeMulti(w io.Writer, privateKeys []*packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) {
  276. for _, k := range privateKeys {
  277. if k.Encrypted {
  278. return nil, errors.InvalidArgumentError(fmt.Sprintf("signing key %s is encrypted", k.KeyIdString()))
  279. }
  280. }
  281. hashType := config.Hash()
  282. name := nameOfHash(hashType)
  283. if len(name) == 0 {
  284. return nil, errors.UnsupportedError("unknown hash type: " + strconv.Itoa(int(hashType)))
  285. }
  286. if !hashType.Available() {
  287. return nil, errors.UnsupportedError("unsupported hash type: " + strconv.Itoa(int(hashType)))
  288. }
  289. var hashers []hash.Hash
  290. var ws []io.Writer
  291. for range privateKeys {
  292. h := hashType.New()
  293. hashers = append(hashers, h)
  294. ws = append(ws, h)
  295. }
  296. toHash := io.MultiWriter(ws...)
  297. buffered := bufio.NewWriter(w)
  298. // start has a \n at the beginning that we don't want here.
  299. if _, err = buffered.Write(start[1:]); err != nil {
  300. return
  301. }
  302. if err = buffered.WriteByte(lf); err != nil {
  303. return
  304. }
  305. if _, err = buffered.WriteString("Hash: "); err != nil {
  306. return
  307. }
  308. if _, err = buffered.WriteString(name); err != nil {
  309. return
  310. }
  311. if err = buffered.WriteByte(lf); err != nil {
  312. return
  313. }
  314. if err = buffered.WriteByte(lf); err != nil {
  315. return
  316. }
  317. plaintext = &dashEscaper{
  318. buffered: buffered,
  319. hashers: hashers,
  320. hashType: hashType,
  321. toHash: toHash,
  322. atBeginningOfLine: true,
  323. isFirstLine: true,
  324. byteBuf: make([]byte, 1),
  325. privateKeys: privateKeys,
  326. config: config,
  327. }
  328. return
  329. }
  330. // nameOfHash returns the OpenPGP name for the given hash, or the empty string
  331. // if the name isn't known. See RFC 4880, section 9.4.
  332. func nameOfHash(h crypto.Hash) string {
  333. switch h {
  334. case crypto.MD5:
  335. return "MD5"
  336. case crypto.SHA1:
  337. return "SHA1"
  338. case crypto.RIPEMD160:
  339. return "RIPEMD160"
  340. case crypto.SHA224:
  341. return "SHA224"
  342. case crypto.SHA256:
  343. return "SHA256"
  344. case crypto.SHA384:
  345. return "SHA384"
  346. case crypto.SHA512:
  347. return "SHA512"
  348. }
  349. return ""
  350. }