clearsign.go 9.2 KB

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