Sign.pm

filter: Statementstmt 39.0% 168 / 430 Branchbran 20.4% 38 / 186 Conditioncond 13.3% 4 / 30 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 69.5% 16 / 23 Podpod 81.8% 9 / 11 totaltotal 33.6% 235 / 698 CC 105 SCAR 64.8
CC
105
Cov
33%
verify_signatures
1892.0
tsa_fetch
56.0
prepare_file
36.0
CRAP 653.9
↑ Summary example.pl »
1 package PDF::Sign;
2 #
3 # Originally inspired by Martin Schuette <info@mschuette.name> (2012)
4 # https://mschuette.name/files/pdfsign.pl
5 # BSD 2-Clause License — retained below as required
6 #
7 # Imported for study and proof of concept: Massimiliano Citterio (2019)
8 # Substantially rewritten and extended by Massimiliano Citterio (2023-2026)
9 # - Refactored into reusable subs (prepare_file, sign_file, prepare_ts, ts_file)
10 # - RFC3161 TSA timestamp support (ETSI.RFC3161 / DocTimeStamp)
11 # - OpenSSL 1.x/3.x + LibreSSL compatibility (CAdES, ETSI.CAdES.detached)
12 # - Visible signature widget with appearance stream
13 # - Certificate chain support (-certfile)
14 # - Cross-platform timezone handling (Linux / Windows)
15 # - Process-safe temp files (PID in filename)
16 # - openssl cms replacing smime+sed pipeline
17 # - PDF32000-2008 12.8.1 compliant ByteRange implementation
18 # - curl/LWP::UserAgent fallback for TSA requests
19 #
20 # @copyright (c) Citterio Massimiliano, Perl License (GPL/Artistic)
21 #
22 # --- BSD 2-Clause License (Martin Schuette, 2012) ---
23 # Copyright (c) 2012, Martin Schuette <info@mschuette.name>
24 # All rights reserved.
25 #
26 # Redistribution and use in source and binary forms, with or without
27 # modification, are permitted provided that the following conditions are met:
28 #
29 # 1. Redistributions of source code must retain the above copyright notice,
30 # this list of conditions and the following disclaimer.
31 # 2. Redistributions in binary form must reproduce the above copyright notice,
32 # this list of conditions and the following disclaimer in the documentation
33 # and/or other materials provided with the distribution.
34 #
35 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
39 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
41 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
42 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
43 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 # --- end BSD 2-Clause License ---
46  
47 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 4 ▶no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
49 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 4 ▶use 5.016;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 4 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
53 4 ▶use Cwd qw(getcwd);
Subroutine BEGIN: called CC=1 SCAR=0.0
54 4 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
55 4 ▶use MIME::Base64 qw(decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
56 4 ▶use File::Slurp qw(write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
57 # Crypt::OpenSSL::X509 intentionally not used — XS dependency with
58 # known installation issues on macOS (missing OpenSSL headers).
59 # Subject name extracted via openssl binary instead.
60  
61 # PDF backend: PDF::API2 or PDF::Builder
62 4 my $PDF_BACKEND;
63 BEGIN {
64 4 ▶ if (eval { require PDF::API2; PDF::API2->import(); 1 }) {
Subroutine BEGIN: called CC=3 SCAR=15.1
Branch: 2 branches
BranchTrueFalseTotal
if (eval { do { require PDF::API2; 'PDF::API2'->import; 1 } }) { } 4 0 4
elsif (eval { do { require PDF::Builder; 'PDF::Builder'->import; 1 } }) { } 0 0 0
65 4 $PDF_BACKEND = 'PDF::API2';
66 4 require PDF::API2::Basic::PDF::Utils;
67 4 PDF::API2::Basic::PDF::Utils->import();
68 0 } elsif (eval { require PDF::Builder; PDF::Builder->import(); 1 }) {
69 0 $PDF_BACKEND = 'PDF::Builder';
70 0 require PDF::Builder::Basic::PDF::Utils;
71 0 PDF::Builder::Basic::PDF::Utils->import();
72
73 } else {
74 0 die "PDF::Sign requires PDF::API2 or PDF::Builder\n";
75 }
76 sub PDFLiteral {
77 3 ▶ if ($PDF_BACKEND eq 'PDF::API2'){
Subroutine PDFLiteral: called CC=3 SCAR=16.5
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if ($PDF_BACKEND eq "PDF::API2") 3 0 3
78 3 return PDF::API2::Basic::PDF::Literal->new(@_);
79 }
80 0 ▶ if ($PDF_BACKEND eq 'PDF::Builder'){
Branch: 1 branch
BranchTrueFalseTotal
if ($PDF_BACKEND eq "PDF::Builder") 0 0 0
81 0 return PDF::Builder::Basic::PDF::Literal->new(@_);
82 }
83 }
84 sub PDFForm {
85 0 ▶ if ($PDF_BACKEND eq 'PDF::API2'){
Subroutine PDFForm: not called CC=3 SCAR=24.8
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if ($PDF_BACKEND eq "PDF::API2") 0 0 0
86 0 return PDF::API2::Resource::XObject::Form->new(@_);
87 }
88 0 ▶ if ($PDF_BACKEND eq 'PDF::Builder'){
Branch: 1 branch
BranchTrueFalseTotal
if ($PDF_BACKEND eq "PDF::Builder") 0 0 0
89 0 return PDF::Builder::Resource::XObject::Form->new(@_);
90 }
91 }
92 }
93  
94 # LWP fallback detection (curl preferred)
95 4 my $HAS_LWP = eval { require LWP::UserAgent; 1 };
96  
97 4 our $VERSION = '0.01';
98  
99 4 our @EXPORT_OK = qw(
100 config
101 prepare_file
102 sign_file
103 prepare_ts
104 ts_file
105 cms_sign
106 ts_query
107 tsa_fetch
108 );
109  
110 4 our %EXPORT_TAGS = (
111 sign => [qw(prepare_file sign_file cms_sign)],
112 ts => [qw(prepare_ts ts_file ts_query tsa_fetch)],
113 all => \@EXPORT_OK,
114 );
115  
116 # ============================================================
117 # Configuration — set these before calling any sub,
118 # or pass them as arguments where supported.
119 # All configurable via our() from the calling script.
120 # ============================================================
121 4 our $osslcmd = 'openssl';
122 4 our $x509_pem;
123 4 our $x509_chain;
124 4 our $privkey_pem;
125 4 our $tsaserver = 'http://timestamp.digicert.com';
126 4 our $tmpdir = getcwd();
127 4 ▶our $siglen = 1024 * ($PDF_BACKEND eq 'PDF::Builder' ? 8 : 8);
Branch: 1 branch
BranchTrueFalseTotal
$PDF_BACKEND eq 'PDF::Builder' ? : 0 4 4
128 4 our $debug = 0;
129  
130 4 my $zerorange = sprintf("0 %8d %8d %8d", 0, 0, 0);
131  
132 # detect openssl version and cms availability once at load time
133 4 my $osslv = do {
134 4 ▶ open(my $fh, '-|', $osslcmd, 'version')
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", $osslcmd, "version" or die "Cannot exec openssl: $!" 0 4 4
135 or die "Cannot exec openssl: $!";
136 4 my $v = do { local $/; <$fh> };
137 4 close $fh;
138 4 chomp $v;
139 4 $v;
140 };
141  
142 # cms command availability — LibreSSL 2.x and very old OpenSSL may lack it
143 # fallback to smime if cms is not available.
144 # Note: openssl cms -help writes to stderr, so we redirect stderr to stdout
145 # using shell=1 here intentionally — input is a fixed string, no injection risk
146 4 my $has_cms = do {
147 4 my $out = `$osslcmd cms -help 2>&1`;
148 4 ▶ $out =~ /Usage[\s:]{1,2}cms[\s\[]{1,2}options/i ? '1' : '';
Branch: 1 branch
BranchTrueFalseTotal
$out =~ /Usage[\s:]{1,2}cms[\s\[]{1,2}options/iu ? : 4 0 4
149 };
150  
151 # ============================================================
152 # sub: config
153 # Configure PDF::Sign settings in one call.
154 # Preferred over setting package variables directly.
155 # All keys are optional — only provided keys are updated.
156 #
157 # Example:
158 # PDF::Sign::config(
159 # osslcmd => '/usr/local/bin/openssl',
160 # x509_pem => '/path/to/cert.pem',
161 # x509_chain => '/path/to/chain.pem',
162 # privkey_pem => '/path/to/privkey.pem',
163 # tsaserver => 'http://timestamp.digicert.com',
164 # tmpdir => '/tmp',
165 # siglen => 6144,
166 # debug => 1,
167 # );
168 # ============================================================
169 sub config {
170 4 ▶ my (%args) = @_;
Subroutine config: called CC=12 SCAR=25.1
Pod documented
171  
172 4 ▶ $osslcmd = $args{osslcmd} if exists $args{osslcmd};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"osslcmd"} 2 2 4
173 4 ▶ $x509_pem = $args{x509_pem} if exists $args{x509_pem};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"x509_pem"} 2 2 4
174 4 ▶ $x509_chain = $args{x509_chain} if exists $args{x509_chain};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"x509_chain"} 0 4 4
175 4 ▶ $privkey_pem = $args{privkey_pem} if exists $args{privkey_pem};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"privkey_pem"} 2 2 4
176 4 ▶ $tsaserver = $args{tsaserver} if exists $args{tsaserver};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"tsaserver"} 0 4 4
177 4 ▶ $tmpdir = $args{tmpdir} if exists $args{tmpdir};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"tmpdir"} 2 2 4
178 4 ▶ $siglen = $args{siglen} if exists $args{siglen};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"siglen"} 0 4 4
179 4 ▶ $debug = $args{debug} if exists $args{debug};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"debug"} 2 2 4
180  
181 # re-detect openssl version and cms availability if osslcmd changed
182 4 ▶ if (exists $args{osslcmd}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"osslcmd"}) 2 2 4
183 2 ▶ open(my $fh, '-|', $osslcmd, 'version')
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", $PDF::Sign::osslcmd, "version" or die "Cannot exec openssl: $!" 0 2 2
184 or die "Cannot exec openssl: $!";
185 2 $osslv = do { local $/; <$fh> };
186 2 close $fh;
187 2 chomp $osslv;
188  
189 2 my $cms_out = `$osslcmd cms -help 2>&1`;
190 2 ▶ $has_cms = $cms_out =~ /Usage[\s:]{1,2}cms[\s\[]{1,2}options/i ? '1' : '';
Branch: 1 branch
BranchTrueFalseTotal
$cms_out =~ /Usage[\s:]{1,2}cms[\s\[]{1,2}options/iu ? : 2 0 2
191 }
192  
193 4 return 1;
194 }
195  
196 # ============================================================
197 # sub: prepare_file
198 # Prepares the PDF AcroForm structure for a CMS/CAdES signature.
199 # $presign = 1: visible signature widget on page 1
200 # $presign = 0: invisible signature field
201 # ============================================================
202 sub prepare_file {
203 1 ▶ my $pdf = $_[0];
Subroutine prepare_file: called CC=12 SCAR=35.8
Pod documented
204 1 my $p = $pdf->{'pdf'};
205 1 my $presign = $_[1];
206 1 ▶ my $reason = $_[2] // "Digitally signed document";
Condition50%1/2
$_[2] // "Digitally signed document"
l!l
01
MC/DC0%0/1
$_[2] // "Digitally signed document"
$_[2]
Truth table50%1/2
A
A= $_[2]
Aresult
11
00
207  
208 1 ▶ if (!(-e $privkey_pem && -e $x509_pem)) { return; }
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem) 0 1 1
Condition33%1/3
-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem
!ll&&!rl&&r
001
MC/DC0%0/2
-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem
-e $PDF::Sign::privkey_pem -e $PDF::Sign::x509_pem
Truth table33%1/3
A and B
A= -e $PDF::Sign::privkey_pemB= -e $PDF::Sign::x509_pem
ABresult
0X0
100
111
209  
210 1 my $sigdict = PDFDict();
211 1 $sigdict->{Type} = PDFName("Sig");
212 1 $sigdict->{Filter} = PDFName("Adobe.PPKLite");
213 1 $sigdict->{Reason} = PDFStr($reason);
214 1 $sigdict->{Name} = PDFStr(_cert_subject($x509_pem));
215  
216 1 ▶ if ($^O eq 'linux') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'linux') { } 1 0 1
217 1 $sigdict->{M} = PDFStr(substr(strftime("D:%Y%m%d%H%M%S%z", localtime), 0, 19) . "'00'");
218 } else {
219 0 my @lt = localtime;
220 0 ▶ my $tz = $lt[8] ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$lt[8] ? : 0 0 0
221 0 $sigdict->{M} = PDFStr(substr(strftime("D:%Y%m%d%H%M%S+0${tz}", localtime), 0, 19) . "'00'");
222 }
223  
224 # ETSI.CAdES.detached only with OpenSSL 3+
225 # LibreSSL (any version) and OpenSSL 1.x use adbe.pkcs7.detached
226 1 ▶ if ($osslv =~ /^OpenSSL 3/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($osslv =~ /^OpenSSL 3/u) { } 1 0 1
227 1 $sigdict->{SubFilter} = PDFName('ETSI.CAdES.detached');
228 } else {
229 0 $sigdict->{SubFilter} = PDFName('adbe.pkcs7.detached');
230 }
231  
232 1 $sigdict->{Contents} = PDFStrHex("\0" x $siglen);
233 1 $sigdict->{ByteRange} = PDFLiteral("[$zerorange]");
234 1 $sigdict = $p->new_obj($sigdict);
235  
236 1 my @formarray;
237 1 ▶ if ($presign) {
Branch: 1 branch
BranchTrueFalseTotal
if ($presign) { } 0 1 1
238 0 my $sigannotdict = $pdf->open_page(1)->annotation();
239 0 delete $sigannotdict->{Type};
240 0 $sigannotdict->{Subtype} = PDFName("Widget");
241 0 $sigannotdict->{F} = PDFNum(4 + 128); # + 128 + 256
242 0 $sigannotdict->{V} = $sigdict;
243 0 $sigannotdict->{FT} = PDFName("Sig");
244 0 $sigannotdict->{T} = PDFStr("Signature1");
245 0 delete $sigannotdict->{Border};
246  
247 0 my $ap = $sigannotdict->{AP} = PDFDict();
248 0 my $n0 = PDFForm($p);
249 0 $n0->bbox(0, 0, 150, 20);
250 0 my $frm = PDFForm($p);
251 0 $frm->bbox(0, 0, 150, 20);
252  
253 0 ▶ my ($s, $m, $h, $D, $M, $Y) = map { $_ = '0' . $_ if $_ < 9; $_ } localtime();
Branch: 1 branch
BranchTrueFalseTotal
if $_ < 9 0 0 0
254 0 ▶ $Y += 1900; $M += 1; $M = '0' . $M if $M < 9;
Branch: 1 branch
BranchTrueFalseTotal
if $M < 9 0 0 0
255 # 0 0 0 rg = Color Black, /F1 6 Tf = font1 size 6
256 # somehow buggy font selection on PDF::Builder
257 0 $frm->{' stream'} = "q\n0 0 0 rg\nBT 1 0 0 1 0 0 Tm /F1 6 Tf\n" .
258 "5 8 Td (Digitally signed D: $Y-$M-$D $h:$m:$s CET) Tj ET Q";
259 #$frm->{' stream'} = "q Q"; # debug: empty appearance
260 0 $frm->filter('FlateDecode');
261  
262 0 $ap->{N} = PDFForm($p);
263 0 $ap->{N}->bbox(0, 0, 150, 20);
264 0 $frm->resource('XObject', 'n0', $n0);
265 0 $ap->{N}->resource('XObject', 'FRM', $frm);
266 0 $ap->{N}->{' stream'} = "q 1 0 0 1 0 0 cm /FRM Do Q";
267 0 $ap->{N}->filter('FlateDecode');
268  
269 0 $sigannotdict->{Rect} = PDFLiteral("[25 6 175 26]");
270 0 ▶ if ($pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pdf->{'catalog'}{'Pages'}{'Kids'}{' val'}[0]{' objnum'}) { } 0 0 0
271 $sigannotdict->{P} = PDFLiteral(
272 0 $pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'} . " 0 R");
273 } else {
274 0 $sigannotdict->{P} = $pdf->open_page(1);
275 }
276 0 $sigannotdict = $p->new_obj($sigannotdict);
277 0 push @formarray, $sigannotdict;
278 } else {
279 1 my $sigformdict = PDFDict();
280 1 $sigformdict->{Type} = PDFName("Annot");
281 1 $sigformdict->{Subtype} = PDFName("Widget");
282 1 $sigformdict->{F} = PDFNum(4 + 128);
283 1 $sigformdict->{FT} = PDFName("Sig");
284 1 $sigformdict->{T} = PDFStr("Signature1");
285 1 $sigformdict->{V} = $sigdict;
286 1 ▶ if ($pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pdf->{'catalog'}{'Pages'}{'Kids'}{' val'}[0]{' objnum'}) { } 1 0 1
287 $sigformdict->{P} = PDFLiteral(
288 1 $pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'} . " 0 R");
289 } else {
290 0 $sigformdict->{P} = $pdf->open_page(1);
291 }
292 1 $sigformdict->{Rect} = PDFLiteral("[0 0 0 0]");
293 1 delete $sigformdict->{Border};
294 1 $sigformdict = $p->new_obj($sigformdict);
295 1 push @formarray, $sigformdict;
296 }
297  
298 1 my $acroformdict = PDFDict();
299 1 $acroformdict->{Fields} = PDFArray @formarray;
300 1 $acroformdict->{SigFlags} = PDFNum(3);
301 1 $acroformdict = $p->new_obj($acroformdict);
302  
303 1 $pdf->{catalog}->{'AcroForm'} = $acroformdict;
304 1 $pdf->{pdf}->out_obj($pdf->{catalog});
305 }
306  
307 # ============================================================
308 # sub: sign_file
309 # Applies the CMS/CAdES signature to the PDF byte stream.
310 # Returns the signed PDF as a string.
311 # ============================================================
312 sub sign_file {
313 1 ▶ my $pdf = shift;
Subroutine sign_file: called CC=5 SCAR=16.7
Pod documented
314 1 my $data;
315 1 $data = $pdf->to_string();
316  
317 1 ▶ if (!(-e $privkey_pem && -e $x509_pem)) { return $data; }
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem) 0 1 1
Condition33%1/3
-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem
!ll&&!rl&&r
001
MC/DC0%0/2
-e $PDF::Sign::privkey_pem and -e $PDF::Sign::x509_pem
-e $PDF::Sign::privkey_pem -e $PDF::Sign::x509_pem
Truth table33%1/3
A and B
A= -e $PDF::Sign::privkey_pemB= -e $PDF::Sign::x509_pem
ABresult
0X0
100
111
318  
319 1 my $sigbegin = rindex($data, '/Contents <00000000') + length '/Contents ';
320 1 my $sigend = index($data, '00000000>', $sigbegin) + length '00000000>';
321 1 my $eofsize = length($data) - $sigend;
322  
323 # PDF32000-2008 12.8.1
324 # A byte range digest shall be computed over a range of bytes in the file, that shall be
325 # indicated by the ByteRange entry in the signature dictionary. This range should be the
326 # entire file, including the signature dictionary but excluding the signature value its-
327 # elf (the Contents entry). Other ranges may be used but since they do not check for all
328 # changes to the document, their use is not recommended.
329 1 my $byterange = sprintf("/ByteRange [0 %8d %8d %8d]", $sigbegin, $sigend, $eofsize);
330 1 $data =~ s/\/ByteRange \[$zerorange\]/$byterange/e;
331  
332 1 ▶ if ($sigend - $sigbegin != ($siglen + 1) * 2) { return $data; }
Branch: 1 branch
BranchTrueFalseTotal
if ($sigend - $sigbegin != ($PDF::Sign::siglen + 1) * 2) 0 1 1
333  
334 1 my $streamtext = substr($data, 0, $sigbegin) . substr($data, $sigend, $eofsize);
335 1 my $streamtextfilename = "$tmpdir/pdfsign_streamtext_$$.pdf";
336 1 write_file($streamtextfilename, { binmode => ':raw' }, $streamtext);
337  
338 1 ▶ my $signature = cms_sign(
Condition50%1/2
$PDF::Sign::x509_chain || undef
l!l
01
MC/DC0%0/1
$PDF::Sign::x509_chain || undef
$PDF::Sign::x509_chain
Truth table50%1/2
A
A= $PDF::Sign::x509_chain
Aresult
11
00
339 signer => $x509_pem,
340 inkey => $privkey_pem,
341 in => $streamtextfilename,
342 certfile => $x509_chain || undef,
343 );
344  
345 1 my $sighex = PDFStrHex($signature)->as_pdf;
346 1 chop $sighex;
347 1 substr($data, $sigbegin, length($sighex), $sighex);
348  
349 1 unlink $streamtextfilename;
350 1 return $data;
351 }
352  
353 # ============================================================
354 # sub: prepare_ts
355 # Prepares the PDF AcroForm structure for a RFC3161 DocTimeStamp.
356 # Appends to existing AcroForm if a signature field already exists.
357 # TODO: $presign not yet implemented (visible timestamp widget)
358 # ============================================================
359 sub prepare_ts {
360 0 ▶ my $pdf = $_[0];
Subroutine prepare_ts: not called CC=5 SCAR=34.0
Pod documented
361 0 my $p = $pdf->{'pdf'};
362 0 my $presign = $_[1];
363  
364 0 my $sigdict = PDFDict();
365 0 $sigdict->{Type} = PDFName("DocTimeStamp");
366 0 $sigdict->{Filter} = PDFName("Adobe.PPKLite");
367 0 ▶ if ($^O eq 'linux') {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O eq 'linux') { } 0 0 0
368 #$sigdict->{M} = PDFStr(substr(strftime("D:%Y%m%d%H%M%S%z", localtime), 0, 19) . "'00'");
369 } else {
370 0 my @lt = localtime;
371 0 ▶ my $tz = $lt[8] ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$lt[8] ? : 0 0 0
372 #$sigdict->{M} = PDFStr(substr(strftime("D:%Y%m%d%H%M%S+0${tz}", localtime), 0, 19) . "'00'");
373 }
374 0 $sigdict->{SubFilter} = PDFName('ETSI.RFC3161');
375 0 $sigdict->{Contents} = PDFStrHex("\0" x $siglen);
376 0 $sigdict->{ByteRange} = PDFLiteral("[$zerorange]");
377 0 $sigdict = $p->new_obj($sigdict);
378  
379 0 my @formarray;
380 0 my $sigformdict = PDFDict();
381 0 $sigformdict->{Type} = PDFName("Annot");
382 0 $sigformdict->{Subtype} = PDFName("Widget");
383 0 $sigformdict->{F} = PDFNum(4 + 128);
384 0 $sigformdict->{FT} = PDFName("Sig");
385 0 $sigformdict->{T} = PDFStr("Signature2");
386 0 $sigformdict->{V} = $sigdict;
387 0 ▶ if ($pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pdf->{'catalog'}{'Pages'}{'Kids'}{' val'}[0]{' objnum'}) { } 0 0 0
388 $sigformdict->{P} = PDFLiteral(
389 0 $pdf->{catalog}->{Pages}->{Kids}->{' val'}[0]->{' objnum'} . " 0 R");
390 } else {
391 0 $sigformdict->{P} = $pdf->open_page(1);
392 }
393 0 $sigformdict->{Rect} = PDFLiteral("[0 0 0 0]");
394 0 delete $sigformdict->{Border};
395 0 $sigformdict = $p->new_obj($sigformdict);
396 0 push @formarray, $sigformdict;
397  
398 0 my $acroformdict = PDFDict();
399 0 ▶ if ($pdf->{catalog}->{AcroForm}->{' objnum'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pdf->{"catalog"}{"AcroForm"}{" objnum"}) 0 0 0
400 0 my $signprec = $pdf->{catalog}->{AcroForm}->{' objnum'} - 1;
401 0 push @formarray, PDFLiteral("$signprec 0 R");
402 }
403 0 $acroformdict->{Fields} = PDFArray @formarray;
404 0 $acroformdict->{SigFlags} = PDFNum(3);
405 0 $acroformdict = $p->new_obj($acroformdict);
406 0 $pdf->{catalog}->{'AcroForm'} = $acroformdict;
407 0 $pdf->{pdf}->out_obj($pdf->{catalog});
408 }
409  
410 # ============================================================
411 # sub: ts_file
412 # Applies the RFC3161 timestamp to the PDF byte stream.
413 # Returns the timestamped PDF as a string.
414 # ============================================================
415 sub ts_file {
416 0 ▶ my $pdf = shift;
Subroutine ts_file: not called CC=2 SCAR=17.9
Pod documented
417 0 my $data;
418 0 $data = $pdf->to_string();
419  
420 0 my $sigbegin = rindex($data, '/Contents <00000000') + length '/Contents ';
421 0 my $sigend = index($data, '00000000>', $sigbegin) + length '00000000>';
422 0 my $eofsize = length($data) - $sigend;
423  
424 # PDF32000-2008 12.8.1
425 # A byte range digest shall be computed over a range of bytes in the file, that shall be
426 # indicated by the ByteRange entry in the signature dictionary. This range should be the
427 # entire file, including the signature dictionary but excluding the signature value its-
428 # elf (the Contents entry). Other ranges may be used but since they do not check for all
429 # changes to the document, their use is not recommended.
430 0 my $byterange = sprintf("/ByteRange [0 %8d %8d %8d]", $sigbegin, $sigend, $eofsize);
431 0 $data =~ s/\/ByteRange \[$zerorange\]/$byterange/;
432  
433 0 ▶ if ($sigend - $sigbegin != ($siglen + 1) * 2) { return $data; }
Branch: 1 branch
BranchTrueFalseTotal
if ($sigend - $sigbegin != ($PDF::Sign::siglen + 1) * 2) 0 0 0
434  
435 0 my $streamtext = substr($data, 0, $sigbegin) . substr($data, $sigend, $eofsize);
436 0 my $streamtextfilename = "$tmpdir/pdfsign_streamtext_$$.pdf";
437 0 write_file($streamtextfilename, { binmode => ':raw' }, $streamtext);
438  
439 0 my $tsqfile = "$streamtextfilename.tsq";
440 0 ts_query(
441 in => $streamtextfilename,
442 out => $tsqfile,
443 );
444  
445 0 my $timestamp = tsa_fetch(
446 tsq => $tsqfile,
447 tsa_url => $tsaserver,
448 );
449  
450 0 my $sighex = PDFStrHex($timestamp)->as_pdf;
451 0 chop $sighex;
452 0 substr($data, $sigbegin, length($sighex), $sighex);
453  
454 0 unlink $streamtextfilename;
455 0 unlink $tsqfile;
456 0 return $data;
457 }
458  
459 # ============================================================
460 # sub: cms_sign
461 # Signs a file stream with openssl cms, returns raw DER bytes.
462 # Falls back to openssl smime if cms is not available
463 # (LibreSSL 2.x, very old OpenSSL).
464 # Supports OpenSSL 3+ (-cades, ETSI.CAdES.detached).
465 # ============================================================
466 sub cms_sign {
467 2 ▶ my (%args) = @_;
Subroutine cms_sign: called CC=10 SCAR=32.8
Pod documented
468 # args: signer, inkey, in, certfile (optional)
469  
470 2 my $signature;
471  
472 2 ▶ if ($has_cms) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_cms) { } 2 0 2
473 2 my @cmd = (
474 $osslcmd,
475 'cms', '-nosmimecap', '-md', 'sha256', '-binary', '-sign',
476 );
477 # -cades only with OpenSSL 3+ (not LibreSSL)
478 2 ▶ push @cmd, '-cades' if $osslv =~ /^OpenSSL 3/;
Branch: 1 branch
BranchTrueFalseTotal
if $osslv =~ /^OpenSSL 3/u 2 0 2
479  
480 2 push @cmd, '-signer', $args{signer};
481 2 ▶ push @cmd, '-certfile', $args{certfile} if $args{certfile};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"certfile"} 0 2 2
482 2 push @cmd, '-inkey', $args{inkey};
483 2 push @cmd, '-in', $args{in};
484 2 push @cmd, '-outform', 'pem';
485  
486 {
487 2 local $/;
488 2 ▶ open(my $fh, '-|', @cmd)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", @cmd or die "Cannot exec openssl cms: $!" 0 2 2
489 or die "Cannot exec openssl cms: $!";
490 2 $signature = <$fh>;
491 2 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'openssl cms failed (exit ' . ($? >> 8) . ')' 0 2 2
492 or die "openssl cms failed (exit " . ($? >> 8) . ")";
493 }
494 #write_file("$tmpdir/pdfsign_debug_".substr($osslv,0,13).".p7s", {binmode => ':raw'}, $signature);
495  
496 # strip PEM header/footer lines (-----BEGIN/END CMS-----)
497 2 $signature =~ s/^--.*--\n//mg;
498 2 $signature = decode_base64($signature);
499  
500 } else {
501 # fallback: openssl smime (LibreSSL 2.x, old OpenSSL)
502 # smime produces S/MIME output — strip headers up to blank line,
503 # then strip PEM armor, decode base64
504 0 ▶ warn "PDF::Sign: cms not available, falling back to smime\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDF::Sign::debug 0 0 0
505  
506 0 my @cmd = (
507 $osslcmd,
508 'smime', '-binary', '-sign', '-nodetach',
509 );
510 0 push @cmd, '-signer', $args{signer};
511 0 ▶ push @cmd, '-certfile', $args{certfile} if $args{certfile};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"certfile"} 0 0 0
512 0 push @cmd, '-inkey', $args{inkey};
513 0 push @cmd, '-in', $args{in};
514 0 push @cmd, '-outform', 'pem';
515  
516 {
517 0 local $/;
518 0 ▶ open(my $fh, '-|', @cmd)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", @cmd or die "Cannot exec openssl smime: $!" 0 0 0
519 or die "Cannot exec openssl smime: $!";
520 0 $signature = <$fh>;
521 0 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'openssl smime failed (exit ' . ($? >> 8) . ')' 0 0 0
522 or die "openssl smime failed (exit " . ($? >> 8) . ")";
523 }
524  
525 # strip S/MIME headers (everything up to and including blank line)
526 0 $signature =~ s/\A.*?\n\n//s;
527 # strip PEM armor
528 0 $signature =~ s/^--.*--\n//mg;
529 0 $signature = decode_base64($signature);
530 }
531  
532 # TODO: debug mode - capture stderr separately (platform portability TBD)
533 2 return $signature;
534 }
535  
536 # ============================================================
537 # sub: ts_query
538 # Generates the .tsq file for the TSA request via openssl ts.
539 # Uses openssl.cnf if present in the current directory.
540 # ============================================================
541 sub ts_query {
542 0 ▶ my (%args) = @_;
Subroutine ts_query: not called CC=4 SCAR=30.0
Pod documented
543 # args: in (file to timestamp), out (output .tsq file)
544  
545 my @cmd = (
546 $osslcmd,
547 'ts', '-query',
548 '-data', $args{in},
549 '-sha256', '-cert',
550 '-out', $args{out},
551 0 );
552  
553 # use openssl.cnf only if present in current directory
554 0 ▶ push @cmd, '-config', 'openssl.cnf' if -e 'openssl.cnf';
Branch: 1 branch
BranchTrueFalseTotal
if -e "openssl.cnf" 0 0 0
555  
556 0 ▶ open(my $fh, '-|', @cmd)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", @cmd or die "Cannot exec openssl ts: $!" 0 0 0
557 or die "Cannot exec openssl ts: $!";
558 # output goes to .tsq file, stdout is empty
559 0 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'openssl ts query failed (exit ' . ($? >> 8) . ')' 0 0 0
560 or die "openssl ts query failed (exit " . ($? >> 8) . ")";
561  
562 # TODO: debug mode - capture stderr separately (platform portability TBD)
563 0 return 1;
564 }
565  
566 # ============================================================
567 # sub: tsa_fetch
568 # Sends the .tsq to the TSA server, returns TimeStampToken DER.
569 # Uses curl if available, falls back to LWP::UserAgent.
570 #
571 # Note on substr($timestamp, 9, ...):
572 # The TSA response is a TimeStampResp DER structure:
573 # SEQUENCE {
574 # status INTEGER(0), -- 9 bytes: 30 03 02 01 00
575 # TimeStampToken -- the actual token to embed in PDF
576 # }
577 # We strip the outer wrapper and embed only the inner token.
578 # This is intentional per RFC3161, not a workaround.
579 #
580 # Note on binmode:
581 # The token is binary DER — binmode prevents Perl from mangling
582 # 0x0d bytes on Windows (CRLF translation).
583 # ============================================================
584 sub tsa_fetch {
585 0 ▶ my (%args) = @_;
Subroutine tsa_fetch: not called CC=7 SCAR=40.3
Pod documented
586 # args: tsq (input .tsq file), tsa_url
587  
588 0 my $timestamp;
589  
590 # prefer curl if available in PATH
591 0 my $curl = _which('curl');
592 0 ▶ if ($curl) {
Branch: 2 branches
BranchTrueFalseTotal
if ($curl) { } 0 0 0
elsif ($HAS_LWP) { } 0 0 0
593 my @cmd = (
594 $curl, '-s',
595 '-H', 'Content-Type: application/timestamp-query',
596 '--data-binary', '@' . $args{tsq},
597 $args{tsa_url},
598 0 );
599 0 local $/;
600 0 ▶ open(my $fh, '-|', @cmd)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", @cmd or die "Cannot exec curl: $!" 0 0 0
601 or die "Cannot exec curl: $!";
602 0 binmode $fh; # DER is binary — critical on Windows
603 0 $timestamp = <$fh>;
604 0 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'curl tsa_fetch failed (exit ' . ($? >> 8) . ')' 0 0 0
605 or die "curl tsa_fetch failed (exit " . ($? >> 8) . ")";
606 } elsif ($HAS_LWP) {
607 0 my $tsq_data = do {
608 open(my $fh, '<:raw', $args{tsq})
609 0 ▶ or die "Cannot read tsq file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $args{"tsq"} or die "Cannot read tsq file: $!" 0 0 0
610 0 local $/;
611 0 <$fh>;
612 };
613 0 my $ua = LWP::UserAgent->new(timeout => 30);
614 my $res = $ua->post(
615 $args{tsa_url},
616 0 'Content-Type' => 'application/timestamp-query',
617 Content => $tsq_data,
618 );
619 0 ▶ die "TSA request failed: " . $res->status_line unless $res->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->is_success 0 0 0
620 0 $timestamp = $res->content;
621 } else {
622 0 die "tsa_fetch requires curl or LWP::UserAgent\n";
623 }
624  
625 # strip TimeStampResp outer wrapper (9 bytes: SEQUENCE + status granted)
626 # retain only the inner TimeStampToken DER for embedding in PDF
627 # structure: 30 82 xx xx 30 03 02 01 00 [TimeStampToken starts here]
628 0 $timestamp = substr($timestamp, 9, length($timestamp));
629  
630 # TODO: debug mode - capture stderr separately (platform portability TBD)
631 0 return $timestamp;
632 }
633  
634  
635 # ============================================================
636 # sub: verify_signatures
637 # Reads and verifies all digital signatures in a PDF file.
638 # Returns an arrayref of hashrefs, one per signature field:
639 #
640 # [{
641 # type => 'cms' | 'tsa',
642 # subfilter => 'ETSI.CAdES.detached' | 'adbe.pkcs7.detached' | 'ETSI.RFC3161',
643 # signer => 'CN=..., O=...', # subject from sig dict or openssl output
644 # signed_at => 'D:20260329...', # /M field from sig dict (cms only)
645 # tsa_at => '...', # timestamp from TSA token (tsa only)
646 # valid => '1' | '', # cryptographic verification result
647 # error => '...', # error message if valid is ''
648 # }, ...]
649 #
650 # Verification uses openssl with -noverify (no CA chain check) by default.
651 # Pass ca_bundle => '/path/to/ca.pem' to enable full chain verification.
652 # ============================================================
653 # ============================================================
654 # sub: verify_signatures
655 # Reads and verifies all digital signatures in a PDF file.
656 # Returns an arrayref of hashrefs, one per signature field:
657 #
658 # [{
659 # type => 'cms' | 'tsa',
660 # subfilter => 'ETSI.CAdES.detached' | 'adbe.pkcs7.detached' | 'ETSI.RFC3161',
661 # signer => 'CN=..., O=...', # subject from sig dict or openssl output
662 # signed_at => 'D:20260329...', # /M field from sig dict (cms only)
663 # tsa_at => '...', # timestamp from TSA token (tsa only)
664 # valid => '1' | '', # cryptographic verification result
665 # error => '...', # error message if valid is ''
666 # }, ...]
667 #
668 # Verification uses openssl with -noverify (no CA chain check) by default.
669 # Pass ca_bundle => '/path/to/ca.pem' to enable full chain verification.
670 #
671 # Uses PDF::API2 (or PDF::Builder) to walk AcroForm signature fields,
672 # and extracts the DER blob directly from the ByteRange gap in the raw PDF.
673 # ============================================================
674 sub verify_signatures {
675 0 ▶ my ($pdf_path, %args) = @_;
Subroutine verify_signatures: not called CC=43 SCAR=75.5
Pod documented
676 0 my $ca_bundle = $args{ca_bundle};
677  
678 0 ▶ die "verify_signatures: file not found: $pdf_path\n" unless -e $pdf_path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $pdf_path 0 0 0
679  
680 # load PDF backend
681 0 my $backend;
682 0 ▶ if (eval { require PDF::API2; 1 }) {
Branch: 2 branches
BranchTrueFalseTotal
if (eval { do { require PDF::API2; 1 } }) { } 0 0 0
elsif (eval { do { require PDF::Builder; 1 } }) { } 0 0 0
683 0 $backend = 'PDF::API2';
684 0 } elsif (eval { require PDF::Builder; 1 }) {
685 0 $backend = 'PDF::Builder';
686 } else {
687 0 die "verify_signatures requires PDF::API2 or PDF::Builder\n";
688 }
689 0 require PDF::API2::Basic::PDF::Utils;
690  
691 # read raw PDF bytes — needed for ByteRange gap extraction
692 0 ▶ open(my $fh, '<:raw', $pdf_path) or die "Cannot read $pdf_path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $pdf_path or die "Cannot read ${pdf_path}: $!" 0 0 0
693 0 my $raw = do { local $/; <$fh> };
694 0 close $fh;
695  
696 # collect all real ByteRanges from raw PDF (skip zero placeholders)
697 0 my @byteranges;
698 0 my $scan_pos = 0;
699 0 while (1) {
700 0 my $br_pos = index($raw, '/ByteRange', $scan_pos);
701 0 ▶ last if $br_pos < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $br_pos < 0 0 0 0
702 0 my $br_str = substr($raw, $br_pos, 80);
703 0 ▶ if ($br_str =~ m{/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($br_str =~ m(/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\])u) 0 0 0
704 0 my @br = ($1+0, $2+0, $3+0, $4+0);
705 # skip placeholder (l1=0, o2=0, l2=0)
706 0 ▶ push @byteranges, \@br
Branch: 1 branch
BranchTrueFalseTotal
unless $br[1] == 0 and $br[2] == 0 and $br[3] == 0 0 0 0
Condition0%0/6
$br[1] == 0 and $br[2] == 0 and $br[3] == 0
!ll&&!rl&&r
000
$br[1] == 0 and $br[2] == 0
!ll&&!rl&&r
000
MC/DC0%0/3
$br[1] == 0 and $br[2] == 0 and $br[3] == 0
$br[1] == 0 $br[2] == 0 $br[3] == 0
Truth table0%0/4
A and B and C
A= $br[1] == 0B= $br[2] == 0C= $br[3] == 0
ABCresult
0XX0
10X0
1100
1111
707 unless $br[1] == 0 && $br[2] == 0 && $br[3] == 0;
708 }
709 0 $scan_pos = $br_pos + 10;
710 }
711  
712 0 my @results;
713  
714 # open PDF via PDF::API2 to walk AcroForm signature fields
715 0 my $pdf = $backend->open($pdf_path);
716  
717 0 my $acroform = $pdf->{catalog}->{AcroForm};
718 0 ▶ return [] unless $acroform;
Branch: 1 branch
BranchTrueFalseTotal
unless $acroform 0 0 0
719 0 ▶ $acroform = $acroform->realise
Branch: 1 branch
BranchTrueFalseTotal
if $acroform->isa("PDF::API2::Basic::PDF::Objind") 0 0 0
720 if $acroform->isa('PDF::API2::Basic::PDF::Objind');
721  
722 0 my $fields = $acroform->{Fields};
723 0 ▶ return [] unless $fields;
Branch: 1 branch
BranchTrueFalseTotal
unless $fields 0 0 0
724 0 ▶ $fields = $fields->realise
Branch: 1 branch
BranchTrueFalseTotal
if $fields->isa("PDF::API2::Basic::PDF::Objind") 0 0 0
725 if $fields->isa('PDF::API2::Basic::PDF::Objind');
726  
727 0 my @field_list = $fields->elements;
728  
729 0 my $sig_index = 0; # match fields to ByteRanges in order
730  
731 0 for my $field_ref (@field_list) {
732 0 my $field = $field_ref;
733 0 ▶ $field = $field->realise
Branch: 1 branch
BranchTrueFalseTotal
if $field->isa("PDF::API2::Basic::PDF::Objind") 0 0 0
734 if $field->isa('PDF::API2::Basic::PDF::Objind');
735  
736 # only process signature fields
737 0 ▶ my $ft = $field->{FT} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ft = $field->{"FT"} or next 0 0 0
738 0 ▶ next unless $ft->val eq 'Sig';
Branch: 1 branch
BranchTrueFalseTotal
unless $ft->val eq "Sig" 0 0 0
739  
740 # get signature value dict
741 0 ▶ my $sigval = $field->{V} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $sigval = $field->{"V"} or next 0 0 0
742 0 ▶ $sigval = $sigval->realise
Branch: 1 branch
BranchTrueFalseTotal
if $sigval->isa("PDF::API2::Basic::PDF::Objind") 0 0 0
743 if $sigval->isa('PDF::API2::Basic::PDF::Objind');
744  
745 # extract metadata from sig dict
746 0 ▶ my $subfilter = $sigval->{SubFilter} ? $sigval->{SubFilter}->val : '';
Branch: 1 branch
BranchTrueFalseTotal
$sigval->{'SubFilter'} ? : 0 0 0
747 0 ▶ my $signed_at = $sigval->{M} ? $sigval->{M}->val : '';
Branch: 1 branch
BranchTrueFalseTotal
$sigval->{'M'} ? : 0 0 0
748 0 ▶ my $signer = $sigval->{Name} ? $sigval->{Name}->val : '';
Branch: 1 branch
BranchTrueFalseTotal
$sigval->{'Name'} ? : 0 0 0
749  
750 0 ▶ my $type = ($subfilter eq 'ETSI.RFC3161') ? 'tsa' : 'cms';
Branch: 1 branch
BranchTrueFalseTotal
$subfilter eq 'ETSI.RFC3161' ? : 0 0 0
751  
752 # get ByteRange for this signature
753 0 my $br = $byteranges[$sig_index++];
754 0 ▶ unless ($br) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($br) 0 0 0
755 0 push @results, {
756 type => $type, subfilter => $subfilter,
757 signer => $signer, signed_at => $signed_at,
758 tsa_at => '', valid => '', error => 'ByteRange not found',
759 };
760 0 next;
761 }
762  
763 # extract DER from the gap between ByteRange[1] and ByteRange[2]
764 # this gap contains exactly: /Contents <hexDER 00padding>
765 0 my $gap = substr($raw, $br->[1], $br->[2] - $br->[1]);
766 0 my $contents_hex = '';
767 0 ▶ if ($gap =~ m{<([0-9a-fA-F]+)>}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gap =~ /<([0-9a-fA-F]+)>/u) 0 0 0
768 0 $contents_hex = $1;
769 }
770  
771 0 ▶ unless ($contents_hex) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($contents_hex) 0 0 0
772 0 push @results, {
773 type => $type, subfilter => $subfilter,
774 signer => $signer, signed_at => $signed_at,
775 tsa_at => '', valid => '', error => 'Contents hex not found in ByteRange gap',
776 };
777 0 next;
778 }
779  
780 # decode full hex to binary — then trim to actual ASN.1 length
781 # do NOT use regex strip of trailing zeros: legitimate DER may end with 0x00
782 # instead read the ASN.1 SEQUENCE length from the DER header
783 0 my $der_full = pack('H*', $contents_hex);
784 0 my $der = $der_full;
785 0 ▶ if (length($der_full) >= 4 && ord(substr($der_full,0,1)) == 0x30) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $der_full >= 4 and ord substr($der_full, 0, 1) == 48) 0 0 0
Condition0%0/3
length $der_full >= 4 and ord substr($der_full, 0, 1) == 48
!ll&&!rl&&r
000
MC/DC0%0/2
length $der_full >= 4 and ord substr($der_full, 0, 1) == 48
length $der_full >= 4 ord substr($der_full, 0, 1) == 48
Truth table0%0/3
A and B
A= length $der_full >= 4B= ord substr($der_full, 0, 1) == 48
ABresult
0X0
100
111
786 0 my $len_byte = ord(substr($der_full,1,1));
787 0 my $der_len;
788 0 ▶ if ($len_byte & 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len_byte & 128) { } 0 0 0
789 # long form length
790 0 my $num_bytes = $len_byte & 0x7f;
791 0 $der_len = 0;
792 0 for my $i (0 .. $num_bytes-1) {
793 0 $der_len = ($der_len << 8) | ord(substr($der_full, 2+$i, 1));
794 }
795 0 $der_len += 2 + $num_bytes; # header + content
796 } else {
797 # short form length
798 0 $der_len = $len_byte + 2;
799 }
800 0 ▶ $der = substr($der_full, 0, $der_len) if $der_len <= length($der_full);
Branch: 1 branch
BranchTrueFalseTotal
if $der_len <= length $der_full 0 0 0
801 }
802  
803 # rebuild signed content from the two ByteRange regions
804 0 my $signed_content = substr($raw, $br->[0], $br->[1])
805 . substr($raw, $br->[2], $br->[3]);
806  
807 # write temp files for openssl
808 0 my $tmp_der = "$tmpdir/pdfsign_verify_der_$$.tmp";
809 0 my $tmp_content = "$tmpdir/pdfsign_verify_content_$$.tmp";
810 0 write_file($tmp_der, { binmode => ':raw' }, $der);
811 0 write_file($tmp_content, { binmode => ':raw' }, $signed_content);
812  
813 0 my ($valid, $error, $tsa_at) = ('', '', '');
814 0 ▶ my $noverify = $ca_bundle ? "-CAfile \Q$ca_bundle\E" : '-noverify';
Branch: 1 branch
BranchTrueFalseTotal
$ca_bundle ? : 0 0 0
815  
816 0 ▶ if ($type eq 'cms') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'cms') { } 0 0 0
elsif ($type eq 'tsa') { } 0 0 0
817 # -binary: treat content as binary (required for PDF byte streams)
818 # -out /dev/null: suppress verified content on stdout
819 0 ▶ my $null = ($^O eq 'MSWin32' ? 'nul' : '/dev/null');
Branch: 1 branch
BranchTrueFalseTotal
$^O eq 'MSWin32' ? : 0 0 0
820 0 my $out = `$osslcmd cms -verify -binary -in \Q$tmp_der\E -inform DER -content \Q$tmp_content\E -out $null $noverify 2>&1`;
821 0 ▶ if ($? == 0 || $out =~ /Verification successful/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? == 0 or $out =~ /Verification successful/iu) { } 0 0 0
Condition0%0/3
$? == 0 or $out =~ /Verification successful/iu
l!l&&r!l&&!r
000
MC/DC0%0/2
$? == 0 or $out =~ /Verification successful/iu
$? == 0 $out =~ /Verification successful/iu
Truth table0%0/3
A or B
A= $? == 0B= $out =~ /Verification successful/iu
ABresult
1X1
011
000
822 0 $valid = '1';
823 # try to extract signer from openssl output if not in sig dict
824 0 ▶ if (!$signer && $out =~ /subject=([^\n]+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $signer and $out =~ /subject=([^\n]+)/iu) 0 0 0
Condition0%0/3
not $signer and $out =~ /subject=([^\n]+)/iu
!ll&&!rl&&r
000
MC/DC0%0/2
not $signer and $out =~ /subject=([^\n]+)/iu
not $signer $out =~ /subject=([^\n]+)/iu
Truth table0%0/3
not(A) and B
A= not $signerB= $out =~ /subject=([^\n]+)/iu
ABresult
0X0
100
111
825 0 ($signer = $1) =~ s/^\s+|\s+$//g;
826 }
827 } else {
828 0 ($error = $out) =~ s/\n/ /g;
829 0 $error =~ s/^\s+|\s+$//g;
830 }
831  
832 } elsif ($type eq 'tsa') {
833 0 my $out = `$osslcmd ts -verify -in \Q$tmp_der\E -token_in -data \Q$tmp_content\E 2>&1`;
834 0 ▶ if ($? == 0 || $out =~ /Verification:\s*OK/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? == 0 or $out =~ /Verification:\s*OK/iu) { } 0 0 0
Condition0%0/3
$? == 0 or $out =~ /Verification:\s*OK/iu
l!l&&r!l&&!r
000
MC/DC0%0/2
$? == 0 or $out =~ /Verification:\s*OK/iu
$? == 0 $out =~ /Verification:\s*OK/iu
Truth table0%0/3
A or B
A= $? == 0B= $out =~ /Verification:\s*OK/iu
ABresult
1X1
011
000
835 0 $valid = '1';
836 } else {
837 0 ($error = $out) =~ s/\n/ /g;
838 0 $error =~ s/^\s+|\s+$//g;
839 }
840  
841 # extract human-readable timestamp from TSA token
842 0 my $tsa_text = `$osslcmd ts -reply -in \Q$tmp_der\E -token_in -text 2>&1`;
843 0 ▶ if ($tsa_text =~ /Time stamp:\s*([^\n]+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tsa_text =~ /Time stamp:\s*([^\n]+)/iu) 0 0 0
844 0 ($tsa_at = $1) =~ s/^\s+|\s+$//g;
845 }
846 }
847  
848 0 unlink $tmp_der, $tmp_content;
849  
850 0 push @results, {
851 type => $type,
852 subfilter => $subfilter,
853 signer => $signer,
854 signed_at => $signed_at,
855 tsa_at => $tsa_at,
856 valid => $valid,
857 error => $error,
858 };
859 }
860  
861 0 return \@results;
862 }
863  
864  
865 # ============================================================
866 # internal: _cert_subject
867 # Extracts subject name from a PEM certificate via openssl.
868 # Handles OpenSSL 1.x/3.x and LibreSSL output format differences:
869 # 1.x: subject= /C=IT/O=Org/CN=Name (slash-separated, leading space)
870 # 3.x: subject=CN=Name, O=Org, C=IT (comma-separated, RFC2253 order)
871 # Returns a normalized string suitable for the PDF /Name field.
872 # ============================================================
873 sub _cert_subject {
874 2 ▶ my $pem = shift;
Subroutine _cert_subject: called CC=5 SCAR=17.4
875 2 ▶ open(my $fh, '-|', $osslcmd, 'x509', '-noout', '-subject', '-in', $pem)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "-|", $osslcmd, "x509", "-noout", "-subject", "-in", $pem or die "Cannot exec openssl x509: $!" 0 2 2
876 or die "Cannot exec openssl x509: $!";
877 2 my $subject = do { local $/; <$fh> };
878 2 ▶ close $fh
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die 'openssl x509 failed (exit ' . ($? >> 8) . ')' 0 2 2
879 or die "openssl x509 failed (exit " . ($? >> 8) . ")";
880 2 chomp $subject;
881  
882 # OpenSSL 1.x/LibreSSL: "subject= /C=IT/O=Org/CN=Name"
883 # normalize to "C=IT, O=Org, CN=Name"
884 2 ▶ if ($subject =~ m{^subject=\s*/}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($subject =~ m[^subject=\s*/]u) { } 0 2 2
elsif ($subject =~ /^subject=/u) { } 2 0 2
885 0 $subject =~ s{^subject=\s*/}{}; # strip prefix and leading slash
886 0 $subject =~ s{/}{, }g; # slashes to comma-space
887 }
888 # OpenSSL 3.x: "subject=CN=Name, O=Org, C=IT"
889 # just strip the prefix
890 elsif ($subject =~ m{^subject=}) {
891 2 $subject =~ s{^subject=\s*}{};
892 }
893  
894 2 return $subject;
895 }
896  
897 # ============================================================
898 # internal: _which
899 # Portable `which` — returns full path of binary or undef.
900 # ============================================================
901 sub _which {
902 0 ▶ my $bin = shift;
Subroutine _which: not called CC=4 SCAR=30.0
903 0 ▶ for my $dir (split /:/, ($ENV{PATH} // '')) {
Condition0%0/2
$ENV{"PATH"} // ""
l!l
00
MC/DC0%0/1
$ENV{"PATH"} // ""
$ENV{"PATH"}
Truth table0%0/2
A
A= $ENV{"PATH"}
Aresult
11
00
904 0 my $full = "$dir/$bin";
905 0 ▶ return $full if -x $full;
Branch: 1 branch
BranchTrueFalseTotal
if -x $full 0 0 0
906 }
907 0 return undef;
908 }
909  
910 4 1;
911  
912 __END__
↑ Summary example.pl »