Debian Codegraph @

podofo/tools/podofosign/podofosign.cpp

raw symbols SCIP
1 /**
2 * SPDX-FileCopyrightText: (C) 2016 zyx <[email protected]>
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 */
5
6 #include <podofo/private/PdfDeclarationsPrivate.h>
7 #include <podofo/podofo.h>
8
9 #include <cstdlib>
10 #include <cstdio>
11 #include <string>
12 #include <iostream>
13 #include <openssl/bio.h>
14 #include <openssl/evp.h>
15 #include <openssl/err.h>
16 #include <openssl/pem.h>
17 #include <openssl/ssl.h>
18 #include <openssl/x509.h>
19
20 #if defined(_WIN64)
21 #define fseeko _fseeki64
22 #define ftello _ftelli64
23 #else
24 #define fseeko fseek
25 #define ftello ftell
26 #endif
27
28 using namespace std;
29 using namespace PoDoFo;
30
31 class MySigner : public PdfSigner
32 {
33 public:
34 MySigner(X509* cert, EVP_PKEY* pkey, const EVP_MD* digest)
35 : m_cert(cert), m_pkey(pkey), m_digest(digest) { }
36
37 protected:
38 void Reset() override
39 {
40 m_buffer.clear();
41 }
42
43 void AppendData(const bufferview& data) override
44 {
45 m_buffer.append(data.data(), data.size());
46 }
47
48 void ComputeSignature(charbuff& buffer, bool dryrun) override;
49
50 /**
51 * Should return the signature /Filter, for example "Adobe.PPKLite"
52 */
53 string GetSignatureFilter() const override
54 {
55 return "Adobe.PPKLite";
56 }
57
58 /**
59 * Should return the signature /SubFilter, for example "ETSI.CAdES.detached"
60 */
61 string GetSignatureSubFilter() const override
62 {
63 return "adbe.pkcs7.detached";
64 }
65
66 string GetSignatureType() const override
67 {
68 return "Sig";
69 }
70
71 private:
72 charbuff m_buffer;
73 X509* m_cert;
74 EVP_PKEY* m_pkey;
75 const EVP_MD* m_digest;
76 };
77
78 static int print_errors_string(const char* str, size_t len, void* u)
79 {
80 string* pstr = reinterpret_cast<string*>(u);
81
82 if (!pstr || !len || !str)
83 return 0;
84
85 if (!pstr->empty() && (*pstr)[pstr->length() - 1] != '\n')
86 *pstr += "\n";
87
88 *pstr += string(str, len);
89
90 // to continue
91 return 1;
92 }
93
94 static void raise_podofo_error_with_opensslerror(const char* detail)
95 {
96 string err;
97
98 ERR_print_errors_cb(print_errors_string, &err);
99
100 if (err.empty())
101 err = "Unknown OpenSSL error";
102
103 err = ": " + err;
104 err = detail + err;
105
106 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidHandle, err.c_str());
107 }
108
109 static int pkey_password_cb(char* buf, int bufsize, int rwflag, void* userdata)
110 {
111 (void)rwflag;
112 const char* password = reinterpret_cast<const char*>(userdata);
113
114 if (!password)
115 return 0;
116
117 int res = (int)strlen(password);
118
119 if (res > bufsize)
120 res = bufsize;
121
122 memcpy(buf, password, res);
123
124 return res;
125 }
126
127 static bool load_cert_and_key(const char* certfile, const char* pkeyfile, const char* pkey_password, X509** out_cert, EVP_PKEY** out_pkey)
128 {
129 if (!certfile || !*certfile)
130 {
131 cerr << "Certificate file not specified" << endl;
132 return false;
133 }
134
135 if (!pkeyfile || !*pkeyfile)
136 {
137 cerr << "Private key file not specified" << endl;
138 return false;
139 }
140
141 // should not happen, but let's be paranoid
142 if (!out_cert || !out_pkey)
143 {
144 cerr << "Invalid call of load_cert_and_key" << endl;
145 return false;
146 }
147
148 FILE* fp;
149
150 fp = fopen(certfile, "rb");
151
152 if (!fp)
153 {
154 cerr << "Failed to open certificate file '" << certfile << "'" << endl;
155 return false;
156 }
157
158 *out_cert = PEM_read_X509(fp, NULL, NULL, NULL);
159
160 fclose(fp);
161
162 if (!*out_cert)
163 {
164 cerr << "Failed to decode certificate file '" << certfile << "'" << endl;
165 string err;
166
167 ERR_print_errors_cb(print_errors_string, &err);
168
169 if (!err.empty())
170 cerr << err.c_str() << endl;
171
172 return false;
173 }
174
175 fp = fopen(pkeyfile, "rb");
176
177 if (!fp)
178 {
179 X509_free(*out_cert);
180 *out_cert = NULL;
181
182 cerr << "Failed to private key file '" << pkeyfile << "'" << endl;
183 return false;
184 }
185
186 *out_pkey = PEM_read_PrivateKey(fp, NULL, pkey_password_cb, const_cast<char*>(pkey_password));
187
188 fclose(fp);
189
190 if (!*out_pkey)
191 {
192 X509_free(*out_cert);
193 *out_cert = NULL;
194
195 cerr << "Failed to decode private key file '" << pkeyfile << "'" << endl;
196 string err;
197
198 ERR_print_errors_cb(print_errors_string, &err);
199
200 if (!err.empty())
201 cerr << err.c_str() << endl;
202
203 return false;
204 }
205
206 return true;
207 }
208
209 static void print_help(bool bOnlyUsage)
210 {
211 if (!bOnlyUsage)
212 {
213 cout << "Digitally signs existing PDF file with the given certificate and private key." << endl;
214 }
215
216 cout << endl;
217 cout << "Usage: podofosign [arguments]" << endl;
218 cout << "The required arguments:" << endl;
219 cout << " -in [inputfile] ... an input file to sign; if no -out is set, updates the input file" << endl;
220 cout << " -cert [certfile] ... a file with a PEM-encoded certificate to include in the document" << endl;
221 cout << " -pkey [pkeyfile] ... a file with a PEM-encoded private key to sign the document with" << endl;
222 cout << "The optional arguments:" << endl;
223 cout << " -out [outputfile] ... an output file to save the signed document to; cannot be the same as the input file" << endl;
224 cout << " -password [password] ... a password to unlock the private key file" << endl;
225 cout << " -digest [name] ... a digest name to use for the signature; default is SHA512" << endl;
226 cout << " -reason [utf8-string] ... a UTF-8 encoded string with the reason of the signature; default reason is \"I agree\"" << endl;
227 cout << " -sigsize [size] ... how many bytes to allocate for the signature; the default is derived from the certificate and private key file size" << endl;
228 cout << " -field-name [name] ... field name to use; defaults to 'PoDoFoSignatureFieldXXX', where XXX is the object number" << endl;
229 cout << " -field-use-existing ... whether to use existing signature field, if such named exists; the field type should be a signature" << endl;
230 cout << " -annot-units [mm|inch] ... set units for the annotation positions; default is mm" << endl;
231 cout << " -annot-position [page,left,top,width,height] ... where to place the annotation" << endl;
232 cout << " page ... a 1-based page index (integer), where '1' means the first page, '2' the second, and so on" << endl;
233 cout << " left,top,width,height ... a rectangle (in annot-units) where to place the annotation on the page (double)" << endl;
234 cout << " -annot-print ... use that to have the annotation printable, otherwise it's not printed (the default is not to print it)" << endl;
235 cout << " -annot-font [size,rrggbb,name] ... sets a font for the following annot-text; default is \"5,000000,Helvetica\" in mm" << endl;
236 cout << " size ... the font size, in annot-units" << endl;
237 cout << " rrggbb ... the font color, where rr is for red, gg for green and bb for blue, all two-digit hexa values between 00 and ff" << endl;
238 cout << " name ... the font name to use; if a Base14 font is recognized, then it is used, instead of embedding a new font" << endl;
239 cout << " -annot-text [left,top,utf8-string] ... a UTF-8 encoded string to add to the annotation" << endl;
240 cout << " left,top ... the position (in annot-units, relative to annot-position) where to place the text (double)" << endl;
241 cout << " text ... the actual UTF-8 encoded string to add to the annotation" << endl;
242 cout << " -annot-image [left,top,width,height,filename] ... an image to add to the annotation" << endl;
243 cout << " left,top,width,height ... a rectangle (in annot-units) where to place the image (double), relative to annot-position" << endl;
244 cout << " filename ... a filname of the image to add" << endl;
245 cout << "The annotation arguments can be repeated, except of the -annot-position and -annot-print, which can appear up to once." << endl;
246 cout << "The -annot-print, -annot-font, -annot-text and -annot-image can appear only after -annot-position." << endl;
247 cout << "All the left,top positions are treated with 0,0 being at the left-top of the page." << endl;
248 cout << "No drawing is done when using existing field." << endl;
249 }
250
251 static float convert_to_pdf_units(const string_view& annot_units, float value)
252 {
253 if (annot_units == "mm")
254 {
255 return 72.f * value / 25.4f;
256 }
257 else if (annot_units == "inch")
258 {
259 return 72.f * value;
260 }
261 else
262 {
263 string err = "Unknown annotation unit '";
264 err += annot_units;
265 err += "'";
266
267 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidEnumValue, err);
268 }
269 }
270
271 static bool parse_annot_position(const string_view& annot_position,
272 const string_view& annot_units,
273 int& annot_page,
274 double& annot_left,
275 double& annot_top,
276 double& annot_width,
277 double& annot_height)
278 {
279 float fLeft, fTop, fWidth, fHeight;
280
281 if (sscanf(annot_position.data(), "%d,%f,%f,%f,%f", &annot_page, &fLeft, &fTop, &fWidth, &fHeight) != 5)
282 {
283 return false;
284 }
285
286 annot_left = convert_to_pdf_units(annot_units, fLeft);
287 annot_top = convert_to_pdf_units(annot_units, fTop);
288 annot_width = convert_to_pdf_units(annot_units, fWidth);
289 annot_height = convert_to_pdf_units(annot_units, fHeight);
290
291 if (annot_page < 1)
292 return false;
293
294 annot_page--;
295
296 return true;
297 }
298
299 static const char* skip_commas(const string_view& text, int ncommas)
300 {
301 if (text.empty())
302 {
303 PODOFO_RAISE_ERROR(PdfErrorCode::InvalidHandle);
304 }
305
306 const char* res = text.data();
307
308 while (*res != '\0' && ncommas > 0)
309 {
310 if (*res == ',')
311 ncommas--;
312
313 res++;
314 }
315
316 if (ncommas > 0)
317 {
318 string err = "The text '";
319 err += text;
320 err += "' does not conform to the specified format (no enougt commas)";
321 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidDataType, err.c_str());
322 }
323
324 return res;
325 }
326
327 static void draw_annotation(PdfDocument& document,
328 PdfPainter& painter,
329 const cspan<string_view>& args,
330 const Rect& annot_rect)
331 {
332 string_view annot_units = "mm";
333 double font_size = convert_to_pdf_units("mm", 5.0);
334 PdfColor font_color(0.0, 0.0, 0.0);
335 const char* font_name = "Helvetica";
336 bool updateFont = true;
337 for (unsigned i = 1; i < args.size(); i++)
338 {
339 if (args[i] == "-annot-units")
340 {
341 annot_units = args[i + 1];
342 }
343 else if (args[i] == "-annot-font")
344 {
345 float fSize;
346 int rr, gg, bb;
347
348 if (sscanf(args[i + 1].data(), "%f,%02x%02x%02x,", &fSize, &rr, &gg, &bb) != 4)
349 {
350 string err = "The value for -annot-font '";
351 err += args[i + 1];
352 err += "' doesn't conform to format 'size,rrggbb,name'";
353
354 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidDataType, err.c_str());
355 }
356
357 font_size = convert_to_pdf_units(annot_units, fSize);
358 font_color = PdfColor(static_cast<double>(rr) / 255.0, static_cast<double>(gg) / 255.0, static_cast<double>(bb) / 255.0);
359 font_name = skip_commas(args[i + 1], 2);
360 updateFont = true;
361 }
362 else if (args[i] == "-annot-text")
363 {
364 float left, top;
365
366 if (sscanf(args[i + 1].data(), "%f,%f,", &left, &top) != 2)
367 {
368 string err = "The value for -annot-text '";
369 err += args[i + 1];
370 err += "' doesn't conform to format 'left,top,text'";
371
372 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidDataType, err.c_str());
373 }
374
375 const char* text = skip_commas(args[i + 1], 2);
376
377 if (updateFont)
378 {
379 PdfFont* font;
380
381 font = document.GetFonts().SearchFont(font_name);
382 if (!font)
383 {
384 string err = "Failed to create font '";
385 err += font_name;
386 err += "'";
387
388 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::OutOfMemory, err.c_str());
389 }
390
391 painter.TextState.SetFont(*font, font_size);
392 painter.GraphicsState.SetStrokeColor(font_color);
393 }
394
395 left = convert_to_pdf_units(annot_units, left);
396 top = convert_to_pdf_units(annot_units, top);
397
398 painter.DrawTextMultiLine(text, left,
399 0.0,
400 annot_rect.Width - left,
401 annot_rect.Height - top);
402 }
403 else if (args[i] == "-annot-image")
404 {
405 float left, top, width, height;
406
407 if (sscanf(args[i + 1].data(), "%f,%f,%f,%f,", &left, &top, &width, &height) != 4)
408 {
409 string err = "The value for -annot-image '";
410 err += args[i + 1];
411 err += "' doesn't conform to format 'left,top,width,height,filename'";
412
413 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidDataType, err.c_str());
414 }
415
416 const char* filename = skip_commas(args[i + 1], 4);
417
418 left = convert_to_pdf_units(annot_units, left);
419 top = convert_to_pdf_units(annot_units, top);
420 width = convert_to_pdf_units(annot_units, width);
421 height = convert_to_pdf_units(annot_units, height);
422
423 auto image = document.CreateImage();
424 image->Load(filename);
425
426 double dScaleX = left / image->GetWidth();
427 double dScaleY = height / image->GetHeight();
428
429 painter.DrawImage(*image, left, annot_rect.Height - top - height, dScaleX, dScaleY);
430 }
431
432 // these are the only parameters without additional value
433 if (args[i] != "-annot-print" &&
434 args[i] != "-field-use-existing")
435 {
436 i++;
437 }
438 }
439 }
440
441 static PdfObject* find_existing_signature_field(PdfAcroForm& acroForm, const PdfString& name)
442 {
443 PdfObject* fields = acroForm.GetObject().GetDictionary().GetKey("Fields");
444 if (fields)
445 {
446 if (fields->GetDataType() == PdfDataType::Reference)
447 fields = acroForm.GetDocument().GetObjects().GetObject(fields->GetReference());
448
449 if (fields && fields->GetDataType() == PdfDataType::Array)
450 {
451 PdfArray& rArray = fields->GetArray();
452 PdfArray::iterator it, end = rArray.end();
453 for (it = rArray.begin(); it != end; it++)
454 {
455 // require references in the Fields array
456 if (it->GetDataType() == PdfDataType::Reference)
457 {
458 PdfObject* item = acroForm.GetDocument().GetObjects().GetObject(it->GetReference());
459
460 if (item && item->GetDictionary().HasKey("T") &&
461 item->GetDictionary().GetKey("T")->GetString() == name)
462 {
463 // found a field with the same name
464 const PdfObject* ft = item->GetDictionary().GetKey("FT");
465 if (!ft && item->GetDictionary().HasKey("Parent"))
466 {
467 const PdfObject* temp = item->GetDictionary().FindKey("Parent");
468 if (!temp)
469 {
470 PODOFO_RAISE_ERROR(PdfErrorCode::InvalidDataType);
471 }
472
473 ft = temp->GetDictionary().GetKey("FT");
474 }
475
476 if (!ft)
477 {
478 PODOFO_RAISE_ERROR(PdfErrorCode::NoObject);
479 }
480
481 const PdfName fieldType = ft->GetName();
482 if (fieldType != "Sig")
483 {
484 string err = "Existing field '";
485 err += name.GetString();
486 err += "' isn't of a signature type, but '";
487 err += fieldType.GetString();
488 err += "' instead";
489
490 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidName, err.c_str());
491 }
492
493 return item;
494 }
495 }
496 }
497 }
498 }
499
500 return NULL;
501 }
502
503 #if 0 /* TODO */
504 static void update_default_appearance_streams(PdfAcroForm* pAcroForm)
505 {
506 if (!pAcroForm ||
507 !pAcroForm->GetObject()->GetDictionary().HasKey("Fields") ||
508 pAcroForm->GetObject()->GetDictionary().GetKey("Fields")->GetDataType() != PdfDataType::Array)
509 return;
510
511 PdfArray& rFields = pAcroForm->GetObject()->GetDictionary().GetKey("Fields")->GetArray();
512
513 PdfArray::iterator it, end = rFields.end();
514 for (it = rFields.begin(); it != end; it++)
515 {
516 if (it->GetDataType() == PdfDataType::Reference)
517 {
518 PdfObject* pObject = pAcroForm->GetDocument()->GetObjects()->GetObject(it->GetReference());
519 if (!pObject || pObject->GetDataType() != PdfDataType::Dictionary)
520 continue;
521
522 PdfDictionary& rFielDict = pObject->GetDictionary();
523 if (rFielDict.HasKey("FT") &&
524 rFielDict.GetKey("FT")->GetDataType() == PdfDataType::Name &&
525 (rFielDict.GetKey("FT")->GetName() == "Tx" || rFielDict.GetKey("FT")->GetName() == "Ch"))
526 {
527 PdfString rDA, rV, rDV;
528
529 if (rFielDict.HasKey("V") &&
530 (rFielDict.GetKey("V")->GetDataType() == PdfDataType::String || rFielDict.GetKey("V")->GetDataType() == PdfDataType::HexString))
531 {
532 rV = rFielDict.GetKey("V")->GetString();
533 }
534
535 if (rFielDict.HasKey("DV") &&
536 (rFielDict.GetKey("DV")->GetDataType() == PdfDataType::String || rFielDict.GetKey("DV")->GetDataType() == PdfDataType::HexString))
537 {
538 rDV = rFielDict.GetKey("DV")->GetString();
539 }
540
541 if (rV.IsValid() && rV.GetCharacterLength() > 0)
542 {
543 rDV = rV;
544 }
545
546 if (!rDV.IsValid() || rDV.GetCharacterLength() <= 0)
547 continue;
548
549 if (rDV.GetLength() >= 2 && rDV.GetString()[0] == static_cast<char>(0xFE) && rDV.GetString()[1] == static_cast<char>(0xFF))
550 {
551 if (rDV.GetLength() == 2)
552 continue;
553 }
554
555 if (rFielDict.HasKey("DA") &&
556 rFielDict.GetKey("DA")->GetDataType() == PdfDataType::String)
557 {
558 rDA = rFielDict.GetKey("DA")->GetString();
559 }
560
561 if (rFielDict.HasKey("AP") &&
562 rFielDict.GetKey("AP")->GetDataType() == PdfDataType::Dictionary &&
563 rFielDict.GetKey("AP")->GetDictionary().HasKey("N") &&
564 rFielDict.GetKey("AP")->GetDictionary().GetKey("N")->GetDataType() == PdfDataType::Reference)
565 {
566 pObject = pAcroForm->GetDocument()->GetObjects()->GetObject(rFielDict.GetKey("AP")->GetDictionary().GetKey("N")->GetReference());
567 if (pObject->GetDataType() == PdfDataType::Dictionary &&
568 pObject->GetDictionary().HasKey("Type") &&
569 pObject->GetDictionary().GetKey("Type")->GetDataType() == PdfDataType::Name &&
570 pObject->GetDictionary().GetKey("Type")->GetName() == "XObject")
571 {
572 PdfXObject xObject(pObject);
573 PdfStream* pCanvas = xObject.GetContentsForAppending()->GetStream();
574
575 if (rFielDict.GetKey("FT")->GetName() == "Tx")
576 {
577 pCanvas->BeginAppend(true);
578
579 PdfRefCountedBuffer rBuffer;
580 PdfOutputDevice rOutputDevice(&rBuffer);
581
582 rDV.Write(&rOutputDevice, ePdfWriteMode_Compact);
583
584 ostringstream oss;
585
586 oss << "/Tx BMC" << endl;
587 oss << "BT" << endl;
588 if (rDA.IsValid())
589 oss << rDA.GetString() << endl;
590 oss << "2.0 2.0 Td" << endl;
591 oss << rBuffer.GetBuffer() << " Tj" << endl;
592 oss << "ET" << endl;
593 oss << "EMC" << endl;
594
595 pCanvas->Append(oss.str());
596
597 pCanvas->EndAppend();
598 }
599 else if (rFielDict.GetKey("FT")->GetName() == "Ch")
600 {
601 }
602 }
603 }
604 }
605 }
606 }
607 }
608 #endif
609
610 void Main(const cspan<string_view>& args)
611 {
612 string_view inputfile;
613 string_view outputfile;
614 string_view certfile;
615 string_view pkeyfile;
616 string_view password;
617 string_view digest;
618 string_view reason = "I agree";
619 string_view sigsizestr;
620 string_view annot_units = "mm";
621 string_view annot_position;
622 string_view field_name;
623 int annot_page = 0;
624 double annot_left = 0.0, annot_top = 0.0, annot_width = 0.0, annot_height = 0.0;
625 bool annot_print = false;
626 bool field_use_existing = false;
627
628 PdfCommon::SetMaxLoggingSeverity(PdfLogSeverity::None);
629
630 for (unsigned i = 1; i < args.size(); i++)
631 {
632 string_view* value = nullptr;
633
634 if (args[i] == "-in")
635 {
636 value = &inputfile;
637 }
638 else if (args[i] == "-out")
639 {
640 value = &outputfile;
641 }
642 else if (args[i] == "-cert")
643 {
644 value = &certfile;
645 }
646 else if (args[i] == "-pkey")
647 {
648 value = &pkeyfile;
649 }
650 else if (args[i] == "-digest")
651 {
652 value = &digest;
653 }
654 else if (args[i] == "-password")
655 {
656 value = &password;
657 }
658 else if (args[i] == "-reason")
659 {
660 value = &reason;
661 }
662 else if (args[i] == "-sigsize")
663 {
664 value = &sigsizestr;
665 }
666 else if (args[i] == "-annot-units")
667 {
668 value = &annot_units;
669 }
670 else if (args[i] == "-annot-position")
671 {
672 if (!annot_position.empty())
673 {
674 cerr << "Only one -annot-position can be specified" << endl;
675 exit(-1);
676 }
677
678 value = &annot_position;
679 }
680 else if (args[i] == "-annot-print")
681 {
682 if (annot_position.empty())
683 {
684 cerr << "Missing -annot-position argument, which should be defined before '" << args[i] << "'" << endl;
685 exit(-2);
686 }
687
688 if (annot_print)
689 {
690 cerr << "Only one -annot-print can be specified" << endl;
691 exit(-1);
692 }
693
694 annot_print = !annot_print;
695 continue;
696 }
697 else if (args[i] == "-annot-font" ||
698 args[i] == "-annot-text" ||
699 args[i] == "-annot-image")
700 {
701 if (annot_position.empty())
702 {
703 cerr << "Missing -annot-position argument, which should be defined before '" << args[i] << "'" << endl;
704 exit(-2);
705 }
706 // value is left NULL, these are parsed later
707 }
708 else if (args[i] == "-field-name")
709 {
710 value = &field_name;
711 }
712 else if (args[i] == "-field-use-existing")
713 {
714 if (field_use_existing)
715 {
716 cerr << "Only one -field-use-existing can be specified" << endl;
717 exit(-1);
718 }
719
720 field_use_existing = !field_use_existing;
721 continue;
722 }
723 else
724 {
725 cerr << "Unknown argument '" << args[i] << "'" << endl;
726 print_help(true);
727 exit(-3);
728 }
729
730 if (i + 1 >= args.size())
731 {
732 cerr << "Missing value for argument '" << args[i] << "'" << endl;
733 print_help(true);
734 exit(-4);
735 }
736
737 if (value)
738 {
739 *value = args[i + 1];
740
741 if (*value == annot_units && annot_units != "mm" && annot_units != "inch")
742 {
743 cerr << "Invalid -annot-units value '" << *value << "', only 'mm' and 'inch' are supported" << endl;
744 exit(-5);
745 }
746
747 try
748 {
749 if (*value == annot_position && !parse_annot_position(annot_position, annot_units, annot_page, annot_left, annot_top, annot_width, annot_height))
750 {
751 cerr << "Invalid -annot-position value '" << *value << "', expected format \"page,left,top,width,height\"" << endl;
752 exit(-6);
753 }
754 }
755 catch (...)
756 {
757 cerr << "Invalid -annot-position value '" << *value << "', expected format \"page,left,top,width,height\"" << endl;
758 exit(-6);
759 }
760 }
761 i++;
762 }
763
764 if (inputfile.empty() || certfile.empty() || pkeyfile.empty())
765 {
766 if (args.size() != 1)
767 cerr << "Not all required arguments specified." << endl;
768
769 print_help(true);
770
771 exit(-7);
772 }
773
774 int sigsize = -1;
775
776 if (!sigsizestr.empty())
777 {
778 sigsize = atoi(sigsizestr.data());
779
780 if (sigsize <= 0)
781 {
782 cerr << "Invalid value for signature size specified (" << sigsizestr << "), use a positive integer, please" << endl;
783 exit(-8);
784 }
785 }
786
787 if (!outputfile.empty() && outputfile == inputfile)
788 {
789 // even I told you not to do it, you still specify the same output file
790 // as the input file. Just ignore that.
791 outputfile = { };
792 }
793
794 OPENSSL_init_crypto(0, NULL);
795
796 X509* cert = NULL;
797 EVP_PKEY* pkey = NULL;
798 if (!load_cert_and_key(certfile.data(), pkeyfile.data(), password.data(), &cert, &pkey))
799 {
800 exit(-9);
801 }
802
803 PdfSignature* signature = NULL;
804
805 const EVP_MD* md_digest;
806
807 if (!digest.empty())
808 {
809 md_digest = EVP_get_digestbyname(digest.data());
810 if (!md_digest)
811 {
812 string err = "Unknown digest '";
813 err += digest;
814 err += "'";
815 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::InvalidName, err.c_str());
816 }
817 }
818 else
819 {
820 md_digest = EVP_sha512();
821 if (!md_digest)
822 cerr << "Cannot get SHA512 digest, using default OpenSSL digest instead." << endl;
823 }
824
825 PdfMemDocument document;
826
827 document.Load(inputfile);
828
829 if (!document.GetPages().GetCount())
830 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::PageNotFound, "The document has no page. Only documents with at least one page can be signed");
831
832 auto& acroForm = document.GetOrCreateAcroForm();
833 if (!acroForm.GetObject().GetDictionary().HasKey("SigFlags") ||
834 !acroForm.GetObject().GetDictionary().MustGetKey("SigFlags").IsNumber() ||
835 acroForm.GetObject().GetDictionary().FindKeyAsSafe<int64_t>("SigFlags") != 3)
836 {
837 if (acroForm.GetObject().GetDictionary().HasKey("SigFlags"))
838 acroForm.GetObject().GetDictionary().RemoveKey("SigFlags");
839
840 int64_t val = 3;
841 acroForm.GetObject().GetDictionary().AddKey("SigFlags", val);
842 }
843
844 if (acroForm.GetNeedAppearances())
845 {
846 #if 0 /* TODO */
847 update_default_appearance_streams(pAcroForm);
848 #endif
849
850 acroForm.SetNeedAppearances(false);
851 }
852
853 PdfString name;
854 PdfObject* existingSigField = NULL;
855
856 if (!field_name.empty())
857 {
858 name = PdfString(field_name);
859
860 existingSigField = find_existing_signature_field(acroForm, name);
861 if (existingSigField && !field_use_existing)
862 {
863 string err = "Signature field named '";
864 err += name.GetString();
865 err += "' already exists";
866
867 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::WrongDestinationType, err.c_str());
868 }
869 }
870 else
871 {
872 char fldName[96]; // use bigger buffer to make sure sprintf does not overflow
873 sprintf(fldName, "PodofoSignatureField%u", document.GetObjects().GetObjectCount());
874
875 name = PdfString(fldName);
876 }
877
878 if (existingSigField)
879 {
880 if (!existingSigField->GetDictionary().HasKey("P"))
881 {
882 string err = "Signature field named '";
883 err += name.GetString();
884 err += "' doesn't have a page reference";
885
886 PODOFO_RAISE_ERROR_INFO(PdfErrorCode::PageNotFound, err.c_str());
887 }
888
889 auto& page = document.GetPages().GetPage(existingSigField->GetDictionary().GetKey("P")->GetReference());
890 signature = &static_cast<PdfSignature&>(
891 static_cast<PdfAnnotationWidget&>(page.GetAnnotations().GetAnnot(existingSigField->GetIndirectReference())).GetField());
892 signature->EnsureValueObject();
893 }
894 else
895 {
896 auto& page = document.GetPages().GetPageAt(annot_page);
897 Rect annot_rect;
898 if (!annot_position.empty())
899 {
900 annot_rect = Rect(annot_left, page.GetMediaBox().Height - annot_top - annot_height, annot_width, annot_height);
901 }
902
903 signature = &page.CreateField<PdfSignature>(name, annot_rect);
904 if (!annot_position.empty() && annot_print)
905 signature->MustGetWidget().SetFlags(PdfAnnotationFlags::Print);
906 else if (annot_position.empty() && (field_name.empty() || !field_use_existing))
907 signature->MustGetWidget().SetFlags(PdfAnnotationFlags::Invisible | PdfAnnotationFlags::Hidden);
908
909 if (!annot_position.empty())
910 {
911 Rect annotSize(0.0, 0.0, annot_rect.Width, annot_rect.Height);
912 auto sigXObject = document.CreateXObjectForm(annotSize);
913 PdfPainter painter;
914
915 try
916 {
917 painter.SetCanvas(*sigXObject);
918
919 /* Workaround Adobe's reader error 'Expected a dict object.' when the stream
920 contains only one object which does Save()/Restore() on its own, like
921 the image XObject. */
922 painter.Save();
923 painter.Restore();
924
925 draw_annotation(document, painter, args, annot_rect);
926
927 signature->SetAppearanceStream(*sigXObject);
928 }
929 catch (...)
930 {
931 }
932
933 painter.FinishDrawing();
934 }
935 }
936
937 signature->SetSignatureReason(PdfString(reason));
938 signature->SetSignatureDate(PdfDate());
939
940 MySigner signer(cert, pkey, md_digest);
941
942 FileStreamDevice device(outputfile.empty() ? inputfile : outputfile, FileMode::Open, DeviceAccess::Write);
943
944 PoDoFo::SignDocument(document, device, signer, *signature);
945
946 if (pkey)
947 EVP_PKEY_free(pkey);
948
949 if (cert)
950 X509_free(cert);
951 }
952
953 // TODO: Optmize so the process is buffered
954 void MySigner::ComputeSignature(charbuff& buffer, bool dryrun)
955 {
956 (void)dryrun;
957 int rc;
958 BIO* mem = BIO_new(BIO_s_mem());
959 if (!mem)
960 raise_podofo_error_with_opensslerror("Failed to create input BIO");
961
962 unsigned int flags = PKCS7_DETACHED | PKCS7_BINARY;
963 PKCS7* pkcs7 = PKCS7_sign(m_cert, m_pkey, NULL, mem, flags | PKCS7_PARTIAL);
964 if (!pkcs7)
965 {
966 BIO_free(mem);
967 raise_podofo_error_with_opensslerror("PKCS7_sign failed");
968 }
969
970 if (!PKCS7_sign_add_signer(pkcs7, m_cert, m_pkey, m_digest, 0))
971 {
972 BIO_free(mem);
973 PKCS7_free(pkcs7);
974 raise_podofo_error_with_opensslerror("PKCS7_sign_add_signer failed");
975 }
976
977 rc = BIO_write(mem, m_buffer.data(), (int)m_buffer.size());
978 if (rc != (int)m_buffer.size())
979 {
980 PKCS7_free(pkcs7);
981 BIO_free(mem);
982 raise_podofo_error_with_opensslerror("BIO_write failed");
983 }
984
985 if (PKCS7_final(pkcs7, mem, flags) <= 0)
986 {
987 PKCS7_free(pkcs7);
988 BIO_free(mem);
989 raise_podofo_error_with_opensslerror("PKCS7_final failed");
990 }
991
992 BIO* out = BIO_new(BIO_s_mem());
993 if (!out)
994 {
995 PKCS7_free(pkcs7);
996 BIO_free(mem);
997 raise_podofo_error_with_opensslerror("Failed to create output BIO");
998 }
999
1000 char* outBuff = NULL;
1001 long outLen;
1002
1003 i2d_PKCS7_bio(out, pkcs7);
1004
1005 outLen = BIO_get_mem_data(out, &outBuff);
1006
1007 buffer.resize(outLen);
1008 std::memcpy(buffer.data(), outBuff, outLen);
1009
1010 PKCS7_free(pkcs7);
1011 BIO_free(out);
1012 BIO_free(mem);
1013 }