clearsign.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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
  10. import (
  11. "bufio"
  12. "bytes"
  13. "crypto"
  14. "hash"
  15. "io"
  16. "net/textproto"
  17. "strconv"
  18. "code.google.com/p/go.crypto/openpgp/armor"
  19. "code.google.com/p/go.crypto/openpgp/errors"
  20. "code.google.com/p/go.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. for {
  100. start := rest
  101. line, rest = getLine(rest)
  102. if bytes.Equal(line, endText) {
  103. // Back up to the start of the line because armor expects to see the
  104. // header line.
  105. rest = start
  106. break
  107. }
  108. // The final CRLF isn't included in the hash so we don't write it until
  109. // we've seen the next line.
  110. if len(b.Bytes) > 0 {
  111. b.Bytes = append(b.Bytes, crlf...)
  112. }
  113. if bytes.HasPrefix(line, dashEscape) {
  114. line = line[2:]
  115. }
  116. line = bytes.TrimRight(line, " \t")
  117. b.Bytes = append(b.Bytes, line...)
  118. b.Plaintext = append(b.Plaintext, line...)
  119. b.Plaintext = append(b.Plaintext, lf)
  120. }
  121. // We want to find the extent of the armored data (including any newlines at
  122. // the end).
  123. i := bytes.Index(rest, end)
  124. if i == -1 {
  125. return nil, data
  126. }
  127. i += len(end)
  128. for i < len(rest) && (rest[i] == '\r' || rest[i] == '\n') {
  129. i++
  130. }
  131. armored := rest[:i]
  132. rest = rest[i:]
  133. var err error
  134. b.ArmoredSignature, err = armor.Decode(bytes.NewBuffer(armored))
  135. if err != nil {
  136. return nil, data
  137. }
  138. return b, rest
  139. }
  140. // A dashEscaper is an io.WriteCloser which processes the body of a clear-signed
  141. // message. The clear-signed message is written to buffered and a hash, suitable
  142. // for signing, is maintained in h.
  143. //
  144. // When closed, an armored signature is created and written to complete the
  145. // message.
  146. type dashEscaper struct {
  147. buffered *bufio.Writer
  148. h hash.Hash
  149. hashType crypto.Hash
  150. atBeginningOfLine bool
  151. isFirstLine bool
  152. whitespace []byte
  153. byteBuf []byte // a one byte buffer to save allocations
  154. privateKey *packet.PrivateKey
  155. config *packet.Config
  156. }
  157. func (d *dashEscaper) Write(data []byte) (n int, err error) {
  158. for _, b := range data {
  159. d.byteBuf[0] = b
  160. if d.atBeginningOfLine {
  161. // The final CRLF isn't included in the hash so we have to wait
  162. // until this point (the start of the next line) before writing it.
  163. if !d.isFirstLine {
  164. d.h.Write(crlf)
  165. }
  166. d.isFirstLine = false
  167. // At the beginning of a line, hyphens have to be escaped.
  168. if b == '-' {
  169. // The signature isn't calculated over the dash-escaped text so
  170. // the escape is only written to buffered.
  171. if _, err = d.buffered.Write(dashEscape); err != nil {
  172. return
  173. }
  174. d.h.Write(d.byteBuf)
  175. d.atBeginningOfLine = false
  176. } else if b == '\n' {
  177. // Nothing to do because we dely writing CRLF to the hash.
  178. } else {
  179. d.h.Write(d.byteBuf)
  180. d.atBeginningOfLine = false
  181. }
  182. if err = d.buffered.WriteByte(b); err != nil {
  183. return
  184. }
  185. } else {
  186. // Any whitespace at the end of the line has to be removed so we
  187. // buffer it until we find out whether there's more on this line.
  188. if b == ' ' || b == '\t' || b == '\r' {
  189. d.whitespace = append(d.whitespace, b)
  190. } else if b == '\n' {
  191. // We got a raw \n. Drop any trailing whitespace and write a
  192. // CRLF.
  193. d.whitespace = d.whitespace[:0]
  194. // We dely writing CRLF to the hash until the start of the
  195. // next line.
  196. if err = d.buffered.WriteByte(b); err != nil {
  197. return
  198. }
  199. d.atBeginningOfLine = true
  200. } else {
  201. // Any buffered whitespace wasn't at the end of the line so
  202. // we need to write it out.
  203. if len(d.whitespace) > 0 {
  204. d.h.Write(d.whitespace)
  205. if _, err = d.buffered.Write(d.whitespace); err != nil {
  206. return
  207. }
  208. d.whitespace = d.whitespace[:0]
  209. }
  210. d.h.Write(d.byteBuf)
  211. if err = d.buffered.WriteByte(b); err != nil {
  212. return
  213. }
  214. }
  215. }
  216. }
  217. n = len(data)
  218. return
  219. }
  220. func (d *dashEscaper) Close() (err error) {
  221. if !d.atBeginningOfLine {
  222. if err = d.buffered.WriteByte(lf); err != nil {
  223. return
  224. }
  225. }
  226. sig := new(packet.Signature)
  227. sig.SigType = packet.SigTypeText
  228. sig.PubKeyAlgo = d.privateKey.PubKeyAlgo
  229. sig.Hash = d.hashType
  230. sig.CreationTime = d.config.Now()
  231. sig.IssuerKeyId = &d.privateKey.KeyId
  232. if err = sig.Sign(d.h, d.privateKey, d.config); err != nil {
  233. return
  234. }
  235. out, err := armor.Encode(d.buffered, "PGP SIGNATURE", nil)
  236. if err != nil {
  237. return
  238. }
  239. if err = sig.Serialize(out); err != nil {
  240. return
  241. }
  242. if err = out.Close(); err != nil {
  243. return
  244. }
  245. if err = d.buffered.Flush(); err != nil {
  246. return
  247. }
  248. return
  249. }
  250. // Encode returns a WriteCloser which will clear-sign a message with privateKey
  251. // and write it to w. If config is nil, sensible defaults are used.
  252. func Encode(w io.Writer, privateKey *packet.PrivateKey, config *packet.Config) (plaintext io.WriteCloser, err error) {
  253. if privateKey.Encrypted {
  254. return nil, errors.InvalidArgumentError("signing key is encrypted")
  255. }
  256. hashType := config.Hash()
  257. name := nameOfHash(hashType)
  258. if len(name) == 0 {
  259. return nil, errors.UnsupportedError("unknown hash type: " + strconv.Itoa(int(hashType)))
  260. }
  261. h := hashType.New()
  262. if h == nil {
  263. return nil, errors.UnsupportedError("unsupported hash type: " + strconv.Itoa(int(hashType)))
  264. }
  265. buffered := bufio.NewWriter(w)
  266. // start has a \n at the beginning that we don't want here.
  267. if _, err = buffered.Write(start[1:]); err != nil {
  268. return
  269. }
  270. if err = buffered.WriteByte(lf); err != nil {
  271. return
  272. }
  273. if _, err = buffered.WriteString("Hash: "); err != nil {
  274. return
  275. }
  276. if _, err = buffered.WriteString(name); err != nil {
  277. return
  278. }
  279. if err = buffered.WriteByte(lf); err != nil {
  280. return
  281. }
  282. if err = buffered.WriteByte(lf); err != nil {
  283. return
  284. }
  285. plaintext = &dashEscaper{
  286. buffered: buffered,
  287. h: h,
  288. hashType: hashType,
  289. atBeginningOfLine: true,
  290. isFirstLine: true,
  291. byteBuf: make([]byte, 1),
  292. privateKey: privateKey,
  293. config: config,
  294. }
  295. return
  296. }
  297. // nameOfHash returns the OpenPGP name for the given hash, or the empty string
  298. // if the name isn't known. See RFC 4880, section 9.4.
  299. func nameOfHash(h crypto.Hash) string {
  300. switch h {
  301. case crypto.MD5:
  302. return "MD5"
  303. case crypto.SHA1:
  304. return "SHA1"
  305. case crypto.RIPEMD160:
  306. return "RIPEMD160"
  307. case crypto.SHA224:
  308. return "SHA224"
  309. case crypto.SHA256:
  310. return "SHA256"
  311. case crypto.SHA384:
  312. return "SHA384"
  313. case crypto.SHA512:
  314. return "SHA512"
  315. }
  316. return ""
  317. }