hardening_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package pdfrender
  2. import (
  3. "bytes"
  4. "fmt"
  5. "runtime/debug"
  6. "strings"
  7. "testing"
  8. "time"
  9. "github.com/go-pdf/fpdf"
  10. "golang.org/x/image/font/gofont/goregular"
  11. )
  12. /*
  13. Untrusted input: every PDF in a user's folder gets parsed for its
  14. thumbnail, so crafted files must not panic, hang or allocate wildly.
  15. */
  16. // renderUntrusted opens and renders data, turning a panic into an error
  17. func renderUntrusted(data []byte) (err error, took time.Duration) {
  18. start := time.Now()
  19. defer func() {
  20. took = time.Since(start)
  21. if p := recover(); p != nil {
  22. err = fmt.Errorf("panic: %v\n%s", p, debug.Stack())
  23. }
  24. }()
  25. doc, e := Open(bytes.NewReader(data), int64(len(data)))
  26. if e != nil {
  27. return nil, 0
  28. }
  29. doc.Render(0, Options{Scale: 0.5, Timeout: 2 * time.Second})
  30. return nil, 0
  31. }
  32. func hardeningFixtures(t *testing.T) map[string][]byte {
  33. cffData := buildCFF()
  34. t1Data, t1Len := buildType1()
  35. fonts := onePage(100, 100, "/Font << /F1 4 0 R /F2 5 0 R /F3 6 0 R >>",
  36. "BT /F1 50 Tf 0 0 Td (AA) Tj /F2 50 Tf (AA) Tj /F3 50 Tf (AA) Tj ET", func(b *pdfBuilder) string {
  37. b.reserve()
  38. b.reserve()
  39. b.reserve()
  40. ff := b.addStream("/Subtype /Type1C", cffData)
  41. fd := b.add(fmt.Sprintf("<< /Type /FontDescriptor /Flags 32 /FontFile3 %d 0 R >>", ff))
  42. b.set(4, fmt.Sprintf("<< /Type /Font /Subtype /Type1 /FirstChar 65 /LastChar 65 /Widths [700] /FontDescriptor %d 0 R >>", fd))
  43. ff1 := b.addStream(fmt.Sprintf("/Length1 %d", t1Len), t1Data)
  44. fd1 := b.add(fmt.Sprintf("<< /Type /FontDescriptor /Flags 32 /FontFile %d 0 R >>", ff1))
  45. b.set(5, fmt.Sprintf("<< /Type /Font /Subtype /Type1 /FontDescriptor %d 0 R >>", fd1))
  46. proc := b.addStream("", []byte("1000 0 0 0 1000 1000 d1 100 100 500 500 re f"))
  47. b.set(6, fmt.Sprintf("<< /Type /Font /Subtype /Type3 /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /sq %d 0 R >> /Encoding << /Differences [65 /sq] >> /FirstChar 65 /LastChar 65 /Widths [1000] >>", proc))
  48. return ""
  49. })
  50. graphics := onePage(100, 100, `/Shading << /S << /ShadingType 3 /ColorSpace /DeviceRGB /Coords [50 50 0 50 50 50]
  51. /Function << /FunctionType 3 /Domain [0 1] /Bounds [0.5] /Encode [0 1 0 1] /Functions [
  52. << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 1 0] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [0 1 0] /C1 [0 0 1] /N 1 >> ] >> >> >>
  53. /ColorSpace << /I [/Indexed /DeviceRGB 2 <ff0000 00ff00 0000ff>] /L [/Lab << /WhitePoint [0.95 1 1.09] >>] >>
  54. /XObject << /Im 4 0 R >> /ExtGState << /G << /ca 0.5 /BM /Multiply /D [[3 2] 0] /LW 2 >> >>`,
  55. "q 10 10 80 80 re W n /S sh Q /G gs /I cs 2 sc 0 0 50 50 re f /L cs 50 20 -30 sc 50 50 50 50 re f 0 G 1 J 1 j 10 10 m 90 90 l 10 90 l S q 50 0 0 50 0 0 cm /Im Do Q",
  56. func(b *pdfBuilder) string {
  57. b.addStream("/Type /XObject /Subtype /Image /Width 3 /Height 2 /ColorSpace /I /BitsPerComponent 4", []byte{0x01, 0x20, 0x12, 0x00})
  58. return ""
  59. })
  60. pdf := fpdf.New("P", "pt", "A4", "")
  61. pdf.SetCompression(false)
  62. pdf.AddUTF8FontFromBytes("gofont", "", goregular.TTF)
  63. pdf.AddPage()
  64. pdf.SetFont("gofont", "", 30)
  65. pdf.Text(40, 80, "Hello")
  66. pdf.SetFont("Times", "", 30)
  67. pdf.Text(40, 160, "World")
  68. var fb bytes.Buffer
  69. pdf.Output(&fb)
  70. return map[string][]byte{
  71. "fonts": fonts,
  72. "graphics": graphics,
  73. "xrefstm": xrefStreamDoc(t),
  74. "fpdf": fb.Bytes(),
  75. "aes256": aes256Doc(t, false),
  76. }
  77. }
  78. func TestBoundaryValuesDoNotPanic(t *testing.T) {
  79. patterns := [][]byte{
  80. []byte("0"), []byte("-1"), []byte("2147483647"), []byte("4294967295"),
  81. []byte("99999999999"), {0xff, 0xff, 0xff, 0xff}, {0x7f, 0xff, 0xff, 0xff}, []byte("[[<<"),
  82. }
  83. positions := 120
  84. if testing.Short() {
  85. positions = 30
  86. }
  87. failures := 0
  88. for name, data := range hardeningFixtures(t) {
  89. step := len(data) / positions
  90. if step < 1 {
  91. step = 1
  92. }
  93. for pos := 0; pos < len(data); pos += step {
  94. for _, pat := range patterns {
  95. m := append([]byte{}, data...)
  96. copy(m[pos:], pat)
  97. err, took := renderUntrusted(m)
  98. if err != nil && failures < 5 {
  99. failures++
  100. t.Errorf("%s: %q at %d: %v", name, pat, pos, err)
  101. }
  102. if took > 4*time.Second && failures < 5 {
  103. failures++
  104. t.Errorf("%s: %q at %d took %v", name, pat, pos, took)
  105. }
  106. }
  107. }
  108. }
  109. }
  110. // Font programs straight into their parsers, every glyph drawn
  111. func TestFontParsersBoundaryValues(t *testing.T) {
  112. t1Data, t1Len := buildType1()
  113. blobs := map[string][]byte{"truetype": goregular.TTF, "cff": buildCFF(), "type1": t1Data}
  114. words := [][]byte{{0x7f, 0xff, 0xff, 0xff}, {0x80, 0, 0, 0}, {0xff, 0xff, 0xff, 0xff}, {0x01, 0, 0, 0}, {0, 0, 0, 0}}
  115. positions := 300
  116. if testing.Short() {
  117. positions = 60
  118. }
  119. for name, blob := range blobs {
  120. step := len(blob) / positions
  121. if step < 1 {
  122. step = 1
  123. }
  124. for pos := 0; pos+4 <= len(blob); pos += step {
  125. for _, w := range words {
  126. m := append([]byte{}, blob...)
  127. copy(m[pos:], w)
  128. func() {
  129. defer func() {
  130. if p := recover(); p != nil {
  131. t.Fatalf("%s: word %x at %d: panic %v\n%s", name, w, pos, p, debug.Stack())
  132. }
  133. }()
  134. switch name {
  135. case "truetype":
  136. if f, err := parseSFNT(m); err == nil {
  137. for g := 0; g < f.numGlyphs && g < 400; g++ {
  138. f.glyphPath(g).flatten(identity, 1)
  139. }
  140. f.unicodeGID('A')
  141. f.cmapLookup(3, 0, 0xF041)
  142. }
  143. case "cff":
  144. if f, err := parseCFF(m); err == nil {
  145. for g := 0; g < len(f.charStrings); g++ {
  146. f.glyphPath(g)
  147. }
  148. f.gidForName("A")
  149. }
  150. case "type1":
  151. if f, err := parseType1(m, t1Len); err == nil {
  152. f.glyphPath("A")
  153. }
  154. }
  155. }()
  156. }
  157. }
  158. }
  159. }
  160. func TestPathologicalInputs(t *testing.T) {
  161. recursiveType3 := onePage(100, 100, "/Font << /F 4 0 R >>", "BT /F 10 Tf (AAAA) Tj ET", func(b *pdfBuilder) string {
  162. b.reserve()
  163. proc := b.addStream("", []byte("1000 0 d0 BT /F 10 Tf (AAAA) Tj ET"))
  164. b.set(4, fmt.Sprintf("<< /Type /Font /Subtype /Type3 /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a %d 0 R >> /Encoding << /Differences [65 /a] >> /FirstChar 65 /LastChar 65 /Widths [1000] /Resources << /Font << /F 4 0 R >> >> >>", proc))
  165. return ""
  166. })
  167. formCycle := onePage(100, 100, "/XObject << /A 4 0 R >>", "/A Do", func(b *pdfBuilder) string {
  168. b.addStream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /XObject << /B 5 0 R >> >>", []byte("/B Do"))
  169. b.addStream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /XObject << /A 4 0 R >> >>", []byte("/A Do"))
  170. return ""
  171. })
  172. selfPattern := onePage(100, 100, "/Pattern << /P 4 0 R >>", "/Pattern cs /P scn 0 0 100 100 re f", func(b *pdfBuilder) string {
  173. b.addStream("/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /Resources << /Pattern << /P 4 0 R >> >>", []byte("/Pattern cs /P scn 0 0 1 1 re f"))
  174. return ""
  175. })
  176. selfSMask := onePage(100, 100, "/ExtGState << /G << /SMask << /S /Luminosity /G 4 0 R >> >> >>", "/G gs 0 0 100 100 re f", func(b *pdfBuilder) string {
  177. b.addStream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources << /ExtGState << /G << /SMask << /S /Luminosity /G 4 0 R >> >> >> >>", []byte("/G gs 1 g 0 0 100 100 re f"))
  178. return ""
  179. })
  180. hugeImage := onePage(100, 100, "/XObject << /I 4 0 R >>", "100 0 0 100 0 0 cm /I Do", func(b *pdfBuilder) string {
  181. b.addStream("/Type /XObject /Subtype /Image /Width 2000000000 /Height 2000000000 /ColorSpace /DeviceRGB /BitsPerComponent 8", []byte{1, 2, 3})
  182. return ""
  183. })
  184. //A long zigzag stroked very wide with round joins: one paint operator
  185. //whose outline alone outlasts the time budget
  186. var zig strings.Builder
  187. zig.WriteString("1 j 1 J 0.2 0 0 0.2 0 0 cm 5000 w 0 0 m ")
  188. for i := 0; i < 200000; i++ {
  189. fmt.Fprintf(&zig, "%d %d l ", i%500, (i*7)%499)
  190. }
  191. zig.WriteString("S")
  192. refCycle := []byte("%PDF-1.4\n1 0 obj\n2 0 R\nendobj\n2 0 obj\n1 0 R\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n")
  193. prevLoop := []byte("%PDF-1.4\nxref\n0 1\n0000000000 65535 f \ntrailer\n<< /Size 1 /Prev 9 >>\nstartxref\n9\n%%EOF\n")
  194. cases := map[string][]byte{
  195. "recursive type3 glyph": recursiveType3,
  196. "form cycle": formCycle,
  197. "pattern using itself": selfPattern,
  198. "soft mask using itself": selfSMask,
  199. "huge image": hugeImage,
  200. "reference cycle": refCycle,
  201. "xref prev loop": prevLoop,
  202. "deep content nesting": onePage(100, 100, "", strings.Repeat("[", 200000)+" Tj", nil),
  203. "wide zigzag stroke": onePage(100, 100, "", zig.String(), nil),
  204. "tiny dashes": onePage(100, 100, "", "[0.0001 0.0001] 0 d 1e6 w 0 0 m 1e9 1e9 l S", nil),
  205. "huge coordinates": onePage(100, 100, "", "1e30 1e30 m -1e30 1e30 l 1e30 -1e30 l f 1e38 0 0 1e38 0 0 cm 0 0 1 1 re f", nil),
  206. "unbalanced state": onePage(100, 100, "", strings.Repeat("q ", 10000)+strings.Repeat("Q ", 20000)+"BT BT ET ET EMC EMC", nil),
  207. "degenerate matrix": onePage(100, 100, "/XObject << /I 4 0 R >>", "0 0 0 0 0 0 cm /I Do 0 0 m 10 10 l S", func(b *pdfBuilder) string {
  208. b.addStream("/Subtype /Image /Width 1 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceGray", []byte{0})
  209. return ""
  210. }),
  211. "postscript stack abuse": onePage(100, 100, "/ColorSpace << /C [/Separation /X /DeviceRGB 4 0 R] >>", "/C cs 1 sc 0 0 100 100 re f", func(b *pdfBuilder) string {
  212. b.addStream("/FunctionType 4 /Domain [0 1] /Range [0 1 0 1 0 1]", []byte("{ "+strings.Repeat("dup ", 500)+strings.Repeat("{ ", 40)+" }"))
  213. return ""
  214. }),
  215. "sampled function sizes": onePage(100, 100, "/ColorSpace << /C [/Separation /X /DeviceRGB 4 0 R] >>", "/C cs 1 sc 0 0 100 100 re f", func(b *pdfBuilder) string {
  216. b.addStream("/FunctionType 0 /Domain [0 1 0 1 0 1 0 1] /Range [0 1] /Size [65536 65536 65536 65536] /BitsPerSample 8", []byte{1})
  217. return ""
  218. }),
  219. }
  220. for name, data := range cases {
  221. t.Run(name, func(t *testing.T) {
  222. err, took := renderUntrusted(data)
  223. if err != nil {
  224. t.Fatal(err)
  225. }
  226. if took > 4*time.Second {
  227. t.Errorf("took %v", took)
  228. }
  229. })
  230. }
  231. }