├── .gitignore
├── LICENSE
├── README.md
├── main.go
└── pdf
├── action.go
├── array.go
├── dictionary.go
├── encryption.go
├── errors.go
├── file.go
├── filters.go
├── font.go
├── keyword.go
├── logger.go
├── name.go
├── number.go
├── object.go
├── output.go
├── page.go
├── parser.go
├── pdf.go
├── reference.go
├── string.go
├── test
├── carriage_return.pdf
├── comments.pdf
├── empty_array.pdf
├── empty_dictionary.pdf
├── encrypted.pdf
├── filter_ascii_85_decode.pdf
├── filter_ascii_hex_decode.pdf
├── filter_flate_decode.pdf
├── filter_lzw_decode.pdf
├── filter_lzw_tiff_decode.pdf
├── filter_multiple.pdf
├── filter_run_length_decode.pdf
├── malformed_dictionary_key.pdf
├── max_cmap_size.pdf
├── names.pdf
├── reference.pdf
├── reference_loop.pdf
├── reference_null.pdf
├── strings.pdf
├── unclosed_array.pdf
├── unclosed_comment.pdf
├── unclosed_dictionary.pdf
├── unclosed_dictionary_key.pdf
├── unclosed_hex_string.pdf
├── unclosed_name.pdf
├── unclosed_name_escape_1.pdf
├── unclosed_name_escape_2.pdf
├── unclosed_string.pdf
├── unclosed_string_escape.pdf
├── unclosed_string_octal_1.pdf
├── unclosed_string_octal_2.pdf
├── xref_loop.pdf
├── xref_repair.pdf
├── xref_stream_chain.pdf
├── xref_stream_index_default.pdf
└── xref_table_chain.pdf
├── unit_test.go
├── utility.go
└── xref.go
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 | pdfparser
3 | *.extracted/
4 | output/
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | PDF Parser
2 | Decrypts PDF files and extracts contents
3 | Copyright (C) 2019 Cole Robinette
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License version 3 as published
7 | by the Free Software Foundation.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | GNU GENERAL PUBLIC LICENSE
15 | Version 3, 29 June 2007
16 |
17 | Copyright (C) 2007 Free Software Foundation, Inc.
18 | Everyone is permitted to copy and distribute verbatim copies
19 | of this license document, but changing it is not allowed.
20 |
21 | Preamble
22 |
23 | The GNU General Public License is a free, copyleft license for
24 | software and other kinds of works.
25 |
26 | The licenses for most software and other practical works are designed
27 | to take away your freedom to share and change the works. By contrast,
28 | the GNU General Public License is intended to guarantee your freedom to
29 | share and change all versions of a program--to make sure it remains free
30 | software for all its users. We, the Free Software Foundation, use the
31 | GNU General Public License for most of our software; it applies also to
32 | any other work released this way by its authors. You can apply it to
33 | your programs, too.
34 |
35 | When we speak of free software, we are referring to freedom, not
36 | price. Our General Public Licenses are designed to make sure that you
37 | have the freedom to distribute copies of free software (and charge for
38 | them if you wish), that you receive source code or can get it if you
39 | want it, that you can change the software or use pieces of it in new
40 | free programs, and that you know you can do these things.
41 |
42 | To protect your rights, we need to prevent others from denying you
43 | these rights or asking you to surrender the rights. Therefore, you have
44 | certain responsibilities if you distribute copies of the software, or if
45 | you modify it: responsibilities to respect the freedom of others.
46 |
47 | For example, if you distribute copies of such a program, whether
48 | gratis or for a fee, you must pass on to the recipients the same
49 | freedoms that you received. You must make sure that they, too, receive
50 | or can get the source code. And you must show them these terms so they
51 | know their rights.
52 |
53 | Developers that use the GNU GPL protect your rights with two steps:
54 | (1) assert copyright on the software, and (2) offer you this License
55 | giving you legal permission to copy, distribute and/or modify it.
56 |
57 | For the developers' and authors' protection, the GPL clearly explains
58 | that there is no warranty for this free software. For both users' and
59 | authors' sake, the GPL requires that modified versions be marked as
60 | changed, so that their problems will not be attributed erroneously to
61 | authors of previous versions.
62 |
63 | Some devices are designed to deny users access to install or run
64 | modified versions of the software inside them, although the manufacturer
65 | can do so. This is fundamentally incompatible with the aim of
66 | protecting users' freedom to change the software. The systematic
67 | pattern of such abuse occurs in the area of products for individuals to
68 | use, which is precisely where it is most unacceptable. Therefore, we
69 | have designed this version of the GPL to prohibit the practice for those
70 | products. If such problems arise substantially in other domains, we
71 | stand ready to extend this provision to those domains in future versions
72 | of the GPL, as needed to protect the freedom of users.
73 |
74 | Finally, every program is threatened constantly by software patents.
75 | States should not allow patents to restrict development and use of
76 | software on general-purpose computers, but in those that do, we wish to
77 | avoid the special danger that patents applied to a free program could
78 | make it effectively proprietary. To prevent this, the GPL assures that
79 | patents cannot be used to render the program non-free.
80 |
81 | The precise terms and conditions for copying, distribution and
82 | modification follow.
83 |
84 | TERMS AND CONDITIONS
85 |
86 | 0. Definitions.
87 |
88 | "This License" refers to version 3 of the GNU General Public License.
89 |
90 | "Copyright" also means copyright-like laws that apply to other kinds of
91 | works, such as semiconductor masks.
92 |
93 | "The Program" refers to any copyrightable work licensed under this
94 | License. Each licensee is addressed as "you". "Licensees" and
95 | "recipients" may be individuals or organizations.
96 |
97 | To "modify" a work means to copy from or adapt all or part of the work
98 | in a fashion requiring copyright permission, other than the making of an
99 | exact copy. The resulting work is called a "modified version" of the
100 | earlier work or a work "based on" the earlier work.
101 |
102 | A "covered work" means either the unmodified Program or a work based
103 | on the Program.
104 |
105 | To "propagate" a work means to do anything with it that, without
106 | permission, would make you directly or secondarily liable for
107 | infringement under applicable copyright law, except executing it on a
108 | computer or modifying a private copy. Propagation includes copying,
109 | distribution (with or without modification), making available to the
110 | public, and in some countries other activities as well.
111 |
112 | To "convey" a work means any kind of propagation that enables other
113 | parties to make or receive copies. Mere interaction with a user through
114 | a computer network, with no transfer of a copy, is not conveying.
115 |
116 | An interactive user interface displays "Appropriate Legal Notices"
117 | to the extent that it includes a convenient and prominently visible
118 | feature that (1) displays an appropriate copyright notice, and (2)
119 | tells the user that there is no warranty for the work (except to the
120 | extent that warranties are provided), that licensees may convey the
121 | work under this License, and how to view a copy of this License. If
122 | the interface presents a list of user commands or options, such as a
123 | menu, a prominent item in the list meets this criterion.
124 |
125 | 1. Source Code.
126 |
127 | The "source code" for a work means the preferred form of the work
128 | for making modifications to it. "Object code" means any non-source
129 | form of a work.
130 |
131 | A "Standard Interface" means an interface that either is an official
132 | standard defined by a recognized standards body, or, in the case of
133 | interfaces specified for a particular programming language, one that
134 | is widely used among developers working in that language.
135 |
136 | The "System Libraries" of an executable work include anything, other
137 | than the work as a whole, that (a) is included in the normal form of
138 | packaging a Major Component, but which is not part of that Major
139 | Component, and (b) serves only to enable use of the work with that
140 | Major Component, or to implement a Standard Interface for which an
141 | implementation is available to the public in source code form. A
142 | "Major Component", in this context, means a major essential component
143 | (kernel, window system, and so on) of the specific operating system
144 | (if any) on which the executable work runs, or a compiler used to
145 | produce the work, or an object code interpreter used to run it.
146 |
147 | The "Corresponding Source" for a work in object code form means all
148 | the source code needed to generate, install, and (for an executable
149 | work) run the object code and to modify the work, including scripts to
150 | control those activities. However, it does not include the work's
151 | System Libraries, or general-purpose tools or generally available free
152 | programs which are used unmodified in performing those activities but
153 | which are not part of the work. For example, Corresponding Source
154 | includes interface definition files associated with source files for
155 | the work, and the source code for shared libraries and dynamically
156 | linked subprograms that the work is specifically designed to require,
157 | such as by intimate data communication or control flow between those
158 | subprograms and other parts of the work.
159 |
160 | The Corresponding Source need not include anything that users
161 | can regenerate automatically from other parts of the Corresponding
162 | Source.
163 |
164 | The Corresponding Source for a work in source code form is that
165 | same work.
166 |
167 | 2. Basic Permissions.
168 |
169 | All rights granted under this License are granted for the term of
170 | copyright on the Program, and are irrevocable provided the stated
171 | conditions are met. This License explicitly affirms your unlimited
172 | permission to run the unmodified Program. The output from running a
173 | covered work is covered by this License only if the output, given its
174 | content, constitutes a covered work. This License acknowledges your
175 | rights of fair use or other equivalent, as provided by copyright law.
176 |
177 | You may make, run and propagate covered works that you do not
178 | convey, without conditions so long as your license otherwise remains
179 | in force. You may convey covered works to others for the sole purpose
180 | of having them make modifications exclusively for you, or provide you
181 | with facilities for running those works, provided that you comply with
182 | the terms of this License in conveying all material for which you do
183 | not control copyright. Those thus making or running the covered works
184 | for you must do so exclusively on your behalf, under your direction
185 | and control, on terms that prohibit them from making any copies of
186 | your copyrighted material outside their relationship with you.
187 |
188 | Conveying under any other circumstances is permitted solely under
189 | the conditions stated below. Sublicensing is not allowed; section 10
190 | makes it unnecessary.
191 |
192 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
193 |
194 | No covered work shall be deemed part of an effective technological
195 | measure under any applicable law fulfilling obligations under article
196 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
197 | similar laws prohibiting or restricting circumvention of such
198 | measures.
199 |
200 | When you convey a covered work, you waive any legal power to forbid
201 | circumvention of technological measures to the extent such circumvention
202 | is effected by exercising rights under this License with respect to
203 | the covered work, and you disclaim any intention to limit operation or
204 | modification of the work as a means of enforcing, against the work's
205 | users, your or third parties' legal rights to forbid circumvention of
206 | technological measures.
207 |
208 | 4. Conveying Verbatim Copies.
209 |
210 | You may convey verbatim copies of the Program's source code as you
211 | receive it, in any medium, provided that you conspicuously and
212 | appropriately publish on each copy an appropriate copyright notice;
213 | keep intact all notices stating that this License and any
214 | non-permissive terms added in accord with section 7 apply to the code;
215 | keep intact all notices of the absence of any warranty; and give all
216 | recipients a copy of this License along with the Program.
217 |
218 | You may charge any price or no price for each copy that you convey,
219 | and you may offer support or warranty protection for a fee.
220 |
221 | 5. Conveying Modified Source Versions.
222 |
223 | You may convey a work based on the Program, or the modifications to
224 | produce it from the Program, in the form of source code under the
225 | terms of section 4, provided that you also meet all of these conditions:
226 |
227 | a) The work must carry prominent notices stating that you modified
228 | it, and giving a relevant date.
229 |
230 | b) The work must carry prominent notices stating that it is
231 | released under this License and any conditions added under section
232 | 7. This requirement modifies the requirement in section 4 to
233 | "keep intact all notices".
234 |
235 | c) You must license the entire work, as a whole, under this
236 | License to anyone who comes into possession of a copy. This
237 | License will therefore apply, along with any applicable section 7
238 | additional terms, to the whole of the work, and all its parts,
239 | regardless of how they are packaged. This License gives no
240 | permission to license the work in any other way, but it does not
241 | invalidate such permission if you have separately received it.
242 |
243 | d) If the work has interactive user interfaces, each must display
244 | Appropriate Legal Notices; however, if the Program has interactive
245 | interfaces that do not display Appropriate Legal Notices, your
246 | work need not make them do so.
247 |
248 | A compilation of a covered work with other separate and independent
249 | works, which are not by their nature extensions of the covered work,
250 | and which are not combined with it such as to form a larger program,
251 | in or on a volume of a storage or distribution medium, is called an
252 | "aggregate" if the compilation and its resulting copyright are not
253 | used to limit the access or legal rights of the compilation's users
254 | beyond what the individual works permit. Inclusion of a covered work
255 | in an aggregate does not cause this License to apply to the other
256 | parts of the aggregate.
257 |
258 | 6. Conveying Non-Source Forms.
259 |
260 | You may convey a covered work in object code form under the terms
261 | of sections 4 and 5, provided that you also convey the
262 | machine-readable Corresponding Source under the terms of this License,
263 | in one of these ways:
264 |
265 | a) Convey the object code in, or embodied in, a physical product
266 | (including a physical distribution medium), accompanied by the
267 | Corresponding Source fixed on a durable physical medium
268 | customarily used for software interchange.
269 |
270 | b) Convey the object code in, or embodied in, a physical product
271 | (including a physical distribution medium), accompanied by a
272 | written offer, valid for at least three years and valid for as
273 | long as you offer spare parts or customer support for that product
274 | model, to give anyone who possesses the object code either (1) a
275 | copy of the Corresponding Source for all the software in the
276 | product that is covered by this License, on a durable physical
277 | medium customarily used for software interchange, for a price no
278 | more than your reasonable cost of physically performing this
279 | conveying of source, or (2) access to copy the
280 | Corresponding Source from a network server at no charge.
281 |
282 | c) Convey individual copies of the object code with a copy of the
283 | written offer to provide the Corresponding Source. This
284 | alternative is allowed only occasionally and noncommercially, and
285 | only if you received the object code with such an offer, in accord
286 | with subsection 6b.
287 |
288 | d) Convey the object code by offering access from a designated
289 | place (gratis or for a charge), and offer equivalent access to the
290 | Corresponding Source in the same way through the same place at no
291 | further charge. You need not require recipients to copy the
292 | Corresponding Source along with the object code. If the place to
293 | copy the object code is a network server, the Corresponding Source
294 | may be on a different server (operated by you or a third party)
295 | that supports equivalent copying facilities, provided you maintain
296 | clear directions next to the object code saying where to find the
297 | Corresponding Source. Regardless of what server hosts the
298 | Corresponding Source, you remain obligated to ensure that it is
299 | available for as long as needed to satisfy these requirements.
300 |
301 | e) Convey the object code using peer-to-peer transmission, provided
302 | you inform other peers where the object code and Corresponding
303 | Source of the work are being offered to the general public at no
304 | charge under subsection 6d.
305 |
306 | A separable portion of the object code, whose source code is excluded
307 | from the Corresponding Source as a System Library, need not be
308 | included in conveying the object code work.
309 |
310 | A "User Product" is either (1) a "consumer product", which means any
311 | tangible personal property which is normally used for personal, family,
312 | or household purposes, or (2) anything designed or sold for incorporation
313 | into a dwelling. In determining whether a product is a consumer product,
314 | doubtful cases shall be resolved in favor of coverage. For a particular
315 | product received by a particular user, "normally used" refers to a
316 | typical or common use of that class of product, regardless of the status
317 | of the particular user or of the way in which the particular user
318 | actually uses, or expects or is expected to use, the product. A product
319 | is a consumer product regardless of whether the product has substantial
320 | commercial, industrial or non-consumer uses, unless such uses represent
321 | the only significant mode of use of the product.
322 |
323 | "Installation Information" for a User Product means any methods,
324 | procedures, authorization keys, or other information required to install
325 | and execute modified versions of a covered work in that User Product from
326 | a modified version of its Corresponding Source. The information must
327 | suffice to ensure that the continued functioning of the modified object
328 | code is in no case prevented or interfered with solely because
329 | modification has been made.
330 |
331 | If you convey an object code work under this section in, or with, or
332 | specifically for use in, a User Product, and the conveying occurs as
333 | part of a transaction in which the right of possession and use of the
334 | User Product is transferred to the recipient in perpetuity or for a
335 | fixed term (regardless of how the transaction is characterized), the
336 | Corresponding Source conveyed under this section must be accompanied
337 | by the Installation Information. But this requirement does not apply
338 | if neither you nor any third party retains the ability to install
339 | modified object code on the User Product (for example, the work has
340 | been installed in ROM).
341 |
342 | The requirement to provide Installation Information does not include a
343 | requirement to continue to provide support service, warranty, or updates
344 | for a work that has been modified or installed by the recipient, or for
345 | the User Product in which it has been modified or installed. Access to a
346 | network may be denied when the modification itself materially and
347 | adversely affects the operation of the network or violates the rules and
348 | protocols for communication across the network.
349 |
350 | Corresponding Source conveyed, and Installation Information provided,
351 | in accord with this section must be in a format that is publicly
352 | documented (and with an implementation available to the public in
353 | source code form), and must require no special password or key for
354 | unpacking, reading or copying.
355 |
356 | 7. Additional Terms.
357 |
358 | "Additional permissions" are terms that supplement the terms of this
359 | License by making exceptions from one or more of its conditions.
360 | Additional permissions that are applicable to the entire Program shall
361 | be treated as though they were included in this License, to the extent
362 | that they are valid under applicable law. If additional permissions
363 | apply only to part of the Program, that part may be used separately
364 | under those permissions, but the entire Program remains governed by
365 | this License without regard to the additional permissions.
366 |
367 | When you convey a copy of a covered work, you may at your option
368 | remove any additional permissions from that copy, or from any part of
369 | it. (Additional permissions may be written to require their own
370 | removal in certain cases when you modify the work.) You may place
371 | additional permissions on material, added by you to a covered work,
372 | for which you have or can give appropriate copyright permission.
373 |
374 | Notwithstanding any other provision of this License, for material you
375 | add to a covered work, you may (if authorized by the copyright holders of
376 | that material) supplement the terms of this License with terms:
377 |
378 | a) Disclaiming warranty or limiting liability differently from the
379 | terms of sections 15 and 16 of this License; or
380 |
381 | b) Requiring preservation of specified reasonable legal notices or
382 | author attributions in that material or in the Appropriate Legal
383 | Notices displayed by works containing it; or
384 |
385 | c) Prohibiting misrepresentation of the origin of that material, or
386 | requiring that modified versions of such material be marked in
387 | reasonable ways as different from the original version; or
388 |
389 | d) Limiting the use for publicity purposes of names of licensors or
390 | authors of the material; or
391 |
392 | e) Declining to grant rights under trademark law for use of some
393 | trade names, trademarks, or service marks; or
394 |
395 | f) Requiring indemnification of licensors and authors of that
396 | material by anyone who conveys the material (or modified versions of
397 | it) with contractual assumptions of liability to the recipient, for
398 | any liability that these contractual assumptions directly impose on
399 | those licensors and authors.
400 |
401 | All other non-permissive additional terms are considered "further
402 | restrictions" within the meaning of section 10. If the Program as you
403 | received it, or any part of it, contains a notice stating that it is
404 | governed by this License along with a term that is a further
405 | restriction, you may remove that term. If a license document contains
406 | a further restriction but permits relicensing or conveying under this
407 | License, you may add to a covered work material governed by the terms
408 | of that license document, provided that the further restriction does
409 | not survive such relicensing or conveying.
410 |
411 | If you add terms to a covered work in accord with this section, you
412 | must place, in the relevant source files, a statement of the
413 | additional terms that apply to those files, or a notice indicating
414 | where to find the applicable terms.
415 |
416 | Additional terms, permissive or non-permissive, may be stated in the
417 | form of a separately written license, or stated as exceptions;
418 | the above requirements apply either way.
419 |
420 | 8. Termination.
421 |
422 | You may not propagate or modify a covered work except as expressly
423 | provided under this License. Any attempt otherwise to propagate or
424 | modify it is void, and will automatically terminate your rights under
425 | this License (including any patent licenses granted under the third
426 | paragraph of section 11).
427 |
428 | However, if you cease all violation of this License, then your
429 | license from a particular copyright holder is reinstated (a)
430 | provisionally, unless and until the copyright holder explicitly and
431 | finally terminates your license, and (b) permanently, if the copyright
432 | holder fails to notify you of the violation by some reasonable means
433 | prior to 60 days after the cessation.
434 |
435 | Moreover, your license from a particular copyright holder is
436 | reinstated permanently if the copyright holder notifies you of the
437 | violation by some reasonable means, this is the first time you have
438 | received notice of violation of this License (for any work) from that
439 | copyright holder, and you cure the violation prior to 30 days after
440 | your receipt of the notice.
441 |
442 | Termination of your rights under this section does not terminate the
443 | licenses of parties who have received copies or rights from you under
444 | this License. If your rights have been terminated and not permanently
445 | reinstated, you do not qualify to receive new licenses for the same
446 | material under section 10.
447 |
448 | 9. Acceptance Not Required for Having Copies.
449 |
450 | You are not required to accept this License in order to receive or
451 | run a copy of the Program. Ancillary propagation of a covered work
452 | occurring solely as a consequence of using peer-to-peer transmission
453 | to receive a copy likewise does not require acceptance. However,
454 | nothing other than this License grants you permission to propagate or
455 | modify any covered work. These actions infringe copyright if you do
456 | not accept this License. Therefore, by modifying or propagating a
457 | covered work, you indicate your acceptance of this License to do so.
458 |
459 | 10. Automatic Licensing of Downstream Recipients.
460 |
461 | Each time you convey a covered work, the recipient automatically
462 | receives a license from the original licensors, to run, modify and
463 | propagate that work, subject to this License. You are not responsible
464 | for enforcing compliance by third parties with this License.
465 |
466 | An "entity transaction" is a transaction transferring control of an
467 | organization, or substantially all assets of one, or subdividing an
468 | organization, or merging organizations. If propagation of a covered
469 | work results from an entity transaction, each party to that
470 | transaction who receives a copy of the work also receives whatever
471 | licenses to the work the party's predecessor in interest had or could
472 | give under the previous paragraph, plus a right to possession of the
473 | Corresponding Source of the work from the predecessor in interest, if
474 | the predecessor has it or can get it with reasonable efforts.
475 |
476 | You may not impose any further restrictions on the exercise of the
477 | rights granted or affirmed under this License. For example, you may
478 | not impose a license fee, royalty, or other charge for exercise of
479 | rights granted under this License, and you may not initiate litigation
480 | (including a cross-claim or counterclaim in a lawsuit) alleging that
481 | any patent claim is infringed by making, using, selling, offering for
482 | sale, or importing the Program or any portion of it.
483 |
484 | 11. Patents.
485 |
486 | A "contributor" is a copyright holder who authorizes use under this
487 | License of the Program or a work on which the Program is based. The
488 | work thus licensed is called the contributor's "contributor version".
489 |
490 | A contributor's "essential patent claims" are all patent claims
491 | owned or controlled by the contributor, whether already acquired or
492 | hereafter acquired, that would be infringed by some manner, permitted
493 | by this License, of making, using, or selling its contributor version,
494 | but do not include claims that would be infringed only as a
495 | consequence of further modification of the contributor version. For
496 | purposes of this definition, "control" includes the right to grant
497 | patent sublicenses in a manner consistent with the requirements of
498 | this License.
499 |
500 | Each contributor grants you a non-exclusive, worldwide, royalty-free
501 | patent license under the contributor's essential patent claims, to
502 | make, use, sell, offer for sale, import and otherwise run, modify and
503 | propagate the contents of its contributor version.
504 |
505 | In the following three paragraphs, a "patent license" is any express
506 | agreement or commitment, however denominated, not to enforce a patent
507 | (such as an express permission to practice a patent or covenant not to
508 | sue for patent infringement). To "grant" such a patent license to a
509 | party means to make such an agreement or commitment not to enforce a
510 | patent against the party.
511 |
512 | If you convey a covered work, knowingly relying on a patent license,
513 | and the Corresponding Source of the work is not available for anyone
514 | to copy, free of charge and under the terms of this License, through a
515 | publicly available network server or other readily accessible means,
516 | then you must either (1) cause the Corresponding Source to be so
517 | available, or (2) arrange to deprive yourself of the benefit of the
518 | patent license for this particular work, or (3) arrange, in a manner
519 | consistent with the requirements of this License, to extend the patent
520 | license to downstream recipients. "Knowingly relying" means you have
521 | actual knowledge that, but for the patent license, your conveying the
522 | covered work in a country, or your recipient's use of the covered work
523 | in a country, would infringe one or more identifiable patents in that
524 | country that you have reason to believe are valid.
525 |
526 | If, pursuant to or in connection with a single transaction or
527 | arrangement, you convey, or propagate by procuring conveyance of, a
528 | covered work, and grant a patent license to some of the parties
529 | receiving the covered work authorizing them to use, propagate, modify
530 | or convey a specific copy of the covered work, then the patent license
531 | you grant is automatically extended to all recipients of the covered
532 | work and works based on it.
533 |
534 | A patent license is "discriminatory" if it does not include within
535 | the scope of its coverage, prohibits the exercise of, or is
536 | conditioned on the non-exercise of one or more of the rights that are
537 | specifically granted under this License. You may not convey a covered
538 | work if you are a party to an arrangement with a third party that is
539 | in the business of distributing software, under which you make payment
540 | to the third party based on the extent of your activity of conveying
541 | the work, and under which the third party grants, to any of the
542 | parties who would receive the covered work from you, a discriminatory
543 | patent license (a) in connection with copies of the covered work
544 | conveyed by you (or copies made from those copies), or (b) primarily
545 | for and in connection with specific products or compilations that
546 | contain the covered work, unless you entered into that arrangement,
547 | or that patent license was granted, prior to 28 March 2007.
548 |
549 | Nothing in this License shall be construed as excluding or limiting
550 | any implied license or other defenses to infringement that may
551 | otherwise be available to you under applicable patent law.
552 |
553 | 12. No Surrender of Others' Freedom.
554 |
555 | If conditions are imposed on you (whether by court order, agreement or
556 | otherwise) that contradict the conditions of this License, they do not
557 | excuse you from the conditions of this License. If you cannot convey a
558 | covered work so as to satisfy simultaneously your obligations under this
559 | License and any other pertinent obligations, then as a consequence you may
560 | not convey it at all. For example, if you agree to terms that obligate you
561 | to collect a royalty for further conveying from those to whom you convey
562 | the Program, the only way you could satisfy both those terms and this
563 | License would be to refrain entirely from conveying the Program.
564 |
565 | 13. Use with the GNU Affero General Public License.
566 |
567 | Notwithstanding any other provision of this License, you have
568 | permission to link or combine any covered work with a work licensed
569 | under version 3 of the GNU Affero General Public License into a single
570 | combined work, and to convey the resulting work. The terms of this
571 | License will continue to apply to the part which is the covered work,
572 | but the special requirements of the GNU Affero General Public License,
573 | section 13, concerning interaction through a network will apply to the
574 | combination as such.
575 |
576 | 14. Revised Versions of this License.
577 |
578 | The Free Software Foundation may publish revised and/or new versions of
579 | the GNU General Public License from time to time. Such new versions will
580 | be similar in spirit to the present version, but may differ in detail to
581 | address new problems or concerns.
582 |
583 | Each version is given a distinguishing version number. If the
584 | Program specifies that a certain numbered version of the GNU General
585 | Public License "or any later version" applies to it, you have the
586 | option of following the terms and conditions either of that numbered
587 | version or of any later version published by the Free Software
588 | Foundation. If the Program does not specify a version number of the
589 | GNU General Public License, you may choose any version ever published
590 | by the Free Software Foundation.
591 |
592 | If the Program specifies that a proxy can decide which future
593 | versions of the GNU General Public License can be used, that proxy's
594 | public statement of acceptance of a version permanently authorizes you
595 | to choose that version for the Program.
596 |
597 | Later license versions may give you additional or different
598 | permissions. However, no additional obligations are imposed on any
599 | author or copyright holder as a result of your choosing to follow a
600 | later version.
601 |
602 | 15. Disclaimer of Warranty.
603 |
604 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
605 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
606 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
607 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
608 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
609 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
610 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
611 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
612 |
613 | 16. Limitation of Liability.
614 |
615 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
616 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
617 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
618 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
619 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
620 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
621 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
622 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
623 | SUCH DAMAGES.
624 |
625 | 17. Interpretation of Sections 15 and 16.
626 |
627 | If the disclaimer of warranty and limitation of liability provided
628 | above cannot be given local legal effect according to their terms,
629 | reviewing courts shall apply local law that most closely approximates
630 | an absolute waiver of all civil liability in connection with the
631 | Program, unless a warranty or assumption of liability accompanies a
632 | copy of the Program in return for a fee.
633 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PDF Parser
2 | PDF Parser is a command line tool and go library that decrypts PDF files and extracts commands, files, javascript, text and urls. PDF Parser also logs formatting errors and abnormalities that are used to obfuscate malicious PDF files.
3 |
4 | ## Installation
5 | First, [Install Go](https://golang.org/doc/install#install)
6 |
7 | Then install/update the PDF Parser
8 | ```bash
9 | go get -u github.com/KarmaPenny/pdfparser
10 | ```
11 |
12 | #### To uninstall the PDF parser run:
13 | ```bash
14 | go clean -i github.com/KarmaPenny/pdfparser && rm -rf $(go env GOPATH)/src/github.com/KarmaPenny/pdfparser
15 | ```
16 |
17 | #### Run unit tests with:
18 | ```bash
19 | go test github.com/KarmaPenny/pdfparser/pdf
20 | ```
21 |
22 | ## Usage
23 | #### Command Line
24 | The following command extracts the contents of input.pdf to the output directory using "password" for decryption:
25 | ```bash
26 | $(go env GOPATH)/bin/pdfparser -p password input.pdf output/
27 | ```
28 |
29 | #### Library
30 | The following program extracts the contents of input.pdf to the output directory using "password" for decryption:
31 | ```go
32 | package main
33 |
34 | import "github.com/KarmaPenny/pdfparser/pdf"
35 |
36 | func main() {
37 | pdf.Parse("input.pdf", "password", "output")
38 | }
39 | ```
40 |
41 | ## Output
42 | PDF parser creates the following files in the output directory:
43 |
44 | #### commands.txt
45 | Commands run by launch actions are logged to the commands.txt file. Example:
46 | ```
47 | cmd.exe /c hello.exe
48 | calc.exe
49 | ```
50 |
51 | #### contents.txt
52 | The text content of the PDF is written to the contents.txt file.
53 |
54 | #### errors.txt
55 | Format errors and other abnormailites that are sometimes used to obfuscate malicious PDF files are logged to the errors.txt file. Bellow is an example errors.txt file containing the complete list of possible log messages:
56 | ```
57 | invalid dictionary key type
58 | invalid hex string character
59 | invalid name escape character
60 | invalid octal in string
61 | missing dictionary value
62 | unclosed array
63 | unclosed dictionary
64 | unclosed hex string
65 | unclosed stream
66 | unclosed string
67 | unclosed escape in string
68 | unclosed octal in string
69 | unnecessary espace sequence in name
70 | unnecessary espace sequence in string
71 | ```
72 | #### files.txt
73 | The MD5 hash and file path of referenced embedded and external files are logged to the files.txt file. Embedded files are extracted to the output directory using the MD5 hash as the file name. The MD5 hash for external files is all zeros. Example:
74 | ```
75 | 6adb6f85e541f14d7ecec12a6af8ef65:hello.exe
76 | 00000000000000000000000000000000:C:\Windows\System32\calc.exe
77 | ```
78 |
79 | #### javascript.js
80 | The javascript of all actions is extracted to the javascript.js file.
81 |
82 | #### raw.pdf
83 | A decrypted and decoded version of the PDF is written to the raw.pdf file.
84 |
85 | #### urls.txt
86 | All URLs referenced by actions are extracted to the urls.txt file. Example:
87 | ```
88 | http://www.google.com
89 | https://github.com/KarmaPenny
90 | ```
91 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "github.com/KarmaPenny/pdfparser/pdf"
7 | "os"
8 | )
9 |
10 | var overwrite *bool
11 | var password *string
12 |
13 | func usage() {
14 | fmt.Fprintln(os.Stderr, "PDF Parser - Decrypts a PDF file and extracts contents")
15 | fmt.Fprintln(os.Stderr, "")
16 | fmt.Fprintln(os.Stderr, "")
17 | fmt.Fprintln(os.Stderr, "Usage: pdfparser [OPTION]... [FILE] [DIRECTORY]")
18 | fmt.Fprintln(os.Stderr, "Example: pdfparser -v -f -p password input.pdf output/")
19 | fmt.Fprintln(os.Stderr, "")
20 | fmt.Fprintln(os.Stderr, "Options:")
21 | fmt.Fprintln(os.Stderr, " -f overwrite output directory")
22 | fmt.Fprintln(os.Stderr, " -p decryption password")
23 | fmt.Fprintln(os.Stderr, " -v display verbose messages")
24 | fmt.Fprintln(os.Stderr, "")
25 | fmt.Fprintln(os.Stderr, "Copyright (C) 2019 Cole Robinette")
26 | fmt.Fprintln(os.Stderr, "This program is free to use, redistribute, and modify under")
27 | fmt.Fprintln(os.Stderr, "the terms of the GNU General Public License version 3. This")
28 | fmt.Fprintln(os.Stderr, "program is distributed without any warranty.")
29 | fmt.Fprintln(os.Stderr, "")
30 | }
31 |
32 | func init() {
33 | overwrite = flag.Bool("f", false, "overwrite of output directory if it already exists")
34 | password = flag.String("p", "", "encryption password (default: empty)")
35 | pdf.Verbose = flag.Bool("v", false, "display verbose messages")
36 | flag.Usage = usage
37 | flag.Parse()
38 | if flag.NArg() != 2 {
39 | usage()
40 | os.Exit(1)
41 | }
42 | }
43 |
44 | func main() {
45 | // check if output directory already exists
46 | if _, err := os.Stat(flag.Arg(1)); !os.IsNotExist(err) && !*overwrite {
47 | fmt.Printf("output directory \"%s\" already exists, use -f to overwrite\n", flag.Arg(1))
48 | return
49 | }
50 |
51 | // parse the pdf
52 | if err := pdf.Parse(flag.Arg(0), *password, flag.Arg(1)); err != nil {
53 | fmt.Fprintln(os.Stderr, err.Error())
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/pdf/action.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Action Dictionary
8 |
9 | func (a Action) Extract(output *Output) {
10 | d := Dictionary(a)
11 |
12 | isCommand := false
13 | if s, ok := d.GetName("S"); ok && s == "Launch" {
14 | isCommand = true
15 | }
16 |
17 | // filespecification can be in either F or Win[F]
18 | if f, ok := d.GetString("F"); ok {
19 | fmt.Fprintf(output.Files, "%s:%s\n", unknownHash, f)
20 | } else if f, ok := d.GetDictionary("F"); ok {
21 | File(f).Extract(output, isCommand)
22 | }
23 | if win, ok := d.GetDictionary("Win"); ok {
24 | File(win).Extract(output, isCommand)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/pdf/array.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "strings"
5 | )
6 |
7 | type Array []Object
8 |
9 | func (a Array) String() string {
10 | var s strings.Builder
11 | s.WriteString("[")
12 | for i, value := range a {
13 | s.WriteString(value.String())
14 | if i != len(a) - 1 {
15 | s.WriteString(" ")
16 | }
17 | }
18 | s.WriteString("]")
19 | return s.String()
20 | }
21 |
22 | func (a Array) GetArray(index int) (Array, bool) {
23 | if object, ok := a.GetObject(index); ok {
24 | if array, ok := object.(Array); ok {
25 | return array, true
26 | }
27 | }
28 | return Array{}, false
29 | }
30 |
31 | func (a Array) GetBool(index int) (bool, bool) {
32 | if object, ok := a.GetObject(index); ok {
33 | if keyword, ok := object.(Keyword); ok {
34 | if keyword == KEYWORD_TRUE {
35 | return true, true
36 | } else if keyword == KEYWORD_FALSE {
37 | return false, true
38 | }
39 | }
40 | }
41 | return false, false
42 | }
43 |
44 | func (a Array) GetBytes(index int) ([]byte, bool) {
45 | s, ok := a.GetString(index)
46 | return []byte(s), ok
47 | }
48 |
49 | func (a Array) GetDictionary(index int) (Dictionary, bool) {
50 | if object, ok := a.GetObject(index); ok {
51 | if dictionary, ok := object.(Dictionary); ok {
52 | return dictionary, true
53 | }
54 | }
55 | return Dictionary{}, false
56 | }
57 |
58 | func (a Array) GetInt(index int) (int, bool) {
59 | number, ok := a.GetNumber(index)
60 | return int(number), ok
61 | }
62 |
63 | func (a Array) GetInt64(index int) (int64, bool) {
64 | number, ok := a.GetNumber(index)
65 | return int64(number), ok
66 | }
67 |
68 | func (a Array) GetName(index int) (string, bool) {
69 | if object, ok := a.GetObject(index); ok {
70 | if name, ok := object.(Name); ok {
71 | return string(name), true
72 | }
73 | }
74 | return "", false
75 | }
76 |
77 | func (a Array) GetNumber(index int) (Number, bool) {
78 | if object, ok := a.GetObject(index); ok {
79 | if number, ok := object.(Number); ok {
80 | return number, true
81 | }
82 | }
83 | return Number(0), false
84 | }
85 |
86 | func (a Array) GetObject(index int) (Object, bool) {
87 | if index >= 0 && index < len(a) {
88 | object := a[index]
89 | if reference, ok := object.(*Reference); ok {
90 | return reference.Resolve(), true
91 | }
92 | return object, true
93 | }
94 | return KEYWORD_NULL, false
95 | }
96 |
97 | func (a Array) GetStream(index int) ([]byte, bool) {
98 | if index >= 0 && index < len(a) {
99 | if reference, ok := a[index].(*Reference); ok {
100 | return reference.ResolveStream(), true
101 | }
102 | }
103 | return []byte{}, false
104 | }
105 |
106 | func (a Array) GetString(index int) (string, bool) {
107 | if object, ok := a.GetObject(index); ok {
108 | if s, ok := object.(String); ok {
109 | return string(s), true
110 | }
111 | }
112 | return "", false
113 | }
114 |
--------------------------------------------------------------------------------
/pdf/dictionary.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "strings"
5 | )
6 |
7 | type Dictionary map[string]Object
8 |
9 | func (d Dictionary) String() string {
10 | var s strings.Builder
11 | s.WriteString("<<")
12 | for key, value := range d {
13 | s.WriteString("/")
14 | s.WriteString(key)
15 | s.WriteString(" ")
16 | s.WriteString(value.String())
17 | }
18 | s.WriteString(">>")
19 | return s.String()
20 | }
21 |
22 | func (d Dictionary) GetArray(key string) (Array, bool) {
23 | if object, ok := d.GetObject(key); ok {
24 | if array, ok := object.(Array); ok {
25 | return array, true
26 | }
27 | }
28 | return Array{}, false
29 | }
30 |
31 | func (d Dictionary) GetBool(key string) (bool, bool) {
32 | if object, ok := d.GetObject(key); ok {
33 | if keyword, ok := object.(Keyword); ok {
34 | if keyword == KEYWORD_TRUE {
35 | return true, true
36 | } else if keyword == KEYWORD_FALSE {
37 | return false, true
38 | }
39 | }
40 | }
41 | return false, false
42 | }
43 |
44 | func (d Dictionary) GetBytes(key string) ([]byte, bool) {
45 | s, ok := d.GetString(key)
46 | return []byte(s), ok
47 | }
48 |
49 | func (d Dictionary) GetDictionary(key string) (Dictionary, bool) {
50 | if object, ok := d.GetObject(key); ok {
51 | if dictionary, ok := object.(Dictionary); ok {
52 | return dictionary, true
53 | }
54 | }
55 | return Dictionary{}, false
56 | }
57 |
58 | func (d Dictionary) GetInt(key string) (int, bool) {
59 | number, ok := d.GetNumber(key)
60 | return int(number), ok
61 | }
62 |
63 | func (d Dictionary) GetInt64(key string) (int64, bool) {
64 | number, ok := d.GetNumber(key)
65 | return int64(number), ok
66 | }
67 |
68 | func (d Dictionary) GetName(key string) (string, bool) {
69 | if object, ok := d.GetObject(key); ok {
70 | if name, ok := object.(Name); ok {
71 | return string(name), true
72 | }
73 | }
74 | return "", false
75 | }
76 |
77 | func (d Dictionary) GetNameTreeMap(key string) Array {
78 | if root, ok := d.GetDictionary(key); ok {
79 | return root.getNameTreeMap(map[int]interface{}{})
80 | }
81 | return Array{}
82 | }
83 |
84 | func (d Dictionary) getNameTreeMap(resolved_kids map[int]interface{}) Array {
85 | nameTreeMap := Array{}
86 | if names, ok := d.GetArray("Names"); ok {
87 | // append names to name tree map
88 | nameTreeMap = append(nameTreeMap, names...)
89 | }
90 | if kids, ok := d.GetArray("Kids"); ok {
91 | for i := range kids {
92 | // prevent infinite resolve reference loop
93 | if r, ok := kids[i].(*Reference); ok {
94 | if _, resolved := resolved_kids[r.Number]; resolved {
95 | continue
96 | }
97 | resolved_kids[r.Number] = nil
98 | }
99 |
100 | // get child dictionary
101 | kid, _ := kids.GetDictionary(i)
102 | nameTreeMap = append(nameTreeMap, kid.getNameTreeMap(resolved_kids)...)
103 | }
104 | }
105 | return nameTreeMap
106 | }
107 |
108 | func (d Dictionary) GetNumber(key string) (Number, bool) {
109 | if object, ok := d.GetObject(key); ok {
110 | if number, ok := object.(Number); ok {
111 | return number, true
112 | }
113 | }
114 | return Number(0), false
115 | }
116 |
117 | func (d Dictionary) GetObject(key string) (Object, bool) {
118 | if object, ok := d[key]; ok {
119 | if reference, ok := object.(*Reference); ok {
120 | return reference.Resolve(), true
121 | }
122 | return object, true
123 | }
124 | return KEYWORD_NULL, false
125 | }
126 |
127 | func (d Dictionary) GetPageTree(key string) ([]Dictionary, bool) {
128 | if pageTree, ok := d.GetDictionary(key); ok {
129 | return pageTree.ResolveKids(map[int]interface{}{}), true
130 | }
131 | return []Dictionary{}, false
132 | }
133 |
134 | func (d Dictionary) ResolveKids(resolved_kids map[int]interface{}) []Dictionary {
135 | kids_list := []Dictionary{d}
136 | if kids, ok := d.GetArray("Kids"); ok {
137 | for i := range kids {
138 | if r, ok := kids[i].(*Reference); ok {
139 | // ignore circular references
140 | if _, resolved := resolved_kids[r.Number]; resolved {
141 | continue
142 | }
143 | resolved_kids[r.Number] = nil
144 |
145 | // resolve
146 | object := r.Resolve()
147 | if kid_d, ok := object.(Dictionary); ok {
148 | // recursively resolve kids
149 | kids_list = append(kids_list, kid_d.ResolveKids(resolved_kids)...)
150 | }
151 | }
152 | }
153 | }
154 | return kids_list
155 | }
156 |
157 | func (d Dictionary) GetReference(key string) (*Reference, bool) {
158 | if object, ok := d[key]; ok {
159 | if reference, ok := object.(*Reference); ok {
160 | return reference, true
161 | }
162 | }
163 | return nil, false
164 | }
165 |
166 | func (d Dictionary) GetStream(key string) ([]byte, bool) {
167 | if object, ok := d[key]; ok {
168 | if reference, ok := object.(*Reference); ok {
169 | return reference.ResolveStream(), true
170 | }
171 | }
172 | return []byte{}, false
173 | }
174 |
175 | func (d Dictionary) GetString(key string) (string, bool) {
176 | if object, ok := d.GetObject(key); ok {
177 | if s, ok := object.(String); ok {
178 | return string(s), true
179 | }
180 | }
181 | return "", false
182 | }
183 |
--------------------------------------------------------------------------------
/pdf/encryption.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "crypto/md5"
7 | "crypto/rc4"
8 | "encoding/binary"
9 | )
10 |
11 | var padding_string []byte = []byte("\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A")
12 | var noFilter = &CryptFilterNone{}
13 | var noDecryptor = &DecryptorNone{}
14 | type CryptFilter interface {
15 | NewDecryptor(int, int) Decryptor
16 | }
17 |
18 | type Decryptor interface {
19 | Decrypt([]byte)
20 | }
21 |
22 | // No encryption
23 | type CryptFilterNone struct {}
24 |
25 | func (c *CryptFilterNone) NewDecryptor(n int, g int) Decryptor {
26 | return &DecryptorNone{}
27 | }
28 |
29 | type DecryptorNone struct {}
30 |
31 | func (d *DecryptorNone) Decrypt(data []byte) {}
32 |
33 | // AES
34 | type CryptFilterAES struct {
35 | encryption_key []byte
36 | }
37 |
38 | func (c *CryptFilterAES) NewDecryptor(n int, g int) Decryptor {
39 | // allocate space for salt and copy encryption key into it
40 | salt := make([]byte, len(c.encryption_key), len(c.encryption_key) + 9)
41 | copy(salt, c.encryption_key)
42 |
43 | // get n as byte little endian byte array, add first 3 bytes to salt
44 | nb := make([]byte, 4)
45 | binary.LittleEndian.PutUint32(nb, uint32(n))
46 | salt = append(salt, nb[:3]...)
47 |
48 | // get g as byte little endian byte array, add first 2 bytes to salt
49 | gb := make([]byte, 4)
50 | binary.LittleEndian.PutUint32(gb, uint32(g))
51 | salt = append(salt, gb[:2]...)
52 |
53 | // add sAlT to key
54 | salt = append(salt, []byte("sAlT")...)
55 |
56 | // hash the salt to produce the key
57 | hash := md5.New()
58 | hash.Write(salt)
59 | key := hash.Sum(nil)
60 |
61 | // trucate key to length + 5 max 16
62 | l := len(c.encryption_key) + 5
63 | if l > 16 {
64 | l = 16
65 | }
66 | key = key[:l]
67 |
68 | // return new crypt filter with salted key
69 | return &DecryptorAES{key}
70 | }
71 |
72 | type DecryptorAES struct {
73 | encryption_key []byte
74 | }
75 |
76 | func (d *DecryptorAES) Decrypt(data []byte) {
77 | // catch crypt block panic
78 | defer func() {
79 | if err := recover(); err != nil {
80 | Debug("recovered from panic: %s", err)
81 | }
82 | }()
83 |
84 | // create new cipher
85 | block, _ := aes.NewCipher(d.encryption_key)
86 |
87 | // no data to decrypt, first block is initialization vector
88 | if len(data) <= aes.BlockSize {
89 | return
90 | }
91 |
92 | // set iv to first block and decrypt remaining blocks with cbc decryptor
93 | iv := data[:aes.BlockSize]
94 | data = data[aes.BlockSize:]
95 | cbc := cipher.NewCBCDecrypter(block, iv)
96 | cbc.CryptBlocks(data, data)
97 | }
98 |
99 | // RC4
100 | type CryptFilterRC4 struct {
101 | encryption_key []byte
102 | }
103 |
104 | func (c *CryptFilterRC4) NewDecryptor(n int, g int) Decryptor {
105 | // allocate space for salt and copy encryption key into it
106 | salt := make([]byte, len(c.encryption_key), len(c.encryption_key) + 5)
107 | copy(salt, c.encryption_key)
108 |
109 | // get n as byte little endian byte array, add first 3 bytes to salt
110 | nb := make([]byte, 4)
111 | binary.LittleEndian.PutUint32(nb, uint32(n))
112 | salt = append(salt, nb[:3]...)
113 |
114 | // get g as byte little endian byte array, add first 2 bytes to salt
115 | gb := make([]byte, 4)
116 | binary.LittleEndian.PutUint32(gb, uint32(g))
117 | salt = append(salt, gb[:2]...)
118 |
119 | // hash the salt to produce the key
120 | hash := md5.New()
121 | hash.Write(salt)
122 | key := hash.Sum(nil)
123 |
124 | // trucate key to length + 5 max 16
125 | l := len(c.encryption_key) + 5
126 | if l > 16 {
127 | l = 16
128 | }
129 | key = key[:l]
130 |
131 | // return new crypt filter with salted key
132 | return &DecryptorRC4{key}
133 | }
134 |
135 | type DecryptorRC4 struct {
136 | encryption_key []byte
137 | }
138 |
139 | func (d *DecryptorRC4) Decrypt(data []byte) {
140 | cipher, _ := rc4.NewCipher(d.encryption_key)
141 | cipher.XORKeyStream(data, data)
142 | }
143 |
144 | type SecurityHandler struct {
145 | v int
146 | length int
147 | r int
148 | o []byte
149 | u []byte
150 | p []byte
151 | encrypt_meta_data bool
152 | id []byte
153 | stream_filter CryptFilter
154 | string_filter CryptFilter
155 | file_filter CryptFilter
156 | crypt_filters map[string]CryptFilter
157 | encryption_key []byte
158 | }
159 |
160 | func NewSecurityHandler() *SecurityHandler {
161 | sh := &SecurityHandler{}
162 | sh.stream_filter = noFilter
163 | sh.string_filter = noFilter
164 | sh.file_filter = noFilter
165 | sh.crypt_filters = map[string]CryptFilter{}
166 | return sh
167 | }
168 |
169 | func (sh *SecurityHandler) Init(password []byte, trailer Dictionary) error {
170 | var ok bool = false
171 |
172 | // get encryption dictionary
173 | encrypt, ok := trailer.GetDictionary("Encrypt")
174 | if !ok {
175 | return EncryptionError
176 | }
177 |
178 | // get filter
179 | filter, _ := encrypt.GetName("Filter")
180 | if filter != "Standard" {
181 | return EncryptionUnsupported
182 | }
183 |
184 | // get V
185 | sh.v, _ = encrypt.GetInt("V")
186 | if sh.v != 1 && sh.v != 2 && sh.v != 4 {
187 | return EncryptionUnsupported
188 | }
189 |
190 | // get R
191 | sh.r, _ = encrypt.GetInt("R")
192 | if sh.r < 2 || sh.r > 4 {
193 | return EncryptionUnsupported
194 | }
195 |
196 | // get Length
197 | if sh.v == 1 {
198 | sh.length = 40
199 | } else {
200 | sh.length, ok = encrypt.GetInt("Length")
201 | if !ok {
202 | sh.length = 40
203 | }
204 | }
205 | sh.length = sh.length/8
206 | if sh.length < 5 {
207 | sh.length = 5
208 | } else if sh.length > 16 {
209 | sh.length = 16
210 | }
211 |
212 | // get O
213 | sh.o, ok = encrypt.GetBytes("O")
214 | if !ok {
215 | return EncryptionError
216 | }
217 |
218 | // get U
219 | sh.u, ok = encrypt.GetBytes("U")
220 | if !ok {
221 | return EncryptionError
222 | }
223 |
224 | // get P
225 | p, ok := encrypt.GetInt("P")
226 | if !ok {
227 | return EncryptionError
228 | }
229 | sh.p = make([]byte, 4)
230 | binary.LittleEndian.PutUint32(sh.p, uint32(p))
231 |
232 | // get EncryptMetadata
233 | sh.encrypt_meta_data, ok = encrypt.GetBool("EncryptMetadata")
234 | if !ok {
235 | sh.encrypt_meta_data = true
236 | }
237 |
238 | // get ID[0] from trailer
239 | ids, ok := trailer.GetArray("ID")
240 | if !ok {
241 | return EncryptionError
242 | }
243 | sh.id, ok = ids.GetBytes(0)
244 | if !ok {
245 | return EncryptionError
246 | }
247 |
248 | // compute encryption key from password
249 | sh.encryption_key = sh.computeEncryptionKey(password, sh.length)
250 |
251 | // verify key
252 | if sh.r == 2 { // if revision 2 use algorithm 4
253 | u := make([]byte, 32)
254 | cipher, _ := rc4.NewCipher(sh.encryption_key)
255 | cipher.XORKeyStream(u, padding_string)
256 | if string(u) != string(sh.u) {
257 | return EncryptionPasswordError
258 | }
259 | } else if sh.r >= 3 { // for revision 3+ use algorithm 5
260 | // step b, c
261 | hash := md5.New()
262 | hash.Write(padding_string)
263 | hash.Write(sh.id)
264 | u := hash.Sum(nil)
265 |
266 | // step d, e
267 | temp_key := make([]byte, len(sh.encryption_key))
268 | for i := 0; i < 20; i++ {
269 | for j := range sh.encryption_key {
270 | temp_key[j] = sh.encryption_key[j] ^ byte(i)
271 | }
272 | cipher, _ := rc4.NewCipher(temp_key)
273 | cipher.XORKeyStream(u, u)
274 | }
275 |
276 | // compare to first 16 bytes of U entry
277 | if string(u) != string(sh.u[:16]) {
278 | return EncryptionPasswordError
279 | }
280 | }
281 |
282 | // set default crypt filters
283 | sh.stream_filter = &CryptFilterRC4{sh.encryption_key}
284 | sh.string_filter = sh.stream_filter
285 | sh.file_filter = sh.stream_filter
286 | sh.crypt_filters = map[string]CryptFilter{}
287 | sh.crypt_filters["Identity"] = noFilter
288 |
289 | // load additional crypt filters
290 | if sh.r == 4 {
291 | cf, _ := encrypt.GetDictionary("CF")
292 | for k, entry := range cf {
293 | if cfd, isDictionary := entry.(Dictionary); isDictionary {
294 | if method, ok := cfd.GetName("CFM"); ok {
295 | // get optional length
296 | length, ok := cfd.GetInt("Length")
297 | if !ok {
298 | length = sh.length
299 | }
300 |
301 | // create filter entry
302 | if method == "None" {
303 | sh.crypt_filters[k] = noFilter
304 | } else if method == "V2" {
305 | sh.crypt_filters[k] = &CryptFilterRC4{sh.computeEncryptionKey(password, length)}
306 | } else if method == "AESV2" {
307 | sh.crypt_filters[k] = &CryptFilterAES{sh.computeEncryptionKey(password, length)}
308 | }
309 | }
310 | }
311 | }
312 |
313 | // assign default filter overrides
314 | if name, ok := encrypt.GetName("StmF"); ok {
315 | if filter, exists := sh.crypt_filters[name]; exists {
316 | sh.stream_filter = filter
317 | }
318 | }
319 | if name, ok := encrypt.GetName("StrF"); ok {
320 | if filter, exists := sh.crypt_filters[name]; exists {
321 | sh.string_filter = filter
322 | }
323 | }
324 | if name, ok := encrypt.GetName("EEF"); ok {
325 | if filter, exists := sh.crypt_filters[name]; exists {
326 | sh.file_filter = filter
327 | }
328 | }
329 | }
330 |
331 | return nil
332 | }
333 |
334 | // Algorithm 2: Computing an encryption key
335 | func (sh *SecurityHandler) computeEncryptionKey(password []byte, key_length int) []byte {
336 | // step a) pad or truncate password to exactly 32 bytes
337 | if len(password) < 32 {
338 | password = append(password, padding_string[:32 - len(password)]...)
339 | } else {
340 | password = password[:32]
341 | }
342 |
343 | // step b, c, d, e, f, g
344 | hash := md5.New()
345 | hash.Write(password)
346 | hash.Write(sh.o)
347 | hash.Write(sh.p)
348 | hash.Write(sh.id)
349 | if sh.r >= 4 && !sh.encrypt_meta_data {
350 | hash.Write([]byte("\xff\xff\xff\xff"))
351 | }
352 | encryption_key := hash.Sum(nil)[:key_length]
353 |
354 | // step h) for revision 3+, re-hash key 50 times
355 | if sh.r >= 3 {
356 | for i := 0; i < 50; i++ {
357 | hash = md5.New()
358 | hash.Write(encryption_key)
359 | encryption_key = hash.Sum(nil)[:key_length]
360 | }
361 | }
362 |
363 | return encryption_key
364 | }
365 |
--------------------------------------------------------------------------------
/pdf/errors.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "errors"
5 | )
6 |
7 |
8 | // errors
9 | var EncryptionError = errors.New("missing required encryption info")
10 | var EncryptionPasswordError = errors.New("incorrect password")
11 | var EncryptionUnsupported = errors.New("unsupported encryption")
12 | var EndOfArray = errors.New("end of array")
13 | var EndOfDictionary = errors.New("end of dictionary")
14 | var EndOfHexString = errors.New("end of hex string")
15 | var EndOfString = errors.New("end of string")
16 | var ReadError = errors.New("read failed")
17 |
18 | // format errors and abnormalities
19 | var InvalidDictionaryKeyType = "invalid dictionary key type"
20 | var InvalidHexStringChar = "invalid hex string character"
21 | var InvalidNameEscapeChar = "invalid name escape character"
22 | var InvalidOctal = "invalid octal in string"
23 | var MissingDictionaryValue = "missing dictionary value"
24 | var UnclosedArray = "unclosed array"
25 | var UnclosedDictionary = "unclosed dictionary"
26 | var UnclosedHexString = "unclosed hex string"
27 | var UnclosedStream = "unclosed stream"
28 | var UnclosedString = "unclosed string"
29 | var UnclosedStringEscape = "unclosed escape in string"
30 | var UnclosedStringOctal = "unclosed octal in string"
31 | var UnnecessaryEscapeName = "unnecessary espace sequence in name"
32 | var UnnecessaryEscapeString = "unnecessary espace sequence in string"
33 |
--------------------------------------------------------------------------------
/pdf/file.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | var unknownHash string = "00000000000000000000000000000000"
8 |
9 | type File Dictionary
10 |
11 | func (file File) Extract(output *Output, isCommand bool) {
12 | d := Dictionary(file)
13 |
14 | // file specification can be a url or file
15 | fs, _ := d.GetString("FS")
16 | if fs == "URL" {
17 | if f, ok := d.GetString("F"); ok {
18 | fmt.Fprintln(output.URLs, f)
19 | }
20 | } else if ef, ok := d.GetDictionary("EF"); ok {
21 | // get the file data
22 | file_data, _ := ef.GetStream("F")
23 |
24 | // get the file path
25 | f, ok := d.GetString("F")
26 | if !ok {
27 | f = unknownHash
28 | }
29 |
30 | // dump file
31 | output.DumpFile(f, file_data)
32 | } else if p, ok := d.GetString("P"); ok {
33 | if f, ok := d.GetString("F"); ok {
34 | fmt.Fprintf(output.Files, "%s:%s\n", unknownHash, f)
35 | fmt.Fprintf(output.Commands, "%s %s\n", f, p)
36 | }
37 | } else if f, ok := d.GetString("F"); ok {
38 | if isCommand {
39 | fmt.Fprintf(output.Commands, "%s %s\n", f, p)
40 | }
41 | fmt.Fprintf(output.Files, "%s:%s\n", unknownHash, f)
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/pdf/filters.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "bytes"
5 | "compress/lzw"
6 | "compress/zlib"
7 | "encoding/binary"
8 | "io"
9 | "math"
10 | "strconv"
11 | tiff_lzw "golang.org/x/image/tiff/lzw"
12 | )
13 |
14 | func DecodeStream(filter string, data []byte, decode_parms Dictionary) []byte {
15 | // do nothing if data is empty
16 | if len(data) == 0 {
17 | return data
18 | }
19 |
20 | // apply hex filter
21 | if filter == "ASCIIHexDecode" {
22 | return ASCIIHexDecode(data)
23 | }
24 |
25 | // apply ascii 85 filter
26 | if filter == "ASCII85Decode" {
27 | return ASCII85Decode(data)
28 | }
29 |
30 | // apply run length filter
31 | if filter == "RunLengthDecode" {
32 | return RunLengthDecode(data)
33 | }
34 |
35 | // apply zlib filter
36 | if filter == "FlateDecode" {
37 | return FlateDecode(data, decode_parms)
38 | }
39 |
40 | // apply lzw filter
41 | if filter == "LZWDecode" {
42 | return LZWDecode(data, decode_parms)
43 | }
44 |
45 | // filter is not supported
46 | return data
47 | }
48 |
49 | func ASCIIHexDecode(data []byte) []byte {
50 | // allocate buffer for decoded bytes
51 | decoded_data := make([]byte, 0, len(data))
52 |
53 | // decode data
54 | for i := 0; i < len(data); i++ {
55 | // get the first byte
56 | b1 := data[i]
57 |
58 | // skip whitespace
59 | if bytes.IndexByte(whitespace, b1) >= 0 {
60 | continue
61 | }
62 |
63 | // EOD marker
64 | if b1 == byte('>') {
65 | break
66 | }
67 |
68 | // get the second byte defaulting to zero
69 | b2 := byte('0')
70 | for ; i + 1 < len(data); i++ {
71 | // skip whitespace
72 | if bytes.IndexByte(whitespace, data[i+1]) >= 0 {
73 | continue
74 | }
75 |
76 | // EOD marker
77 | if data[i+1] == byte('>') {
78 | break
79 | }
80 |
81 | // set second byte
82 | i++
83 | b2 = data[i]
84 | break
85 | }
86 |
87 | // add decoded byte to decoded data
88 | val, err := strconv.ParseUint(string([]byte{b1, b2}), 16, 8)
89 | if err != nil {
90 | // TODO: report illegal character
91 | continue
92 | }
93 | decoded_data = append(decoded_data, byte(val))
94 | }
95 |
96 | return decoded_data
97 | }
98 |
99 | func ASCII85Decode(data []byte) []byte {
100 | reader := bytes.NewReader(data)
101 | decoded_data := bytes.NewBuffer([]byte{})
102 |
103 | v := uint32(0)
104 | n := 0
105 |
106 | for {
107 | b, err := reader.ReadByte()
108 | if err != nil || b == '~' {
109 | // finish partial group by adding zeros
110 | if n > 1 {
111 | for m := n; m < 5; m++ {
112 | v *= 85
113 | }
114 |
115 | // write result in big endian order
116 | buff := make([]byte, 4)
117 | binary.BigEndian.PutUint32(buff, v)
118 | decoded_data.Write(buff[:n-1])
119 | }
120 |
121 | return decoded_data.Bytes()
122 | }
123 |
124 | // skip whitespace
125 | if bytes.IndexByte(whitespace, b) >= 0 {
126 | continue
127 | }
128 |
129 | // handle special case
130 | if b == 'z' {
131 | if n != 0 {
132 | // TODO: report invalid use of z character
133 | continue
134 | }
135 |
136 | // write all zeros then continue
137 | decoded_data.Write([]byte{0,0,0,0})
138 | continue
139 | }
140 |
141 | // validate byte
142 | if b < '!' || b > 'u' {
143 | // TODO: report invalid ascii85 character
144 | continue
145 | }
146 |
147 | // increment counter, multiply value by 85 then add value of new byte
148 | n++
149 | v *= 85
150 | v += uint32(b) - 33
151 |
152 | if n >= 5 {
153 | // write result in big endian order
154 | buff := make([]byte, 4)
155 | binary.BigEndian.PutUint32(buff, v)
156 | decoded_data.Write(buff)
157 |
158 | // reset value and count
159 | v = 0
160 | n =0
161 | }
162 | }
163 | }
164 |
165 | func RunLengthDecode(data []byte) []byte {
166 | var decoded_data bytes.Buffer
167 | for i := 0; i < len(data); {
168 | // get length byte
169 | length := int(data[i])
170 |
171 | // EOD
172 | if length == 128 {
173 | break
174 | } else if length < 128 {
175 | // length is value of byte plus one
176 | length++
177 |
178 | // increment index
179 | i++
180 | if i >= len(data) {
181 | break
182 | }
183 |
184 | // copy as much data as we can up to length
185 | if i + length > len(data) {
186 | decoded_data.Write(data[i:])
187 | break
188 | } else {
189 | decoded_data.Write(data[i:i + length])
190 | i += length
191 | }
192 | } else if length > 128 {
193 | // increment index
194 | i++
195 | if i >= len(data) {
196 | break
197 | }
198 |
199 | // copy byte 257 - length times
200 | times := 257 - length
201 | for n := 0; n < times; n++ {
202 | decoded_data.WriteByte(data[i])
203 | }
204 | i++
205 | }
206 | }
207 | return decoded_data.Bytes()
208 | }
209 |
210 | func FlateDecode(data []byte, decode_parms Dictionary) []byte {
211 | // create zlib reader from data
212 | byte_reader := bytes.NewReader(data)
213 | zlib_reader, err := zlib.NewReader(byte_reader)
214 | if err != nil {
215 | return data
216 | }
217 | defer zlib_reader.Close()
218 |
219 | // decode data with zlib reader and return
220 | var decoded_data bytes.Buffer
221 | bytes_read, err := decoded_data.ReadFrom(zlib_reader)
222 | if bytes_read == 0 && err != nil {
223 | return data
224 | }
225 |
226 | // reverse predictor
227 | return ReversePredictor(decoded_data.Bytes(), decode_parms)
228 | }
229 |
230 | func LZWDecode(data []byte, decode_parms Dictionary) []byte {
231 | // create lzw reader from data using different implementation based on early change parm
232 | var lzw_reader io.ReadCloser
233 | early_change, ok := decode_parms.GetInt("EarlyChange")
234 | if !ok {
235 | early_change = 1
236 | }
237 | if early_change == 0 {
238 | lzw_reader = lzw.NewReader(bytes.NewReader(data), lzw.MSB, 8)
239 | } else {
240 | lzw_reader = tiff_lzw.NewReader(bytes.NewReader(data), tiff_lzw.MSB, 8)
241 | }
242 | defer lzw_reader.Close()
243 |
244 | // decode data with lzw reader and return
245 | var decoded_data bytes.Buffer
246 | bytes_read, err := decoded_data.ReadFrom(lzw_reader)
247 | if bytes_read == 0 && err != nil {
248 | return data
249 | }
250 |
251 | // reverse predictor
252 | return ReversePredictor(decoded_data.Bytes(), decode_parms)
253 | }
254 |
255 | func ReversePredictor(data []byte, decode_parms Dictionary) []byte {
256 | // get predictor parms using default when not found
257 | predictor, ok := decode_parms.GetInt("Predictor")
258 | if !ok {
259 | predictor = 1
260 | }
261 | bits_per_component, ok := decode_parms.GetInt("BitsPerComponent")
262 | if !ok {
263 | bits_per_component = 8
264 | }
265 | colors, ok := decode_parms.GetInt("Colors")
266 | if !ok {
267 | colors = 1
268 | }
269 | columns, ok := decode_parms.GetInt("Columns")
270 | if !ok {
271 | columns = 1
272 | }
273 |
274 | // make sure bits_per_component value is acceptable
275 | if bits_per_component <= 0 || bits_per_component > 16 {
276 | return data
277 | }
278 |
279 | // determine row widths in bytes
280 | row_width := (bits_per_component * colors * columns) / 8
281 | if (bits_per_component * colors * columns) % 8 > 0 {
282 | row_width++
283 | }
284 | if row_width <= 0 {
285 | return data
286 | }
287 |
288 | // no predictor applied
289 | if predictor == 1 {
290 | return data
291 | }
292 |
293 | // TIFF predictor
294 | if predictor == 2 {
295 | for r := 0; r * row_width < len(data); r ++ {
296 | row_start := r * row_width * 8
297 | for c := 1; c < columns; c++ {
298 | for i := 0; i < colors; i++ {
299 | pos := row_start + ((c * colors + i) * bits_per_component)
300 | if pos >= len(data) * 8 {
301 | return data
302 | }
303 | prev_value := GetBits(data, pos - (colors * bits_per_component), bits_per_component)
304 | value := GetBits(data, pos, bits_per_component)
305 | SetBits(data, pos, bits_per_component, value + prev_value)
306 | }
307 | }
308 | }
309 | return data
310 | }
311 |
312 | // PNG predictors
313 | if predictor >= 10 && predictor <= 15 {
314 | // allocate buffer for decoded data
315 | decoded_data := make([]byte, 0, len(data))
316 |
317 | // png row includes an algorithm tag as first byte of each row
318 | d_row_width := row_width
319 | row_width++
320 |
321 | // determine the method
322 | method := predictor - 10
323 |
324 | // for each row
325 | for r := 0; r < len(data); r += row_width {
326 | // optimum predictor allows the method to change each row based on algorithm tag
327 | if predictor == 15 {
328 | method = int(data[r])
329 | }
330 |
331 | // calculate start of row in decoded buffer
332 | dr := (r / row_width) * (row_width - 1)
333 |
334 | // apply predictors based on method
335 | for c := 1; c < row_width && r + c < len(data); c++ {
336 | // calculate column in decoded buffer
337 | dc := c - 1
338 |
339 | if method == 0 {
340 | // no predictor
341 | decoded_data = append(decoded_data, data[r + c])
342 | } else if method == 1 {
343 | // sub predictor
344 | left := 0
345 | if dc > 0 {
346 | left = int(decoded_data[dr + dc - 1])
347 | }
348 | decoded_data = append(decoded_data, byte((int(data[r + c]) + left) % 256))
349 | } else if method == 2 {
350 | // up predictor
351 | up := 0
352 | if dr + dc - d_row_width >= 0 {
353 | up = int(decoded_data[dr + dc - d_row_width])
354 | }
355 | decoded_data = append(decoded_data, byte((int(data[r + c]) + up) % 256))
356 | } else if method == 3 {
357 | // avg predictor
358 | left := 0
359 | if dc > 0 {
360 | left = int(decoded_data[dr + dc - 1])
361 | }
362 | up := 0
363 | if dr + dc - d_row_width >= 0 {
364 | up = int(decoded_data[dr + dc - d_row_width])
365 | }
366 | avg := (left + up) / 2
367 | decoded_data = append(decoded_data, byte((int(data[r + c]) + avg) % 256))
368 | } else if method == 4 {
369 | //paeth predictor
370 | left := 0
371 | if dc > 0 {
372 | left = int(decoded_data[dr + dc - 1])
373 | }
374 | up := 0
375 | if dr + dc - d_row_width >= 0 {
376 | up = int(decoded_data[dr + dc - d_row_width])
377 | }
378 | up_left := 0
379 | if dr + dc - d_row_width - 1 >= 0 && dc > 0 {
380 | up_left = int(decoded_data[dr + dc - d_row_width - 1])
381 | }
382 | p := left + up - up_left
383 | p_left := int(math.Abs(float64(p - left)))
384 | p_up := int(math.Abs(float64(p - up)))
385 | p_up_left := int(math.Abs(float64(p - up_left)))
386 | if p_left <= p_up && p_left <= p_up_left {
387 | decoded_data = append(decoded_data, byte((int(data[r + c]) + left) % 256))
388 | } else if p_up <= p_up_left {
389 | decoded_data = append(decoded_data, byte((int(data[r + c]) + up) % 256))
390 | } else {
391 | decoded_data = append(decoded_data, byte((int(data[r + c]) + up_left) % 256))
392 | }
393 | } else {
394 | // unknown predictor, do nothing
395 | decoded_data = append(decoded_data, data[r + c])
396 | }
397 | }
398 | }
399 | return decoded_data
400 | }
401 |
402 | // unknown predictor
403 | return data
404 | }
405 |
--------------------------------------------------------------------------------
/pdf/font.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "bytes"
5 | "strings"
6 | )
7 |
8 | var FontDefault *Font = &Font{map[int]string{}, 1}
9 |
10 | type Font struct {
11 | Cmap map[int]string
12 | Width int
13 | }
14 |
15 | func NewFont(d Dictionary) *Font {
16 | cmap_string, _ := d.GetStream("ToUnicode")
17 | cmap := []byte(cmap_string)
18 |
19 | // create new font object
20 | font := &Font{map[int]string{}, 1}
21 |
22 | // create parser for parsing cmap
23 | parser := NewParser(bytes.NewReader(cmap), nil)
24 |
25 | for {
26 | // read next command
27 | command, operands, err := parser.ReadCommand()
28 | if err == ReadError {
29 | break
30 | }
31 |
32 | if command == KEYWORD_BEGIN_BF_RANGE {
33 | count, _ := operands.GetInt(len(operands) - 1)
34 | for i := 0; i < count; i++ {
35 | start_b := parser.ReadHexString(noDecryptor)
36 | if start_b == "" {
37 | break
38 | }
39 | font.Width = len([]byte(start_b))
40 | start := BytesToInt([]byte(start_b))
41 |
42 | end_b := parser.ReadHexString(noDecryptor)
43 | if end_b == "" {
44 | break
45 | }
46 | end := BytesToInt([]byte(end_b))
47 |
48 | value := parser.ReadHexString(noDecryptor)
49 | if value == "" {
50 | break
51 | }
52 |
53 | for j := start; j <= end; j++ {
54 | font.Cmap[j] = string(value)
55 | }
56 | }
57 | } else if command == KEYWORD_BEGIN_BF_CHAR {
58 | count, _ := operands.GetInt(len(operands) - 1)
59 | for i := 0; i < count; i++ {
60 | key_b := parser.ReadHexString(noDecryptor)
61 | if key_b == "" {
62 | break
63 | }
64 | font.Width = len([]byte(key_b))
65 | key := BytesToInt([]byte(key_b))
66 |
67 | value := parser.ReadHexString(noDecryptor)
68 | if value == "" {
69 | break
70 | }
71 |
72 | font.Cmap[key] = string(value)
73 | }
74 | }
75 | }
76 |
77 | return font
78 | }
79 |
80 | func (font *Font) Decode(b []byte) string {
81 | var s strings.Builder
82 | for i := 0; i + font.Width <= len(b); i += font.Width {
83 | bs := b[i:i + font.Width]
84 | k := BytesToInt(bs)
85 | if v, ok := font.Cmap[k]; ok {
86 | s.WriteString(v)
87 | } else {
88 | s.WriteString(string(bs))
89 | }
90 | }
91 | return s.String()
92 | }
93 |
--------------------------------------------------------------------------------
/pdf/keyword.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | const (
4 | KEYWORD_XREF = Keyword("xref")
5 | KEYWORD_TRAILER = Keyword("trailer")
6 | KEYWORD_OBJ = Keyword("obj")
7 | KEYWORD_STREAM = Keyword("stream")
8 | KEYWORD_R = Keyword("R")
9 | KEYWORD_N = Keyword("n")
10 | KEYWORD_NULL = Keyword("null")
11 | KEYWORD_TRUE = Keyword("true")
12 | KEYWORD_FALSE = Keyword("false")
13 | KEYWORD_TEXT = Keyword("BT")
14 | KEYWORD_TEXT_END = Keyword("ET")
15 | KEYWORD_TEXT_FONT = Keyword("Tf")
16 | KEYWORD_TEXT_MOVE_1 = Keyword("T*")
17 | KEYWORD_TEXT_MOVE_2 = Keyword("Td")
18 | KEYWORD_TEXT_MOVE_3 = Keyword("TD")
19 | KEYWORD_TEXT_POSITION = Keyword("TJ")
20 | KEYWORD_TEXT_SHOW_1 = Keyword("Tj")
21 | KEYWORD_TEXT_SHOW_2 = Keyword("'")
22 | KEYWORD_TEXT_SHOW_3 = Keyword("\"")
23 | KEYWORD_BEGIN_BF_RANGE = Keyword("beginbfrange")
24 | KEYWORD_BEGIN_BF_CHAR = Keyword("beginbfchar")
25 | )
26 |
27 | type Keyword string
28 |
29 | func NewKeyword(keyword string) Keyword {
30 | return Keyword(keyword)
31 | }
32 |
33 | func (keyword Keyword) String() string {
34 | return string(keyword)
35 | }
36 |
--------------------------------------------------------------------------------
/pdf/logger.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | )
7 |
8 | var Verbose *bool
9 |
10 | func Debug(format string, a ...interface{}) {
11 | if *Verbose {
12 | if len(a) > 0 {
13 | fmt.Fprintf(os.Stderr, format, a...)
14 | fmt.Fprintln(os.Stderr, "")
15 | } else {
16 | fmt.Fprintln(os.Stderr, format)
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/pdf/name.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | type Name string
4 |
5 | func (name Name) String() string {
6 | return "/" + string(name)
7 | }
8 |
--------------------------------------------------------------------------------
/pdf/number.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Number float64
8 |
9 | func (number Number) String() string {
10 | return fmt.Sprint(float64(number))
11 | }
12 |
--------------------------------------------------------------------------------
/pdf/object.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | type Object interface {
9 | String() string
10 | }
11 |
12 | type IndirectObject struct {
13 | Number int
14 | Generation int
15 | Value Object
16 | Stream []byte
17 | }
18 |
19 | func NewIndirectObject(number int) *IndirectObject {
20 | return &IndirectObject{number, 0, KEYWORD_NULL, nil}
21 | }
22 |
23 | func (object *IndirectObject) String() string {
24 | var sb strings.Builder
25 | sb.WriteString(fmt.Sprintf("%d %d obj\n%s\n", object.Number, object.Generation, object.Value))
26 | if object.Stream != nil {
27 | sb.WriteString(fmt.Sprintf("stream\n%s\nendstream\n", string(object.Stream)))
28 | }
29 | sb.WriteString("endobj\n")
30 | return sb.String()
31 | }
32 |
33 | func (object *IndirectObject) Extract(output *Output) {
34 | // get object dictionary
35 | if d, ok := object.Value.(Dictionary); ok {
36 | extract(d, output)
37 | }
38 | }
39 |
40 | func extract(o Object, output *Output) {
41 | if d, ok := o.(Dictionary); ok {
42 | // dump actions
43 | if a, ok := d.GetDictionary("A"); ok {
44 | Action(a).Extract(output)
45 | }
46 |
47 | // dump open action
48 | if open_action, ok := d.GetDictionary("OpenAction"); ok {
49 | Action(open_action).Extract(output)
50 | }
51 |
52 | // dump additional actions
53 | if aa, ok := d.GetDictionary("AA"); ok {
54 | for key := range aa {
55 | if a, ok := aa.GetDictionary(key); ok {
56 | Action(a).Extract(output)
57 | }
58 | }
59 | }
60 |
61 | // dump forms
62 | if xfa, ok := d.GetStream("XFA"); ok {
63 | output.DumpFile("form.xml", xfa)
64 | } else if xfa, ok := d.GetArray("XFA"); ok {
65 | var form_data strings.Builder
66 | for i := range xfa {
67 | if s, ok := xfa.GetStream(i); ok {
68 | form_data.WriteString(string(s))
69 | }
70 | }
71 | output.DumpFile("form.xml", []byte(form_data.String()))
72 | }
73 |
74 | // dump Embedded Files
75 | embedded_files := d.GetNameTreeMap("EmbeddedFiles")
76 | for i := 1; i < len(embedded_files); i += 2 {
77 | if f, ok := embedded_files.GetString(i); ok {
78 | fmt.Fprintf(output.Files, "%s:%s\n", unknownHash, f)
79 | } else if f, ok := embedded_files.GetDictionary(i); ok {
80 | File(f).Extract(output, false)
81 | }
82 | }
83 |
84 | // dump javascript
85 | if js, ok := d.GetString("JS"); ok {
86 | fmt.Fprintln(output.Javascript, js)
87 | } else if js, ok := d.GetStream("JS"); ok {
88 | fmt.Fprintln(output.Javascript, string(js))
89 | }
90 |
91 | // dump page text
92 | if pages, ok := d.GetPageTree("Pages"); ok {
93 | for i := range pages {
94 | Page(pages[i]).Extract(output)
95 | }
96 | }
97 |
98 | // dump URIs
99 | if url, ok := d.GetString("URI"); ok {
100 | fmt.Fprintln(output.URLs, string(url))
101 | } else if url, ok := d.GetDictionary("URI"); ok {
102 | if base, ok := url.GetString("Base"); ok {
103 | fmt.Fprintln(output.URLs, string(base))
104 | }
105 | }
106 |
107 | // dump URLs
108 | urls := d.GetNameTreeMap("URLS")
109 | for i := 0; i < len(urls); i += 2 {
110 | if url, ok := urls.GetString(i); ok {
111 | fmt.Fprintln(output.URLs, string(url))
112 | }
113 | }
114 |
115 | for key := range d {
116 | extract(d[key], output)
117 | }
118 | } else if a, ok := o.(Array); ok {
119 | for i := range a {
120 | extract(a[i], output)
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/pdf/output.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "crypto/md5"
5 | "encoding/hex"
6 | "fmt"
7 | "io/ioutil"
8 | "os"
9 | "path"
10 | )
11 |
12 | type Output struct {
13 | Commands *os.File
14 | Directory string
15 | Errors *os.File
16 | Files *os.File
17 | Javascript *os.File
18 | Raw *os.File
19 | Text *os.File
20 | URLs *os.File
21 | }
22 |
23 | func NewOutput(directory string) (output *Output, err error) {
24 | // create new output object
25 | output = &Output{}
26 | output.Directory = directory
27 |
28 | // create output dir
29 | os.RemoveAll(directory)
30 | os.MkdirAll(directory, 0755)
31 |
32 | // create commands file
33 | if output.Commands, err = os.Create(path.Join(directory, "commands.txt")); err != nil {
34 | return
35 | }
36 |
37 | // create errors file
38 | if output.Errors, err = os.Create(path.Join(directory, "errors.txt")); err != nil {
39 | return
40 | }
41 |
42 | // create manifest file
43 | if output.Files, err = os.Create(path.Join(directory, "files.txt")); err != nil {
44 | return
45 | }
46 |
47 | // create javascript file
48 | if output.Javascript, err = os.Create(path.Join(directory, "javascript.js")); err != nil {
49 | return
50 | }
51 |
52 | // create raw.pdf file
53 | if output.Raw, err = os.Create(path.Join(directory, "raw.pdf")); err != nil {
54 | return
55 | }
56 |
57 | // create text content file in output dir
58 | if output.Text, err = os.Create(path.Join(directory, "contents.txt")); err != nil {
59 | return
60 | }
61 |
62 | // create urls file
63 | if output.URLs, err = os.Create(path.Join(directory, "urls.txt")); err != nil {
64 | return
65 | }
66 | return
67 | }
68 |
69 | func (output *Output) Close() {
70 | if output.Commands != nil {
71 | output.Commands.Close()
72 | }
73 | if output.Errors != nil {
74 | output.Files.Close()
75 | }
76 | if output.Files != nil {
77 | output.Files.Close()
78 | }
79 | if output.Javascript != nil {
80 | output.Javascript.Close()
81 | }
82 | if output.Raw != nil {
83 | output.Raw.Close()
84 | }
85 | if output.Text != nil {
86 | output.Text.Close()
87 | }
88 | if output.URLs != nil {
89 | output.URLs.Close()
90 | }
91 | }
92 |
93 | func (output *Output) DumpFile(name string, data []byte) {
94 | // get md5 hash of the file
95 | hash := md5.New()
96 | hash.Write(data)
97 | md5sum := hex.EncodeToString(hash.Sum(nil))
98 |
99 | // add to manifest
100 | fmt.Fprintf(output.Files, "%s:%s\n", md5sum, name)
101 |
102 | // write file data to file in extract dir
103 | ioutil.WriteFile(path.Join(output.Directory, md5sum), data, 0644)
104 | }
105 |
106 | func (output *Output) Error(message string) {
107 | if output.Errors != nil {
108 | fmt.Fprintln(output.Errors, message)
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/pdf/page.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "bytes"
5 | "io"
6 | "strings"
7 | )
8 |
9 | type Page Dictionary
10 |
11 | func (page Page) Extract(output *Output) {
12 | d := Dictionary(page)
13 |
14 | // load fonts
15 | font_map := map[string]*Font{}
16 | resources, _ := d.GetDictionary("Resources")
17 | fonts, _ := resources.GetDictionary("Font")
18 | for font := range fonts {
19 | font_info, _ := fonts.GetDictionary(font)
20 | font_map[font] = NewFont(font_info)
21 | }
22 |
23 | // get contents
24 | if contents, ok := d.GetStream("Contents"); ok {
25 | page.extract(output, font_map, contents)
26 | } else if contents_array, ok := d.GetArray("Contents"); ok {
27 | for i := range contents_array {
28 | if contents, ok := contents_array.GetStream(i); ok {
29 | page.extract(output, font_map, contents)
30 | }
31 | }
32 | }
33 | }
34 |
35 | func (page Page) extract(output *Output, font_map map[string]*Font, contents []byte) {
36 | // create parser for parsing contents
37 | page_parser := NewParser(bytes.NewReader(contents), nil)
38 |
39 | for {
40 | // read next command
41 | command, _, err := page_parser.ReadCommand()
42 | if err == ReadError {
43 | break
44 | }
45 |
46 | // start of text block
47 | if command == KEYWORD_TEXT {
48 | // initial font is none
49 | current_font := FontDefault
50 |
51 | for {
52 | command, operands, err := page_parser.ReadCommand()
53 | // stop if end of stream or end of text block
54 | if err == ReadError || command == KEYWORD_TEXT_END {
55 | break
56 | }
57 |
58 | // handle font changes
59 | if command == KEYWORD_TEXT_FONT {
60 | font_name, _ := operands.GetName(len(operands) - 2)
61 | if font, ok := font_map[font_name]; ok {
62 | current_font = font
63 | } else {
64 | current_font = FontDefault
65 | }
66 | } else if command == KEYWORD_TEXT_SHOW_1 || command == KEYWORD_TEXT_SHOW_2 || command == KEYWORD_TEXT_SHOW_3 {
67 | // decode text with current font font
68 | s, _ := operands.GetString(len(operands) - 1)
69 | io.WriteString(output.Text, current_font.Decode([]byte(s)))
70 | io.WriteString(output.Text, "\n")
71 | } else if command == KEYWORD_TEXT_POSITION {
72 | // decode positioned text with current font
73 | var sb strings.Builder
74 | a, _ := operands.GetArray(len(operands) - 1)
75 | for i := 0; i < len(a); i += 2 {
76 | s, _ := a.GetString(i)
77 | sb.WriteString(string(s))
78 | }
79 | io.WriteString(output.Text, current_font.Decode([]byte(sb.String())))
80 | io.WriteString(output.Text, "\n")
81 | }
82 | }
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/pdf/parser.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "io"
7 | "regexp"
8 | "sort"
9 | "strconv"
10 | "strings"
11 | )
12 |
13 | var start_xref_scan_buffer_size int64 = 256
14 | var start_xref_regexp = regexp.MustCompile(`startxref\s*(\d+)\s*%%EOF`)
15 | var start_obj_regexp = regexp.MustCompile(`\d+([\s\x00]|(%[^\r\n]*))+\d+([\s\x00]|(%[^\r\n]*))+obj`)
16 | var xref_regexp = regexp.MustCompile(`xref`)
17 | var whitespace = []byte("\x00\t\n\f\r ")
18 | var delimiters = []byte("()<>[]/%")
19 |
20 | type Parser struct {
21 | *bufio.Reader
22 | seeker io.ReadSeeker
23 | Xref map[int]*XrefEntry
24 | trailer Dictionary
25 | security_handler *SecurityHandler
26 | output *Output
27 | }
28 |
29 | func NewParser(readSeeker io.ReadSeeker, output *Output) *Parser {
30 | return &Parser{bufio.NewReader(readSeeker), readSeeker, map[int]*XrefEntry{}, Dictionary{}, NewSecurityHandler(), output}
31 | }
32 |
33 | func (parser *Parser) Load(password string) error {
34 | // find location of all xref tables
35 | xref_offsets := parser.findXrefOffsets()
36 |
37 | // find location of all objects
38 | objects := parser.findObjects()
39 |
40 | // add xref stream offsets to xref offsets then sort first to last
41 | for _, object := range objects {
42 | if object.IsXrefStream {
43 | xref_offsets = append(xref_offsets, object.Offset)
44 | }
45 | }
46 | sort.Slice(xref_offsets, func(i, j int) bool { return xref_offsets[i] < xref_offsets[j] })
47 |
48 | // add start xref offset as last entry in xref_offsets so it overrides xref entries
49 | if start_xref_offset, ok := parser.getStartXrefOffset(); ok {
50 | xref_offsets = append(xref_offsets, start_xref_offset)
51 | }
52 |
53 | // load all xrefs
54 | for i := range xref_offsets {
55 | parser.loadXref(xref_offsets[i], map[int64]interface{}{})
56 | }
57 |
58 | // repair broken and missing xref entries
59 | for object_number, object := range objects {
60 | if xref_entry, ok := parser.Xref[object_number]; ok {
61 | // replace xref entry if it does not point to an object or points to the wrong object
62 | parser.Seek(xref_entry.Offset, io.SeekStart)
63 | if n, _, ok := parser.ReadObjectHeader(); ok || n != object_number {
64 | xref_entry.Offset = object.Offset
65 | }
66 | } else {
67 | // add missing object to xref
68 | parser.Xref[object_number] = object
69 | }
70 | }
71 |
72 | // setup security handler if pdf is encrypted
73 | if encrypt, ok := parser.trailer["Encrypt"]; ok {
74 | // make sure we don't decrypt the encryption dictionary
75 | if ref, ok := encrypt.(*Reference); ok {
76 | if xref_entry, ok := parser.Xref[ref.Number]; ok {
77 | xref_entry.IsEncrypted = false
78 | }
79 | }
80 |
81 | // set encryption password
82 | if err := parser.SetPassword(password); err != nil {
83 | return err
84 | }
85 | }
86 |
87 | return nil
88 | }
89 |
90 | func (parser *Parser) SetPassword(password string) error {
91 | return parser.security_handler.Init([]byte(password), parser.trailer)
92 | }
93 |
94 | // FindXrefOffsets locates all xref tables
95 | func (parser *Parser) findXrefOffsets() []int64 {
96 | offsets := []int64{}
97 |
98 | // jump to start of file
99 | offset, _ := parser.Seek(0, io.SeekStart)
100 |
101 | for {
102 | // scan for xref table marker
103 | index := xref_regexp.FindReaderIndex(parser)
104 | if index == nil {
105 | break
106 | }
107 |
108 | // add location to offsets
109 | offsets = append(offsets, offset + int64(index[0]))
110 |
111 | // seek to end of xref marker
112 | offset, _ = parser.Seek(offset + int64(index[1]), io.SeekStart)
113 | }
114 |
115 | return offsets
116 | }
117 |
118 | // FindObjects locates all object markers
119 | func (parser *Parser) findObjects() map[int]*XrefEntry {
120 | // create xref map
121 | objects := map[int]*XrefEntry{}
122 |
123 | // jump to start of file
124 | offset, _ := parser.Seek(0, io.SeekStart)
125 |
126 | for {
127 | // scan for object start marker
128 | index := start_obj_regexp.FindReaderIndex(parser)
129 | if index == nil {
130 | break
131 | }
132 |
133 | // seek to start of object
134 | parser.Seek(offset + int64(index[0]), io.SeekStart)
135 |
136 | // get object number, generation
137 | n, g, _ := parser.ReadObjectHeader()
138 |
139 | // add xref entry
140 | objects[n] = NewXrefEntry(offset + int64(index[0]), g, XrefTypeIndirectObject)
141 |
142 | // determine if object is xref stream
143 | d := parser.ReadDictionary(noDecryptor)
144 | if t, ok := d.GetName("Type"); ok && t == "XRef" {
145 | objects[n].IsXrefStream = true
146 | objects[n].IsEncrypted = false
147 | }
148 |
149 | // seek to end of object start marker
150 | offset, _ = parser.Seek(offset + int64(index[1]), io.SeekStart)
151 | }
152 |
153 | return objects
154 | }
155 |
156 | func (parser *Parser) getStartXrefOffset() (int64, bool) {
157 | // start reading from the end of the file
158 | offset, _ := parser.Seek(0, io.SeekEnd)
159 |
160 | // dont start past begining of file
161 | offset -= start_xref_scan_buffer_size
162 | if offset < 0 {
163 | offset = 0
164 | }
165 |
166 | // read in buffer at offset
167 | buffer := make([]byte, start_xref_scan_buffer_size)
168 | parser.Seek(offset, io.SeekStart)
169 | parser.Read(buffer)
170 |
171 | // check for start xref
172 | matches := start_xref_regexp.FindAllSubmatch(buffer, -1)
173 | if matches == nil {
174 | return 0, false
175 | }
176 |
177 | // convert match to int64
178 | start_xref_offset, err := strconv.ParseInt(string(matches[len(matches)-1][1]), 10, 64)
179 | if err != nil {
180 | return 0, false
181 | }
182 |
183 | // return the start xref offset
184 | return start_xref_offset, true
185 | }
186 |
187 | func (parser *Parser) loadXref(offset int64, offsets map[int64]interface{}) {
188 | // dont load same xref twice
189 | if _, ok := offsets[offset]; !ok {
190 | offsets[offset] = nil
191 |
192 | // if xref is a table
193 | parser.Seek(offset, io.SeekStart)
194 | if keyword := parser.ReadKeyword(); keyword == KEYWORD_XREF {
195 | parser.loadXrefTable(offsets)
196 | } else {
197 | // if xref is a stream
198 | parser.Seek(offset, io.SeekStart)
199 | if n, g, ok := parser.ReadObjectHeader(); ok {
200 | // prevent decrypting xref streams
201 | parser.Xref[n] = NewXrefEntry(offset, g, XrefTypeIndirectObject)
202 | parser.Xref[n].IsEncrypted = false
203 |
204 | // read the xref object
205 | parser.loadXrefStream(n, offsets)
206 | }
207 | }
208 | }
209 | }
210 |
211 | func (parser *Parser) loadXrefTable(offsets map[int64]interface{}) {
212 | // read all xref entries
213 | xrefs := map[int]*XrefEntry{}
214 | for {
215 | // get subsection start
216 | subsection_start, ok := parser.ReadInt()
217 | if !ok {
218 | break
219 | }
220 |
221 | // get subsection length
222 | subsection_length, ok := parser.ReadInt()
223 | if !ok {
224 | break
225 | }
226 |
227 | // load each object in xref subsection
228 | for i := 0; i < subsection_length; i++ {
229 | // find xref entry offset
230 | offset, ok := parser.ReadInt64()
231 | if !ok {
232 | break
233 | }
234 |
235 | // find xref entry generation
236 | generation, ok := parser.ReadInt()
237 | if !ok {
238 | break
239 | }
240 |
241 | // find xref entry in use flag
242 | flag := parser.ReadKeyword()
243 | xref_type := XrefTypeFreeObject
244 | if flag == KEYWORD_N {
245 | xref_type = XrefTypeIndirectObject
246 | }
247 |
248 | // determine object number from subsection start
249 | object_number := subsection_start + i
250 |
251 | // add the object to xrefs
252 | xrefs[object_number] = NewXrefEntry(offset, generation, xref_type)
253 | }
254 | }
255 |
256 | // read trailer keyword
257 | parser.ReadKeyword();
258 |
259 | // read in trailer dictionary
260 | trailer := parser.ReadDictionary(noDecryptor);
261 |
262 | // load previous xref section if it exists
263 | if prev, ok := trailer.GetInt64("Prev"); ok {
264 | parser.loadXref(prev, offsets)
265 | }
266 |
267 | // merge trailer
268 | for key, value := range trailer {
269 | parser.trailer[key] = value
270 | }
271 |
272 | // merge xrefs
273 | for key, value := range xrefs {
274 | parser.Xref[key] = value
275 | }
276 | }
277 |
278 | func (parser *Parser) loadXrefStream(n int, offsets map[int64]interface{}) {
279 | xref_stream_offset := parser.CurrentOffset()
280 |
281 | // Get the xref stream object
282 | object := parser.GetObject(n)
283 |
284 | // get the stream dictionary which is also the trailer dictionary
285 | trailer, ok := object.Value.(Dictionary)
286 | if !ok {
287 | return
288 | }
289 |
290 | // load previous xref section if it exists
291 | if prev, ok := trailer.GetInt64("Prev"); ok {
292 | parser.loadXref(prev, offsets)
293 | }
294 |
295 | // merge trailer
296 | for key, value := range trailer {
297 | parser.trailer[key] = value
298 | }
299 |
300 | // get the index and width arrays
301 | index, ok := trailer.GetArray("Index")
302 | if !ok {
303 | // if there is no Index field then use default of [0 Size]
304 | size, ok := trailer.GetNumber("Size")
305 | if !ok {
306 | return
307 | }
308 | index = Array{Number(0), size}
309 | }
310 | width, ok := trailer.GetArray("W")
311 | if !ok {
312 | return
313 | }
314 |
315 | // get widths of each field
316 | type_width, ok := width.GetInt(0)
317 | if !ok {
318 | return
319 | }
320 | offset_width, ok := width.GetInt(1)
321 | if !ok {
322 | return
323 | }
324 | generation_width, ok := width.GetInt(2)
325 | if !ok {
326 | return
327 | }
328 |
329 | // parse xref subsections
330 | data_reader := bytes.NewReader(object.Stream)
331 | for i := 0; i < len(index) - 1; i += 2 {
332 | // get subsection start and length
333 | subsection_start, ok := index.GetInt(i)
334 | if !ok {
335 | return
336 | }
337 | subsection_length, ok := index.GetInt(i + 1)
338 | if !ok {
339 | return
340 | }
341 |
342 | // read in each entry in subsection
343 | for j := 0; j < subsection_length; j++ {
344 | xref_type, ok := ReadInt(data_reader, type_width)
345 | if !ok {
346 | return
347 | }
348 | offset, ok := ReadInt64(data_reader, offset_width)
349 | if !ok {
350 | return
351 | }
352 | generation, ok := ReadInt(data_reader, generation_width)
353 | if !ok {
354 | return
355 | }
356 |
357 | // determine object number from subsection_start
358 | object_number := subsection_start + j
359 |
360 | // add the object to the xrefs
361 | parser.Xref[object_number] = NewXrefEntry(offset, generation, xref_type)
362 | }
363 | }
364 |
365 | // dont decrypt xref streams
366 | parser.Xref[object.Number] = NewXrefEntry(xref_stream_offset, object.Generation, XrefTypeIndirectObject)
367 | parser.Xref[object.Number].IsEncrypted = false
368 | }
369 |
370 | func (parser *Parser) GetObject(number int) *IndirectObject {
371 | object := NewIndirectObject(number)
372 |
373 | if xref_entry, ok := parser.Xref[number]; ok {
374 | if xref_entry.Type == XrefTypeIndirectObject {
375 | // set generation number
376 | object.Generation = xref_entry.Generation
377 |
378 | // seek to start of object
379 | parser.Seek(xref_entry.Offset, io.SeekStart)
380 |
381 | // skip object header
382 | parser.ReadObjectHeader()
383 |
384 | // initialize string decryption filter
385 | var string_filter CryptFilter = noFilter
386 | if parser.security_handler != nil && xref_entry.IsEncrypted {
387 | string_filter = parser.security_handler.string_filter
388 | }
389 | string_decryptor := string_filter.NewDecryptor(number, object.Generation)
390 |
391 | // get the value of the object
392 | object.Value, _ = parser.ReadObject(string_decryptor)
393 |
394 | // get next keyword
395 | if keyword := parser.ReadKeyword(); keyword == KEYWORD_STREAM {
396 | // get stream dictionary
397 | d, ok := object.Value.(Dictionary)
398 | if !ok {
399 | d = Dictionary{}
400 | }
401 |
402 | // create list of decode filters
403 | filter_list, ok := d.GetArray("Filter")
404 | if !ok {
405 | if filter, ok := d.GetName("Filter"); ok {
406 | filter_list = Array{Name(filter)}
407 | } else {
408 | filter_list = Array{}
409 | }
410 | }
411 |
412 | // create list of decode parms
413 | decode_parms_list, ok := d.GetArray("DecodeParms")
414 | if !ok {
415 | if decode_parms, ok := d.GetDictionary("DecodeParms"); ok {
416 | decode_parms_list = Array{decode_parms}
417 | } else {
418 | decode_parms_list = Array{}
419 | }
420 | }
421 |
422 | // create a stream decryptor
423 | var crypt_filter CryptFilter = noFilter
424 | if parser.security_handler != nil && xref_entry.IsEncrypted {
425 | // use stream filter by default
426 | crypt_filter = parser.security_handler.stream_filter
427 |
428 | // use embedded file filter if object is an embedded file
429 | if t, ok := d.GetName("Type"); ok && t == "EmbeddedFile" {
430 | crypt_filter = parser.security_handler.file_filter
431 | }
432 |
433 | // handle crypt filter override
434 | if len(filter_list) > 0 {
435 | if filter, _ := filter_list.GetName(0); filter == "Crypt" {
436 | decode_parms, _ := decode_parms_list.GetDictionary(0)
437 | filter_name, ok := decode_parms.GetName("Name")
438 | if !ok {
439 | filter_name = "Identity"
440 | }
441 | if cf, exists := parser.security_handler.crypt_filters[filter_name]; exists {
442 | crypt_filter = cf
443 | }
444 | filter_list = filter_list[1:]
445 | if len(decode_parms_list) > 0 {
446 | decode_parms_list = decode_parms_list[1:]
447 | }
448 | }
449 | }
450 | }
451 | stream_decryptor := crypt_filter.NewDecryptor(number, xref_entry.Generation)
452 |
453 | // read the stream
454 | object.Stream = parser.ReadStream(stream_decryptor, filter_list, decode_parms_list)
455 | }
456 | }
457 | }
458 |
459 | return object
460 | }
461 |
462 | func (parser *Parser) Seek(offset int64, whence int) (int64, error) {
463 | parser.Reset(parser.seeker)
464 | return parser.seeker.Seek(offset, whence)
465 | }
466 |
467 | func (parser *Parser) CurrentOffset() int64 {
468 | offset, err := parser.seeker.Seek(0, io.SeekCurrent)
469 | if err != nil {
470 | return 0
471 | }
472 | return offset - int64(parser.Buffered())
473 | }
474 |
475 | // ReadObjectHeader reads an object header (10 0 obj) from the current position and returns the object number and generation
476 | func (parser *Parser) ReadObjectHeader() (int, int, bool) {
477 | // read object number
478 | number, ok := parser.ReadInt()
479 | if !ok {
480 | return number, 0, false
481 | }
482 |
483 | // read object generation
484 | generation, ok := parser.ReadInt()
485 | if !ok {
486 | return number, generation, false
487 | }
488 |
489 | // read object start marker
490 | if keyword := parser.ReadKeyword(); keyword != KEYWORD_OBJ {
491 | return number, generation, false
492 | }
493 | return number, generation, true
494 | }
495 |
496 | func (parser *Parser) ReadObject(decryptor Decryptor) (Object, error) {
497 | // consume any leading whitespace/comments
498 | parser.consumeWhitespace()
499 |
500 | // peek at next 2 bytes to determine object type
501 | b, _ := parser.Peek(2)
502 | if len(b) == 0 {
503 | return KEYWORD_NULL, ReadError
504 | }
505 |
506 | // handle names
507 | if b[0] == '/' {
508 | return parser.ReadName(), nil
509 | }
510 |
511 | // handle arrays
512 | if b[0] == '[' {
513 | return parser.ReadArray(decryptor), nil
514 | }
515 | if b[0] == ']' {
516 | parser.Discard(1)
517 | return KEYWORD_NULL, EndOfArray
518 | }
519 |
520 | // handle strings
521 | if b[0] == '(' {
522 | return parser.ReadString(decryptor), nil
523 | }
524 | if b[0] == ')' {
525 | parser.Discard(1)
526 | return KEYWORD_NULL, EndOfString
527 | }
528 |
529 | // handle dictionaries
530 | if string(b) == "<<" {
531 | return parser.ReadDictionary(decryptor), nil
532 | }
533 | if string(b) == ">>" {
534 | parser.Discard(2)
535 | return KEYWORD_NULL, EndOfDictionary
536 | }
537 |
538 | // handle hex strings
539 | if b[0] == '<' {
540 | return parser.ReadHexString(decryptor), nil
541 | }
542 | if b[0] == '>' {
543 | parser.Discard(1)
544 | return KEYWORD_NULL, EndOfHexString
545 | }
546 |
547 | // handle numbers and references
548 | if (b[0] >= '0' && b[0] <= '9') || b[0] == '+' || b[0] == '-' || b[0] == '.' {
549 | number := parser.ReadNumber()
550 |
551 | // save offset so we can revert if this is not a reference
552 | offset := parser.CurrentOffset()
553 |
554 | // if generation number does not follow then revert to saved offset and return number
555 | generation, ok := parser.ReadInt()
556 | if !ok {
557 | parser.Seek(offset, io.SeekStart)
558 | return number, nil
559 | }
560 |
561 | // if not a reference then revert to saved offset and return the number
562 | if keyword := parser.ReadKeyword(); keyword != KEYWORD_R {
563 | parser.Seek(offset, io.SeekStart)
564 | return number, nil
565 | }
566 |
567 | // return the reference
568 | return NewReference(parser, int(number), generation), nil
569 | }
570 |
571 | // handle keywords
572 | return parser.ReadKeyword(), nil
573 | }
574 |
575 | func (parser *Parser) ReadArray(decryptor Decryptor) Array {
576 | // consume any leading whitespace/comments
577 | parser.consumeWhitespace()
578 |
579 | // create a new array
580 | array := Array{}
581 |
582 | // read start of array marker
583 | b, err := parser.ReadByte()
584 | if err != nil || b != '[' {
585 | return array
586 | }
587 |
588 | // read in elements and append to array
589 | for {
590 | element, err := parser.ReadObject(decryptor)
591 | if err == ReadError {
592 | parser.log_error(UnclosedArray)
593 | break
594 | }
595 | if err == EndOfArray {
596 | break
597 | }
598 | array = append(array, element)
599 | }
600 |
601 | // return array
602 | return array
603 | }
604 |
605 | func (parser *Parser) ReadCommand() (Keyword, Array, error) {
606 | // read in operands until command keyword
607 | operands := Array{}
608 | for {
609 | operand, err := parser.ReadObject(noDecryptor)
610 | if err != nil {
611 | return KEYWORD_NULL, operands, err
612 | }
613 | if keyword, ok := operand.(Keyword); ok {
614 | return keyword, operands, nil
615 | }
616 | operands = append(operands, operand)
617 | }
618 | }
619 |
620 | func (parser *Parser) ReadDictionary(decryptor Decryptor) Dictionary {
621 | // consume any leading whitespace/comments
622 | parser.consumeWhitespace()
623 |
624 | // create new dictionary
625 | dictionary := Dictionary{}
626 |
627 | // read start of dictionary markers
628 | b := make([]byte, 2)
629 | _, err := parser.Read(b)
630 | if err != nil || string(b) != "<<" {
631 | return dictionary
632 | }
633 |
634 | // parse all key value pairs
635 | for {
636 | // read next object
637 | name, err := parser.ReadObject(decryptor)
638 | if err == ReadError {
639 | parser.log_error(UnclosedDictionary)
640 | break
641 | }
642 | if err == EndOfDictionary {
643 | break
644 | }
645 |
646 | // skip if not a name
647 | key, ok := name.(Name)
648 | if !ok {
649 | parser.log_error(InvalidDictionaryKeyType)
650 | continue
651 | }
652 |
653 | // get value
654 | value, err := parser.ReadObject(decryptor)
655 | if err == ReadError || err == EndOfDictionary {
656 | parser.log_error(MissingDictionaryValue)
657 | break
658 | }
659 |
660 | // add key value pair to dictionary
661 | dictionary[string(key)] = value
662 | }
663 | return dictionary
664 | }
665 |
666 | func (parser *Parser) ReadHexString(decryptor Decryptor) String {
667 | // consume any leading whitespace/comments
668 | parser.consumeWhitespace()
669 |
670 | // create new string builder
671 | var s strings.Builder
672 |
673 | // read start of hex string marker
674 | b, err := parser.ReadByte()
675 | if err != nil || b != '<' {
676 | return String(s.String())
677 | }
678 |
679 | // read hex code pairs until end of hex string or file
680 | for {
681 | code := []byte{'0', '0'}
682 | for i := 0; i < 2; {
683 | parser.consumeWhitespace()
684 | b, err := parser.ReadByte()
685 | if err != nil || b == '>' {
686 | if err != nil {
687 | parser.log_error(UnclosedHexString)
688 | }
689 | if i > 0 {
690 | val, _ := strconv.ParseUint(string(code), 16, 8)
691 | s.WriteByte(byte(val))
692 | }
693 | s_data := []byte(s.String())
694 | decryptor.Decrypt(s_data)
695 | return String(s_data)
696 | }
697 | if !IsHex(b) {
698 | parser.log_error(InvalidHexStringChar)
699 | continue
700 | }
701 | code[i] = b
702 | i++
703 | }
704 | val, _ := strconv.ParseUint(string(code), 16, 8)
705 | s.WriteByte(byte(val))
706 | }
707 | }
708 |
709 | func (parser *Parser) ReadInt() (int, bool) {
710 | value, ok := parser.ReadInt64()
711 | return int(value), ok
712 | }
713 |
714 | func (parser *Parser) ReadInt64() (int64, bool) {
715 | // consume any leading whitespace/comments
716 | parser.consumeWhitespace()
717 |
718 | // create a new number object
719 | value := int64(0)
720 |
721 | // ensure first byte is a digit
722 | b, err := parser.ReadByte()
723 | if err != nil || b < '0' || b > '9' {
724 | parser.UnreadByte()
725 | return value, false
726 | }
727 |
728 | // add digit to value
729 | value = value * 10 + int64(b - '0')
730 |
731 | // parse int part
732 | for {
733 | b, err = parser.ReadByte()
734 | if err != nil {
735 | break
736 | }
737 |
738 | // stop if no numeric char
739 | if b < '0' || b > '9' {
740 | parser.UnreadByte()
741 | break
742 | }
743 |
744 | // add digit to value
745 | value = value * 10 + int64(b - '0')
746 | }
747 |
748 | return value, true
749 | }
750 |
751 | func (parser *Parser) ReadKeyword() Keyword {
752 | // consume any leading whitespace/comments
753 | parser.consumeWhitespace()
754 |
755 | // build keyword
756 | var keyword strings.Builder
757 |
758 | for {
759 | // read in the next byte
760 | b, err := parser.ReadByte()
761 | if err != nil {
762 | break
763 | }
764 |
765 | // stop if not keyword character
766 | if bytes.IndexByte(whitespace, b) >= 0 || bytes.IndexByte(delimiters, b) >= 0 {
767 | parser.UnreadByte()
768 | break
769 | }
770 |
771 | // add character to keyword
772 | keyword.WriteByte(b)
773 | }
774 |
775 | // interpret keyword value
776 | return NewKeyword(keyword.String())
777 | }
778 |
779 | func (parser *Parser) ReadName() Name {
780 | // consume any leading whitespace/comments
781 | parser.consumeWhitespace()
782 |
783 | // build name
784 | var name strings.Builder
785 |
786 | // read start of name marker
787 | b, err := parser.ReadByte()
788 | if err != nil || b != '/' {
789 | return Name(name.String())
790 | }
791 |
792 | for {
793 | // read in the next byte
794 | b, err = parser.ReadByte()
795 | if err != nil {
796 | return Name(name.String())
797 | }
798 |
799 | // if the next byte is whitespace or delimiter then unread it and return the name
800 | if bytes.IndexByte(delimiters, b) >= 0 || bytes.IndexByte(whitespace, b) >= 0 {
801 | parser.UnreadByte()
802 | break
803 | }
804 |
805 | // if next byte is the start of a hex character code
806 | if b == '#' {
807 | // read in the hex code
808 | code := []byte{'0', '0'}
809 | for i := 0; i < 2; i++ {
810 | b, err = parser.ReadByte()
811 | if err != nil {
812 | break
813 | }
814 | if !IsHex(b) {
815 | parser.log_error(InvalidNameEscapeChar)
816 | parser.UnreadByte()
817 | break
818 | }
819 | code[i] = b
820 | }
821 |
822 | // convert the hex code to a byte
823 | val, _ := strconv.ParseUint(string(code), 16, 8)
824 | b = byte(val)
825 |
826 | // if b did not need to be escaped
827 | if b >= '!' && b <= '~' && b != '#' && bytes.IndexByte(delimiters, b) < 0 {
828 | parser.log_error(UnnecessaryEscapeName)
829 | }
830 | }
831 |
832 | // add byte to name
833 | name.WriteByte(b)
834 | }
835 |
836 | return Name(name.String())
837 | }
838 |
839 | func (parser *Parser) ReadNumber() Number {
840 | // consume any leading whitespace/comments
841 | parser.consumeWhitespace()
842 |
843 | // create a new number object
844 | var number Number
845 | isReal := false
846 | isNegative := false
847 |
848 | // process first byte
849 | b, err := parser.ReadByte()
850 | if err != nil {
851 | return number
852 | }
853 | if b == '-' {
854 | isNegative = true
855 | } else if b >= '0' && b <= '9' {
856 | number = Number(float64(number) * 10 + float64(b - '0'))
857 | } else if b == '.' {
858 | isReal = true
859 | } else if b != '+' {
860 | parser.UnreadByte()
861 | return number
862 | }
863 |
864 | // parse int part
865 | for !isReal {
866 | b, err = parser.ReadByte()
867 | if err != nil {
868 | break
869 | }
870 |
871 | if b >= '0' && b <= '9' {
872 | number = Number(float64(number) * 10 + float64(b - '0'))
873 | } else if b == '.' {
874 | isReal = true
875 | } else {
876 | parser.UnreadByte()
877 | break
878 | }
879 | }
880 |
881 | // parse real part
882 | if isReal {
883 | for i := 1; true; i++ {
884 | b, err = parser.ReadByte()
885 | if err != nil {
886 | break
887 | }
888 |
889 | if b >= '0' && b <= '9' {
890 | number = Number(float64(number) + float64(b - '0') / (10 * float64(i)))
891 | } else {
892 | parser.UnreadByte()
893 | break
894 | }
895 | }
896 | }
897 |
898 | // make negative if first byte was a minus sign
899 | if isNegative {
900 | number = -number
901 | }
902 |
903 | // return the number
904 | return number
905 | }
906 |
907 | func (parser *Parser) ReadStream(decryptor Decryptor, filter_list Array, decode_parms_list Array) []byte {
908 | // create buffers for stream data
909 | stream_data := bytes.NewBuffer([]byte{})
910 |
911 | // read until new line
912 | for {
913 | b, err := parser.ReadByte()
914 | if err != nil {
915 | return stream_data.Bytes()
916 | }
917 |
918 | // if new line then we are at the start of the stream data
919 | if b == '\n' {
920 | break
921 | }
922 |
923 | // if carriage return check if next byte is line feed
924 | if b == '\r' {
925 | b, err := parser.ReadByte()
926 | if err != nil {
927 | return stream_data.Bytes()
928 | }
929 | // if not new line then put it back cause it is part of the stream data
930 | if b != '\n' {
931 | parser.UnreadByte()
932 | }
933 | break
934 | }
935 | }
936 |
937 | // read first 9 bytes to get started
938 | end_buff := bytes.NewBuffer([]byte{})
939 | buff := make([]byte, 9)
940 | bytes_read, _ := parser.Read(buff)
941 | if bytes_read > 0 {
942 | end_buff.Write(buff[:bytes_read])
943 | }
944 |
945 | // read in stream data until endstream marker
946 | for {
947 | if end_buff.String() == "endstream" {
948 | // truncate last new line from stream_data and stop reading stream data
949 | l := stream_data.Len()
950 | if l-1 >= 0 && stream_data.Bytes()[l-1] == '\n' {
951 | if l-2 >= 0 && stream_data.Bytes()[l-2] == '\r' {
952 | stream_data.Truncate(l-2)
953 | } else {
954 | stream_data.Truncate(l-1)
955 | }
956 | } else if l-1 >= 0 && stream_data.Bytes()[l-1] == '\r' {
957 | stream_data.Truncate(l-1)
958 | }
959 | break
960 | }
961 |
962 | // add first byte of end_buff to stream_data
963 | b, err := end_buff.ReadByte()
964 | if err != nil {
965 | break
966 | }
967 | stream_data.WriteByte(b)
968 |
969 | // add next byte of stream to end_buff
970 | b, err = parser.ReadByte()
971 | if err != nil {
972 | parser.log_error(UnclosedStream)
973 | stream_data.Write(end_buff.Bytes())
974 | break
975 | }
976 | end_buff.WriteByte(b)
977 | }
978 |
979 | // decrypt stream
980 | stream_data_bytes := stream_data.Bytes()
981 | decryptor.Decrypt(stream_data_bytes)
982 |
983 | // decode stream
984 | for i := 0; i < len(filter_list); i++ {
985 | filter, _ := filter_list.GetName(i)
986 | decode_parms, _ := decode_parms_list.GetDictionary(i)
987 | stream_data_bytes = DecodeStream(filter, stream_data_bytes, decode_parms)
988 | }
989 |
990 | // return the decrypted and decoded stream
991 | return stream_data_bytes
992 | }
993 |
994 | func (parser *Parser) ReadString(decryptor Decryptor) String {
995 | // consume any leading whitespace/comments
996 | parser.consumeWhitespace()
997 |
998 | // create new string builder
999 | var s strings.Builder
1000 |
1001 | // read start of string marker
1002 | b, err := parser.ReadByte()
1003 | if err != nil {
1004 | return String(s.String())
1005 | }
1006 | if b != '(' {
1007 | return String(s.String())
1008 | }
1009 |
1010 | // find balanced closing bracket
1011 | for open_parens := 1; true; {
1012 | // read next byte
1013 | b, err = parser.ReadByte()
1014 | if err != nil {
1015 | parser.log_error(UnclosedString)
1016 | s_data := []byte(s.String())
1017 | decryptor.Decrypt(s_data)
1018 | return String(s_data)
1019 | }
1020 |
1021 | // if this is the start of an escape sequence
1022 | if b == '\\' {
1023 | // read next byte
1024 | b, err = parser.ReadByte()
1025 | if err != nil {
1026 | parser.log_error(UnclosedStringEscape)
1027 | s.WriteByte('\\')
1028 | s_data := []byte(s.String())
1029 | decryptor.Decrypt(s_data)
1030 | return String(s_data)
1031 | }
1032 |
1033 | // ignore escaped line breaks \n or \r or \r\n
1034 | if b == '\n' {
1035 | continue
1036 | }
1037 | if b == '\r' {
1038 | // read next byte
1039 | b, err = parser.ReadByte()
1040 | if err != nil {
1041 | parser.log_error(UnclosedStringEscape)
1042 | s_data := []byte(s.String())
1043 | decryptor.Decrypt(s_data)
1044 | return String(s_data)
1045 | }
1046 | // if byte is not a new line then unread it
1047 | if b != '\n' {
1048 | parser.UnreadByte()
1049 | }
1050 | continue
1051 | }
1052 |
1053 | // special escape values
1054 | if b == 'n' {
1055 | b = '\n'
1056 | } else if b == 'r' {
1057 | b = '\r'
1058 | } else if b == 't' {
1059 | b = '\t'
1060 | } else if b == 'b' {
1061 | b = '\b'
1062 | } else if b == 'f' {
1063 | b = '\f'
1064 | }
1065 |
1066 | // if this is the start of an octal character code
1067 | if b >= '0' && b <= '7' {
1068 | // add byte to character code
1069 | code := bytes.NewBuffer([]byte{b})
1070 |
1071 | // add at most 2 more bytes to code
1072 | for i := 0; i < 2; i++ {
1073 | // read next byte
1074 | b, err = parser.ReadByte()
1075 | if err != nil {
1076 | parser.log_error(UnclosedStringOctal)
1077 | break
1078 | }
1079 |
1080 | // if next byte is not part of the octal code
1081 | if b < '0' || b > '7' {
1082 | // unread the byte and stop collecting code
1083 | parser.UnreadByte()
1084 | break
1085 | }
1086 |
1087 | // add byte to code
1088 | code.WriteByte(b)
1089 | }
1090 |
1091 | // convert code into byte
1092 | val, err := strconv.ParseUint(string(code.Bytes()), 8, 8)
1093 | if err != nil {
1094 | // octal code is too large so ignore last byte
1095 | parser.log_error(InvalidOctal)
1096 | parser.UnreadByte()
1097 | val, _ = strconv.ParseUint(string(code.Bytes()[:code.Len()-1]), 8, 8)
1098 | }
1099 | b = byte(val)
1100 |
1101 | // if b did not need to be escaped
1102 | if b >= '!' && b <= '~' && b != '\\' && b != '(' && b != ')' {
1103 | parser.log_error(UnnecessaryEscapeString)
1104 | }
1105 | }
1106 |
1107 | // add byte to string and continue
1108 | s.WriteByte(b)
1109 | continue
1110 | }
1111 |
1112 | // keep track of number of open parens
1113 | if b == '(' {
1114 | open_parens++
1115 | } else if b == ')' {
1116 | open_parens--
1117 | }
1118 |
1119 | // stop if last paren was read
1120 | if open_parens == 0 {
1121 | break
1122 | }
1123 |
1124 | // add byte to string
1125 | s.WriteByte(b)
1126 | }
1127 |
1128 | // return string
1129 | s_data := []byte(s.String())
1130 | decryptor.Decrypt(s_data)
1131 | return String(s_data)
1132 | }
1133 |
1134 | // consumeWhitespace reads until end of whitespace/comments
1135 | func (parser *Parser) consumeWhitespace() {
1136 | for {
1137 | // get next byte
1138 | b, err := parser.ReadByte()
1139 | if err != nil {
1140 | return
1141 | }
1142 |
1143 | // consume comments and whitespace
1144 | if b == '%' {
1145 | parser.consumeComment()
1146 | } else if bytes.IndexByte(whitespace, b) < 0 {
1147 | parser.UnreadByte()
1148 | return
1149 | }
1150 | }
1151 | }
1152 |
1153 | func (parser *Parser) consumeComment() {
1154 | for {
1155 | // get next byte
1156 | b, err := parser.ReadByte()
1157 | if err != nil {
1158 | return
1159 | }
1160 |
1161 | // stop on line feed
1162 | if b == '\n' {
1163 | return
1164 | }
1165 |
1166 | // stop on carriage return
1167 | if b == '\r' {
1168 | // consume optional line feed
1169 | b, err := parser.ReadByte()
1170 | if err != nil {
1171 | return
1172 | }
1173 | if b != '\n' {
1174 | parser.UnreadByte()
1175 | }
1176 | return
1177 | }
1178 | }
1179 | }
1180 |
1181 | func (parser *Parser) log_error(message string) {
1182 | if parser.output != nil {
1183 | parser.output.Error(message)
1184 | }
1185 | }
1186 |
--------------------------------------------------------------------------------
/pdf/pdf.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | )
7 |
8 | func Parse(file_path string, password string, output_dir string) error {
9 | // open the pdf
10 | file, err := os.Open(file_path)
11 | if err != nil {
12 | return err
13 | }
14 | defer file.Close()
15 |
16 | // create output directory and files
17 | output, err := NewOutput(output_dir)
18 | defer output.Close()
19 | if err != nil {
20 | return err
21 | }
22 |
23 | // create a new parser
24 | parser := NewParser(file, output)
25 |
26 | // load the pdf
27 | Debug("Loading xref")
28 | if err := parser.Load(password); err != nil {
29 | return err
30 | }
31 |
32 | // extract and dump all objects
33 | for object_number, xref_entry := range parser.Xref {
34 | if xref_entry.Type == XrefTypeIndirectObject {
35 | Debug("Extracting object %d", object_number)
36 | object := parser.GetObject(object_number)
37 | object.Extract(output)
38 | fmt.Fprintln(output.Raw, object.String())
39 | }
40 | }
41 |
42 | return nil
43 | }
44 |
--------------------------------------------------------------------------------
/pdf/reference.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | )
7 |
8 | type Reference struct {
9 | parser *Parser
10 | Number int
11 | Generation int
12 | }
13 |
14 | func NewReference(parser *Parser, number int, generation int) *Reference {
15 | return &Reference{parser, number, generation}
16 | }
17 |
18 | func (reference *Reference) String() string {
19 | return fmt.Sprintf("%d %d R", reference.Number, reference.Generation)
20 | }
21 |
22 | func (reference *Reference) Resolve() Object {
23 | // save current offset so we can come back
24 | current_offset := reference.parser.CurrentOffset()
25 |
26 | // resolve the referenced object value
27 | object := reference.resolve(map[int]interface{}{})
28 |
29 | // revert offset
30 | reference.parser.Seek(current_offset, io.SeekStart)
31 |
32 | // return the resolved object value
33 | return object.Value
34 | }
35 |
36 | func (reference *Reference) ResolveStream() []byte {
37 | // save current offset so we can come back
38 | current_offset := reference.parser.CurrentOffset()
39 |
40 | // resolve the referenced object value
41 | object := reference.resolve(map[int]interface{}{})
42 |
43 | // revert offset
44 | reference.parser.Seek(current_offset, io.SeekStart)
45 |
46 | // return the resolved object value
47 | return object.Stream
48 | }
49 |
50 | func (reference *Reference) resolve(resolved_references map[int]interface{}) *IndirectObject {
51 | // prevent infinite loop
52 | if _, ok := resolved_references[reference.Number]; ok {
53 | return NewIndirectObject(reference.Number)
54 | }
55 | resolved_references[reference.Number] = nil
56 |
57 | // use parser to get object
58 | object := reference.parser.GetObject(reference.Number)
59 |
60 | // recursively resolve references
61 | if ref, ok := object.Value.(*Reference); ok {
62 | return ref.resolve(resolved_references)
63 | }
64 |
65 | // return the object
66 | return object
67 | }
68 |
--------------------------------------------------------------------------------
/pdf/string.go:
--------------------------------------------------------------------------------
1 | package pdf
2 |
3 | type String string
4 |
5 | func (s String) String() string {
6 | return "(" + string(s) + ")"
7 | }
8 |
--------------------------------------------------------------------------------
/pdf/test/carriage_return.pdf:
--------------------------------------------------------------------------------
1 | 1
0%comment
obj
2 | <>
3 | stream
Hello
4 | endstream
5 | endobj
6 |
--------------------------------------------------------------------------------
/pdf/test/comments.pdf:
--------------------------------------------------------------------------------
1 | % lets see if some comments mess this up
2 | 1 %comment
3 | %comment
4 | 0%%comment
5 | %comment
6 | obj %comment
7 | (%this is not a comment) %comment
8 | %comment
9 | endobj
10 |
--------------------------------------------------------------------------------
/pdf/test/empty_array.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | []
3 | endobj
4 |
--------------------------------------------------------------------------------
/pdf/test/empty_dictionary.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | <<>>
3 | endobj
4 |
--------------------------------------------------------------------------------
/pdf/test/encrypted.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/encrypted.pdf
--------------------------------------------------------------------------------
/pdf/test/filter_ascii_85_decode.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | <>stream
3 | z,p >`r
4 | DK Jj'E+L~>
5 | endstream
6 | endobj
7 |
--------------------------------------------------------------------------------
/pdf/test/filter_ascii_hex_decode.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | <>
3 | stream
4 | 4 8656c6C6f7>71qwe
5 | endstream
6 | endobj
7 |
--------------------------------------------------------------------------------
/pdf/test/filter_flate_decode.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/filter_flate_decode.pdf
--------------------------------------------------------------------------------
/pdf/test/filter_lzw_decode.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/filter_lzw_decode.pdf
--------------------------------------------------------------------------------
/pdf/test/filter_lzw_tiff_decode.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/filter_lzw_tiff_decode.pdf
--------------------------------------------------------------------------------
/pdf/test/filter_multiple.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/filter_multiple.pdf
--------------------------------------------------------------------------------
/pdf/test/filter_run_length_decode.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KarmaPenny/pdfparser/1aaf59651af9068195333554506630bf2fb6f652/pdf/test/filter_run_length_decode.pdf
--------------------------------------------------------------------------------
/pdf/test/malformed_dictionary_key.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | <>
3 | endobj
4 |
--------------------------------------------------------------------------------
/pdf/test/max_cmap_size.pdf:
--------------------------------------------------------------------------------
1 | 1 0 obj
2 | <>
3 | endobj
4 |
5 | 2 0 obj
6 | <>
7 | stream
8 | /CIDInit /ProcSet findresource begin
9 | 12 dict begin
10 | begincmap
11 | /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def
12 | /CMapName /Adobe-Identity-UCS def
13 | /CMapType 2 def
14 | /WMode 0 def
15 | 1 begincodespacerange
16 | <0000>
17 | endcodespacerange
18 | 100 beginbfrange
19 | <0000> <00ff> <0000>
20 | <0100> <01ff> <0100>
21 | <0200> <02ff> <0200>
22 | <0300> <03ff> <0300>
23 | <0400> <04ff> <0400>
24 | <0500> <05ff> <0500>
25 | <0600> <06ff> <0600>
26 | <0700> <07ff> <0700>
27 | <0800> <08ff> <0800>
28 | <0900> <09ff> <0900>
29 | <0a00> <0aff> <0a00>
30 | <0b00> <0bff> <0b00>
31 | <0c00> <0cff> <0c00>
32 | <0d00> <0dff> <0d00>
33 | <0e00> <0eff> <0e00>
34 | <0f00> <0fff> <0f00>
35 | <1000> <10ff> <1000>
36 | <1100> <11ff> <1100>
37 | <1200> <12ff> <1200>
38 | <1300> <13ff> <1300>
39 | <1400> <14ff> <1400>
40 | <1500> <15ff> <1500>
41 | <1600> <16ff> <1600>
42 | <1700> <17ff> <1700>
43 | <1800> <18ff> <1800>
44 | <1900> <19ff> <1900>
45 | <1a00> <1aff> <1a00>
46 | <1b00> <1bff> <1b00>
47 | <1c00> <1cff> <1c00>
48 | <1d00> <1dff> <1d00>
49 | <1e00> <1eff> <1e00>
50 | <1f00> <1fff> <1f00>
51 | <2000> <20ff> <2000>
52 | <2100> <21ff> <2100>
53 | <2200> <22ff> <2200>
54 | <2300> <23ff> <2300>
55 | <2400> <24ff> <2400>
56 | <2500> <25ff> <2500>
57 | <2600> <26ff> <2600>
58 | <2700> <27ff> <2700>
59 | <2800> <28ff> <2800>
60 | <2900> <29ff> <2900>
61 | <2a00> <2aff> <2a00>
62 | <2b00> <2bff> <2b00>
63 | <2c00> <2cff> <2c00>
64 | <2d00> <2dff> <2d00>
65 | <2e00> <2eff> <2e00>
66 | <2f00> <2fff> <2f00>
67 | <3000> <30ff> <3000>
68 | <3100> <31ff> <3100>
69 | <3200> <32ff> <3200>
70 | <3300> <33ff> <3300>
71 | <3400> <34ff> <3400>
72 | <3500> <35ff> <3500>
73 | <3600> <36ff> <3600>
74 | <3700> <37ff> <3700>
75 | <3800> <38ff> <3800>
76 | <3900> <39ff> <3900>
77 | <3a00> <3aff> <3a00>
78 | <3b00> <3bff> <3b00>
79 | <3c00> <3cff> <3c00>
80 | <3d00> <3dff> <3d00>
81 | <3e00> <3eff> <3e00>
82 | <3f00> <3fff> <3f00>
83 | <4000> <40ff> <4000>
84 | <4100> <41ff> <4100>
85 | <4200> <42ff> <4200>
86 | <4300> <43ff> <4300>
87 | <4400> <44ff> <4400>
88 | <4500> <45ff> <4500>
89 | <4600> <46ff> <4600>
90 | <4700> <47ff> <4700>
91 | <4800> <48ff> <4800>
92 | <4900> <49ff> <4900>
93 | <4a00> <4aff> <4a00>
94 | <4b00> <4bff> <4b00>
95 | <4c00> <4cff> <4c00>
96 | <4d00> <4dff> <4d00>
97 | <4e00> <4eff> <4e00>
98 | <4f00> <4fff> <4f00>
99 | <5000> <50ff> <5000>
100 | <5100> <51ff> <5100>
101 | <5200> <52ff> <5200>
102 | <5300> <53ff> <5300>
103 | <5400> <54ff> <5400>
104 | <5500> <55ff> <5500>
105 | <5600> <56ff> <5600>
106 | <5700> <57ff> <5700>
107 | <5800> <58ff> <5800>
108 | <5900> <59ff> <5900>
109 | <5a00> <5aff> <5a00>
110 | <5b00> <5bff> <5b00>
111 | <5c00> <5cff> <5c00>
112 | <5d00> <5dff> <5d00>
113 | <5e00> <5eff> <5e00>
114 | <5f00> <5fff> <5f00>
115 | <6000> <60ff> <6000>
116 | <6100> <61ff> <6100>
117 | <6200> <62ff> <6200>
118 | <6300> <63ff> <6300>
119 | endbfrange
120 | 100 beginbfrange
121 | <6400> <64ff> <6400>
122 | <6500> <65ff> <6500>
123 | <6600> <66ff> <6600>
124 | <6700> <67ff> <6700>
125 | <6800> <68ff> <6800>
126 | <6900> <69ff> <6900>
127 | <6a00> <6aff> <6a00>
128 | <6b00> <6bff> <6b00>
129 | <6c00> <6cff> <6c00>
130 | <6d00> <6dff> <6d00>
131 | <6e00> <6eff> <6e00>
132 | <6f00> <6fff> <6f00>
133 | <7000> <70ff> <7000>
134 | <7100> <71ff> <7100>
135 | <7200> <72ff> <7200>
136 | <7300> <73ff> <7300>
137 | <7400> <74ff> <7400>
138 | <7500> <75ff> <7500>
139 | <7600> <76ff> <7600>
140 | <7700> <77ff> <7700>
141 | <7800> <78ff> <7800>
142 | <7900> <79ff> <7900>
143 | <7a00> <7aff> <7a00>
144 | <7b00> <7bff> <7b00>
145 | <7c00> <7cff> <7c00>
146 | <7d00> <7dff> <7d00>
147 | <7e00> <7eff> <7e00>
148 | <7f00> <7fff> <7f00>
149 | <8000> <80ff> <8000>
150 | <8100> <81ff> <8100>
151 | <8200> <82ff> <8200>
152 | <8300> <83ff> <8300>
153 | <8400> <84ff> <8400>
154 | <8500> <85ff> <8500>
155 | <8600> <86ff> <8600>
156 | <8700> <87ff> <8700>
157 | <8800> <88ff> <8800>
158 | <8900> <89ff> <8900>
159 | <8a00> <8aff> <8a00>
160 | <8b00> <8bff> <8b00>
161 | <8c00> <8cff> <8c00>
162 | <8d00> <8dff> <8d00>
163 | <8e00> <8eff> <8e00>
164 | <8f00> <8fff> <8f00>
165 | <9000> <90ff> <9000>
166 | <9100> <91ff> <9100>
167 | <9200> <92ff> <9200>
168 | <9300> <93ff> <9300>
169 | <9400> <94ff> <9400>
170 | <9500> <95ff> <9500>
171 | <9600> <96ff> <9600>
172 | <9700> <97ff> <9700>
173 | <9800> <98ff> <9800>
174 | <9900> <99ff> <9900>
175 | <9a00> <9aff> <9a00>
176 | <9b00> <9bff> <9b00>
177 | <9c00> <9cff> <9c00>
178 | <9d00> <9dff> <9d00>
179 | <9e00> <9eff> <9e00>
180 | <9f00> <9fff> <9f00>
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 | endbfrange
222 | 56 beginbfrange
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |