blib/lib/Mail/Make/SMIME.pm untested

filter: Statementstmt 0.0% 0 / 241 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 94 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 468 CC 38 SCAR 33.1
CC
38
Cov
0%
_load_private_key
72.0
sign_encrypt
56.0
_build_from_smime_output
56.0
CRAP 27.3
1 ##----------------------------------------------------------------------------
2 ## MIME Email Builder - ~/lib/Mail/Make/SMIME.pm
3 ## Version v0.1.2
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created: 2026/03/07
7 ## Modified: 2026/03/07
8 ## All rights reserved.
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Mail::Make::SMIME;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 warnings::register_categories( 'Mail::Make' );
19 use parent qw( Module::Generic );
20 use vars qw( $VERSION $EXCEPTION_CLASS );
21 our $EXCEPTION_CLASS = 'Mail::Make::Exception';
22 our $VERSION = 'v0.1.2';
23 };
24  
25 use strict;
26 use warnings;
27  
28 # init( %opts )
29 # Initialises attributes. Accepted constructor options (all optional):
30 # ca_cert => $pem_string_or_file CA certificate(s) for chain verification
31 # cert => $pem_string_or_file Signer certificate (PEM)
32 # key => $pem_string_or_file Private key (PEM)
33 # key_password => $string_or_coderef Passphrase for encrypted private key
34 sub init
35 {
36 my $self = shift( @_ );
37 $self->{ca_cert} = undef; # PEM string or file path: CA cert(s) for verification
38 $self->{cert} = undef; # PEM string or file path: signer certificate
39 $self->{key} = undef; # PEM string or file path: private key
40 $self->{key_password} = undef; # string or CODE ref; undef = unencrypted key
41 $self->{_exception_class} = $EXCEPTION_CLASS;
42 $self->SUPER::init( @_ ) || return( $self->pass_error );
43 return( $self );
44 }
45  
46 # ca_cert( [$pem_or_file] )
47 sub ca_cert { return( shift->_set_get_scalar( 'ca_cert', @_ ) ); }
48  
49 # cert( [$pem_or_file] )
50 sub cert { return( shift->_set_get_scalar( 'cert', @_ ) ); }
51  
52 # encrypt( entity => $mail_make, RecipientCert => $cert_or_arrayref [, %opts] )
53 # Encrypts $mail_make for one or more recipients. Returns a new Mail::Make object whose
54 # entity is a RFC 5751 application/pkcs7-mime enveloped message.
55 #
56 # Required options:
57 # entity => Mail::Make object
58 # RecipientCert => PEM string, file path, or arrayref of either
59 #
60 # Optional options:
61 # Cipher => 'DES3' | 'AES128' | 'AES256' (default: AES256)
62 sub encrypt
63 {
64 my $self = shift( @_ );
65 my $opts = $self->_get_args_as_hash( @_ );
66 my $entity = $opts->{entity} ||
67 return( $self->error( 'encrypt(): entity option is required.' ) );
68  
69 my $recipient_cert = $opts->{RecipientCert} ||
70 return( $self->error( 'encrypt(): RecipientCert option is required.' ) );
71  
72 # Ensure Date and Message-ID exist before serialising
73 $self->_ensure_envelope_headers( $entity ) || return( $self->pass_error );
74  
75 my $smime = $self->_make_crypt_smime || return( $self->pass_error );
76  
77 # Load recipient certificate(s) as public key(s)
78 my @certs = ref( $recipient_cert ) eq 'ARRAY'
79 ? @$recipient_cert
80 : ( $recipient_cert );
81  
82 my @pem_certs;
83 for my $cert ( @certs )
84 {
85 my $pem = $self->_read_pem( $cert ) || return( $self->pass_error );
86 push( @pem_certs, $pem );
87 }
88  
89 local $@;
90 eval{ $smime->setPublicKey( \@pem_certs ) };
91 return( $self->error( "encrypt(): failed to load recipient certificate(s): $@" ) ) if( $@ );
92  
93 # Serialise the full message
94 my $raw = $self->_serialise_for_smime( $entity ) || return( $self->pass_error );
95  
96 my $encrypted;
97 eval{ $encrypted = $smime->encrypt( $raw ) };
98 return( $self->error( "encrypt(): Crypt::SMIME::encrypt() failed: $@" ) ) if( $@ );
99 unless( defined( $encrypted ) && CORE::length( $encrypted ) )
100 {
101 return( $self->error( 'encrypt(): Crypt::SMIME returned empty result.' ) );
102 }
103  
104 return( $self->_build_from_smime_output( $entity, $encrypted ) );
105 }
106  
107 # key( [$pem_or_file] )
108 sub key { return( shift->_set_get_scalar( 'key', @_ ) ); }
109  
110 # key_password( [$string_or_coderef] )
111 sub key_password { return( shift->_set_get_scalar( 'key_password', @_ ) ); }
112  
113 # sign( entity => $mail_make [, %opts] )
114 # Signs $mail_make with a detached S/MIME signature. Returns a new Mail::Make
115 # object whose entity is a RFC 5751 multipart/signed message.
116 #
117 # Required option (or set via constructor / accessors):
118 # entity => Mail::Make object
119 # Cert => PEM string or file path (overrides $self->{cert})
120 # Key => PEM string or file path (overrides $self->{key})
121 #
122 # Optional options:
123 # KeyPassword => string or CODE ref (overrides $self->{key_password})
124 # CACert => PEM string or file path
125 sub sign
126 {
127 my $self = shift( @_ );
128 my $opts = $self->_get_args_as_hash( @_ );
129 my $entity = $opts->{entity} ||
130 return( $self->error( 'sign(): entity option is required.' ) );
131  
132 $self->_ensure_envelope_headers( $entity ) || return( $self->pass_error );
133  
134 my $smime = $self->_make_crypt_smime || return( $self->pass_error );
135  
136 $self->_load_private_key( $smime, $opts ) || return( $self->pass_error );
137  
138 $self->_load_ca_cert( $smime, $opts ); # optional; ignore error
139  
140 my $raw = $self->_serialise_for_smime( $entity ) || return( $self->pass_error );
141  
142 my $signed;
143 local $@;
144 eval{ $signed = $smime->sign( $raw ) };
145 return( $self->error( "sign(): Crypt::SMIME::sign() failed: $@" ) ) if( $@ );
146 unless( defined( $signed ) && CORE::length( $signed ) )
147 {
148 return( $self->error( 'sign(): Crypt::SMIME returned empty result.' ) );
149 }
150  
151 return( $self->_build_from_smime_output( $entity, $signed ) );
152 }
153  
154 # sign_encrypt( entity => $mail_make, RecipientCert => $cert [, %opts] )
155 # Signs then encrypts $mail_make. Returns a new Mail::Make object.
156 #
157 # Required options:
158 # entity => Mail::Make object
159 # Cert => PEM string or file path
160 # Key => PEM string or file path
161 # RecipientCert => PEM string, file path, or arrayref
162 #
163 # Optional options:
164 # KeyPassword => string or CODE ref
165 # CACert => PEM string or file path
166 # Cipher => 'DES3' | 'AES128' | 'AES256'
167 sub sign_encrypt
168 {
169 my $self = shift( @_ );
170 my $opts = $self->_get_args_as_hash( @_ );
171 my $entity = $opts->{entity} ||
172 return( $self->error( 'sign_encrypt(): entity option is required.' ) );
173  
174 $opts->{RecipientCert} ||
175 return( $self->error( 'sign_encrypt(): RecipientCert option is required.' ) );
176  
177 $self->_ensure_envelope_headers( $entity ) || return( $self->pass_error );
178  
179 my $smime = $self->_make_crypt_smime || return( $self->pass_error );
180  
181 $self->_load_private_key( $smime, $opts ) || return( $self->pass_error );
182  
183 $self->_load_ca_cert( $smime, $opts ); # optional
184  
185 # Load recipient certificate(s)
186 my @certs = ref( $opts->{RecipientCert} ) eq 'ARRAY'
187 ? @{$opts->{RecipientCert}}
188 : ( $opts->{RecipientCert} );
189  
190 my @pem_certs;
191 for my $cert ( @certs )
192 {
193 my $pem = $self->_read_pem( $cert ) || return( $self->pass_error );
194 push( @pem_certs, $pem );
195 }
196  
197 local $@;
198 eval{ $smime->setPublicKey( \@pem_certs ) };
199 return( $self->error( "sign_encrypt(): failed to load recipient certificate(s): $@" ) ) if( $@ );
200  
201 my $raw = $self->_serialise_for_smime( $entity ) || return( $self->pass_error );
202  
203 # Crypt::SMIME has no signAndEncrypt() method. RFC 5751 sign-then-encrypt is
204 # implemented by signing first, then encrypting the signed output.
205 # The signed intermediate is a full RFC 2822 message string; we pass it directly to
206 # encrypt() which operates on the same format.
207 my $signed;
208 eval{ $signed = $smime->sign( $raw ) };
209 return( $self->error( "sign_encrypt(): Crypt::SMIME::sign() failed: $@" ) ) if( $@ );
210 unless( defined( $signed ) && CORE::length( $signed ) )
211 {
212 return( $self->error( 'sign_encrypt(): Crypt::SMIME::sign() returned empty result.' ) );
213 }
214  
215 # Re-load recipient public key(s) on a fresh instance for the encrypt step.
216 # The same $smime object already has the private key loaded; calling setPublicKey()
217 # again on it works, but to be explicit and avoid any state confusion we reuse $smime
218 # (Crypt::SMIME accumulates public keys).
219 my $result;
220 eval{ $result = $smime->encrypt( $signed ) };
221 return( $self->error( "sign_encrypt(): Crypt::SMIME::encrypt() failed: $@" ) ) if( $@ );
222 unless( defined( $result ) && CORE::length( $result ) )
223 {
224 return( $self->error( 'sign_encrypt(): Crypt::SMIME::encrypt() returned empty result.' ) );
225 }
226  
227 return( $self->_build_from_smime_output( $entity, $result ) );
228 }
229  
230 # _build_from_smime_output( $original_mail, $smime_string ) → Mail::Make
231 # Parses the S/MIME output string from Crypt::SMIME (which already contains all the correct
232 # headers) into a new Mail::Make object that smtpsend() can use directly.
233 #
234 # Crypt::SMIME::sign() and encrypt() return a fully formed RFC 2822 message string. We
235 # wrap it in a Mail::Make object by parsing it into an Entity and storing it as
236 # _smime_entity, mirroring what _gpg_entity does for GPG.
237 sub _build_from_smime_output
238 {
239 my( $self, $original, $smime_str ) = @_;
240 require Mail::Make;
241  
242 # Canonicalise line endings to CRLF
243 ( my $canon = $smime_str ) =~ s/\015?\012/\015\012/g;
244  
245 # Locate the header / body separator
246 my $pos = index( $canon, "\015\012\015\012" );
247 if( $pos < 0 )
248 {
249 return( $self->error( '_build_from_smime_output(): no header/body separator in Crypt::SMIME output.' ) );
250 }
251  
252 # Parse outer headers into a plain hash (case-insensitive, last-value wins for duplicates)
253 # so that the structure test can call headers->get().
254 my $hdr_block = substr( $canon, 0, $pos + 2 );
255 my %hdrs;
256 my $cur_name = '';
257 my $cur_value = '';
258 for my $line ( split( /(?<=\015\012)/, $hdr_block ) )
259 {
260 if( $line =~ /^[ \t]/ )
261 {
262 ( my $cont = $line ) =~ s/^\015\012$//; # strip trailing CRLF
263 $cur_value .= $line if( CORE::length( $cur_name ) );
264 }
265 elsif( $line =~ /^([\x21-\x39\x3B-\x7E]+):\s*(.*?)\015\012$/ )
266 {
267 $hdrs{ $cur_name } = $cur_value if( CORE::length( $cur_name ) );
268 ( $cur_name, $cur_value ) = ( $1, $2 );
269 }
270 }
271 $hdrs{ $cur_name } = $cur_value if( CORE::length( $cur_name ) );
272  
273 # _RawEntity wraps the complete Crypt::SMIME output string and exposes just enough of
274 # the Entity interface for smtpsend() and the test suite:
275 # headers->get( $name ) - used by structure tests
276 # headers->remove( $name ) - called by smtpsend() to strip Bcc
277 # as_string() - called by smtpsend() for SMTP DATA
278 #
279 # We deliberately do NOT subclass Mail::Make::Entity here. Entity::print_body
280 # branches on is_multipart() and iterates _parts (which would be empty), producing a
281 # message with an empty body. Bypassing Entity entirely is the correct fix.
282 my $entity = Mail::Make::SMIME::_RawEntity->new( \%hdrs, $canon );
283  
284 # Build the wrapper Mail::Make object
285 my $new = Mail::Make->new ||
286 return( $self->pass_error( Mail::Make->error ) );
287  
288 # Copy envelope headers (From, To, Subject, Date, Message-ID …) from the original
289 # Mail::Make object so that smtpsend() can derive the SMTP envelope
290 # (MAIL FROM / RCPT TO) without inspecting the entity.
291 $original->headers->scan( sub
292 {
293 my( $name, $value ) = @_;
294 $new->headers->set( $name => $value );
295 return(1);
296 });
297  
298 # Store pre-assembled entity; as_entity() in Mail::Make returns it directly via the
299 # _smime_entity hook.
300 $new->{_smime_entity} = $entity;
301  
302 return( $new );
303 }
304  
305 # _ensure_envelope_headers( $mail_make_obj )
306 # Generates Date and Message-ID on the Mail::Make object without calling as_entity(), to
307 # avoid polluting $self->{_parts}[0] with RFC 2822 headers.
308 sub _ensure_envelope_headers
309 {
310 my( $self, $mail ) = @_;
311  
312 unless( $mail->{_headers}->exists( 'Date' ) )
313 {
314 $mail->{_headers}->init_header( Date => $mail->_format_date ) ||
315 return( $self->pass_error( $mail->{_headers}->error ) );
316 }
317  
318 unless( $mail->{_headers}->exists( 'Message-ID' ) )
319 {
320 $mail->{_headers}->message_id(
321 { generate => 1, domain => $mail->_default_domain }
322 ) || return( $self->pass_error( $mail->{_headers}->error ) );
323 }
324  
325 return(1);
326 }
327  
328 # _load_ca_cert( $smime_obj, \%opts )
329 # Loads the CA certificate into a Crypt::SMIME instance for chain verification.
330 # Source priority: option CACert > constructor ca_cert.
331 # Silently returns 1 if no CA cert is provided (CA cert is optional for signing).
332 sub _load_ca_cert
333 {
334 my( $self, $smime, $opts_ref ) = @_;
335  
336 my $source = $opts_ref->{CACert} // $self->{ca_cert};
337 return(1) unless( defined( $source ) && CORE::length( $source ) );
338  
339 my $pem = $self->_read_pem( $source ) || return( $self->pass_error );
340  
341 local $@;
342 eval{ $smime->setPublicKey( [$pem] ) };
343 return( $self->error( "_load_ca_cert(): failed to load CA certificate: $@" ) ) if( $@ );
344  
345 return(1);
346 }
347  
348 # _load_private_key( $smime_obj, \%opts )
349 # Loads the private key and signing certificate into a Crypt::SMIME instance.
350 # Source priority: option Cert/Key > constructor cert/key.
351 # Handles key_password as string or CODE ref.
352 sub _load_private_key
353 {
354 my( $self, $smime, $opts_ref ) = @_;
355  
356 my $cert_source = $opts_ref->{Cert} // $self->{cert};
357 my $key_source = $opts_ref->{Key} // $self->{key};
358  
359 unless( defined( $cert_source ) && CORE::length( $cert_source ) )
360 {
361 return( $self->error( '_load_private_key(): no certificate provided. Set Cert option or cert() accessor.' ) );
362 }
363  
364 unless( defined( $key_source ) && CORE::length( $key_source ) )
365 {
366 return( $self->error( '_load_private_key(): no private key provided. Set Key option or key() accessor.' ) );
367 }
368  
369 my $cert_pem = $self->_read_pem( $cert_source ) || return( $self->pass_error );
370  
371 my $key_pem = $self->_read_pem( $key_source ) || return( $self->pass_error );
372  
373 # Resolve key password
374 my $password_src = $opts_ref->{KeyPassword} // $self->{key_password};
375 my $password;
376 if( defined( $password_src ) )
377 {
378 if( ref( $password_src ) eq 'CODE' )
379 {
380 local $@;
381 $password = eval{ $password_src->() };
382 return( $self->error( "_load_private_key(): KeyPassword CODE ref died: $@" ) ) if( $@ );
383 }
384 else
385 {
386 $password = $password_src;
387 }
388 }
389  
390 local $@;
391 if( defined( $password ) )
392 {
393 eval{ $smime->setPrivateKey( $key_pem, $cert_pem, $password ) };
394 }
395 else
396 {
397 eval{ $smime->setPrivateKey( $key_pem, $cert_pem ) };
398 }
399 return( $self->error( "_load_private_key(): failed to load private key/certificate: $@" ) ) if( $@ );
400  
401 return(1);
402 }
403  
404 # _make_crypt_smime() → Crypt::SMIME instance
405 # Loads Crypt::SMIME and returns a new instance, with a clear error if the module is not
406 # installed.
407 sub _make_crypt_smime
408 {
409 my $self = shift( @_ );
410 $self->_load_class( 'Crypt::SMIME' ) ||
411 return( $self->error( 'Crypt::SMIME is required for S/MIME operations. Install it with: cpan Crypt::SMIME' ) );
412  
413 my $smime;
414 eval{ $smime = Crypt::SMIME->new };
415 return( $self->error( "Failed to instantiate Crypt::SMIME: $@" ) ) if( $@ );
416  
417 return( $smime );
418 }
419  
420 # _read_pem( $source ) → $pem_string
421 # Accepts either a PEM string (contains '-----BEGIN') or a file path and returns the PEM
422 # content as a string. Dies gracefully with a proper error.
423 sub _read_pem
424 {
425 my( $self, $source ) = @_;
426  
427 unless( defined( $source ) )
428 {
429 return( $self->error( '_read_pem(): undefined source.' ) );
430 }
431  
432 # Already a PEM string
433 return( $source ) if( $source =~ /-----BEGIN/ );
434  
435 # File path
436 unless( -f $source )
437 {
438 return( $self->error( "_read_pem(): file not found: $source" ) );
439 }
440  
441 unless( -r $source )
442 {
443 return( $self->error( "_read_pem(): file not readable: $source" ) );
444 }
445  
446 open( my $fh, '<', $source ) ||
447 return( $self->error( "_read_pem(): cannot open '$source': $!" ) );
448 local $/;
449 my $pem = <$fh>;
450 close( $fh );
451  
452 unless( defined( $pem ) && $pem =~ /-----BEGIN/ )
453 {
454 return( $self->error( "_read_pem(): file '$source' does not contain PEM data." ) );
455 }
456  
457 return( $pem );
458 }
459  
460 # _serialise_for_smime( $mail_make_obj ) → $string
461 # Serialises the Mail::Make object to a full RFC 2822 message string
462 # (headers + body, CRLF line endings).
463 # Unlike _serialise_for_gpg, we pass the COMPLETE message to Crypt::SMIME; it handles
464 # RFC 5751 header separation internally.
465 sub _serialise_for_smime
466 {
467 my( $self, $mail ) = @_;
468  
469 unless( defined( $mail ) )
470 {
471 return( $self->error( '_serialise_for_smime(): no Mail::Make object supplied.' ) );
472 }
473  
474 unless( $mail->can( 'as_entity' ) )
475 {
476 return( $self->error( '_serialise_for_smime(): argument must be a Mail::Make object.' ) );
477 }
478  
479 my $entity = $mail->as_entity || return( $self->pass_error( $mail->error ) );
480  
481 my $full = $entity->as_string || return( $self->pass_error( $entity->error ) );
482  
483 # Canonicalise line endings to CRLF
484 $full =~ s/\015?\012/\015\012/g;
485  
486 return( $full );
487 }
488  
489 # STORABLE_freeze / STORABLE_thaw - satisfy Module::Generic serialisation hooks
490 sub STORABLE_freeze { return( $_[0] ) }
491  
492 sub STORABLE_thaw { return( $_[0] ) }
493  
494  
495 # NOTE: package Mail::Make::SMIME::_RawEntity
496 ##----------------------------------------------------------------------------
497 ## Mail::Make::SMIME::_RawEntity
498 ## Lightweight entity wrapper for Crypt::SMIME output strings.
499 ##
500 ## Exposes just enough of the Mail::Make::Entity interface to satisfy
501 ## Mail::Make::smtpsend() and the test suite:
502 ##
503 ## headers->get( $name ) - returns the header value
504 ## headers->remove( $name ) - removes a header (no-op if absent)
505 ## as_string() - returns the complete RFC 2822 message verbatim
506 ##
507 ## We deliberately bypass Mail::Make::Entity because Entity::print_body()
508 ## branches on is_multipart() and iterates _parts. For a multipart/signed
509 ## entity the _parts array would be empty, producing a message with only a
510 ## closing boundary and no body. Storing the raw Crypt::SMIME string and
511 ## emitting it verbatim is the correct approach.
512 ##----------------------------------------------------------------------------
513 # Hide it from CPAN
514 package
515 Mail::Make::SMIME::_RawEntity;
516  
517 use strict;
518 use warnings;
519  
520 # new( \%headers, $raw_string ) → _RawEntity
521 sub new
522 {
523 my( $class, $hdrs_ref, $raw ) = @_;
524 return( bless(
525 {
526 _hdrs => { map { lc( $_ ) => $hdrs_ref->{ $_ } } keys( %$hdrs_ref ) },
527 _raw => $raw,
528 }, $class ) );
529 }
530  
531 # as_string() → the complete RFC 2822 message string (CRLF line endings)
532 sub as_string { return( $_[0]->{_raw} ) }
533  
534 # headers() → a _RawHeaders proxy object
535 sub headers
536 {
537 my $self = shift( @_ );
538 return( Mail::Make::SMIME::_RawHeaders->new( $self->{_hdrs} ) );
539 }
540  
541 # NOTE: package Mail::Make::SMIME::_RawHeaders
542 ##----------------------------------------------------------------------------
543 ## Mail::Make::SMIME::_RawHeaders
544 ## Minimal headers proxy used by _RawEntity.
545 ##----------------------------------------------------------------------------
546 # Hide it from CPAN
547 package
548 Mail::Make::SMIME::_RawHeaders;
549  
550 use strict;
551 use warnings;
552  
553 sub new
554 {
555 my( $class, $hdrs_ref ) = @_;
556 return( bless( { _h => $hdrs_ref }, $class ) );
557 }
558  
559 # get( $name ) → value string or undef
560 sub get
561 {
562 my( $self, $name ) = @_;
563 return( $self->{_h}->{ lc( $name ) } );
564 }
565  
566 # remove( $name ) → removes the header (no-op if absent)
567 sub remove
568 {
569 my( $self, $name ) = @_;
570 delete( $self->{_h}->{ lc( $name ) } );
571 return( $self );
572 }
573  
574 1;
575 # NOTE: POD
576 __END__