From 2fe744d5ca61963d7420cf353fc7a5cf49c3b753 Mon Sep 17 00:00:00 2001 From: "Flavio S. Glock" Date: Thu, 12 Nov 2026 16:39:34 +0100 Subject: [PATCH 1/2] fix: preserve eval security and pragma semantics Fix JVM propagation of tainted eval failures, prevent required modules from leaking strict/features/warnings into their caller, and make Safe shared subs visible to compartment eval under strict subs. Add focused regression tests. Refs: #1981, #2011, #2033 Generated with OpenAI Codex (https://openai.com/codex) Co-Authored-By: OpenAI Codex <158243242+openai-codex[bot]@users.noreply.github.com> --- docs/about/changelog.md | 2 + .../org/perlonjava/backend/jvm/EmitEval.java | 9 +++++ .../frontend/parser/StatementParser.java | 37 ++++++++++++++----- .../runtime/runtimetypes/RuntimeCode.java | 3 +- .../runtimetypes/TaintedEvalException.java | 8 ++++ src/main/perl/lib/Safe.pm | 14 +++++-- .../resources/unit/safe_shared_sub_strict.t | 28 ++++++++++++++ .../strict_isa_declared_after_assignment.t | 22 +++++++++++ .../unit/tainted_eval_security_propagation.t | 23 ++++++++++++ 9 files changed, 132 insertions(+), 14 deletions(-) create mode 100644 src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java create mode 100644 src/test/resources/unit/safe_shared_sub_strict.t create mode 100644 src/test/resources/unit/strict_isa_declared_after_assignment.t create mode 100644 src/test/resources/unit/tainted_eval_security_propagation.t diff --git a/docs/about/changelog.md b/docs/about/changelog.md index 784ff1ee00..a9de8a6357 100644 --- a/docs/about/changelog.md +++ b/docs/about/changelog.md @@ -6,6 +6,8 @@ priorities and future plans. ## Work in progress +- Preserve fatal taint-mode eval errors on the JVM, keep loaded-module pragmas out of the caller's lexical scope, and resolve shared Safe subs under strict subs (#1981, #2011, #2033). + - Continue the `eval STRING` hot-path micro-optimisation series (Rounds 26–28): replace `.equals()` with identity (`==`) comparisons for compile-time-literal annotation keys in `AbstractNode`; add a fast path in `compileAssignmentOperator` that handles the dominant `my $scalar = expr` form with five structural checks and direct opcode emission, bypassing the full `LValueVisitor.getContext` traversal and general dispatch; cache the `ThreadLocal` state reference once per `ByteCodeSourceMapper.saveSourceLocation` call instead of four separate lookups (one per AST node compiled); and intern single-char `OPERATOR_CACHE` text strings so the comment-detection and POD-detection branches in `Whitespace.skipWhitespace` can use identity comparison on every token. - Reduce per-eval allocation and compilation overhead in the `eval STRING` hot path: make five `Parser` collection fields lazy (allocated only when first written, saving ~5 `ArrayDeque`/`HashMap` objects for simple evals); extract an inline `Set.of(9-element)` in `ParsePrimary` to a `private static final` constant; encode the `useInteger` annotation as two bit-flags in `AbstractNode.internalAnnotationFlags`, eliminating a per-AST-node `HashMap` entry and its `get` lookup for every arithmetic/bitwise operator; make `ErrorMessageUtil.literalQuoteRanges`, `JavaClassInfo.gotoLabelStack`, and `JavaClassInfo.finallyLabelScopes` lazy; and guard the five reference-alias matchers in `CompileAssignment.compileAssignmentOperator` behind a pre-check so the common `my $x = value` path skips all five calls. Net result: ~4.8% throughput gain on a 1 M-iteration `eval STRING` benchmark (62 492 → ~65 500 evals/s). diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java index 1a66cfb7f6..f4fcb10b94 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java @@ -240,6 +240,15 @@ static void handleEvalOperator(EmitterVisitor emitterVisitor, OperatorNode node) // Catch any exception from evalStringHelper / reflection / applyEval mv.visitLabel(catchBlock); + // Taint rejection is a fatal security error. Unlike syntax/runtime + // failures, eval STRING must not convert it into a normal $@ result. + mv.visitInsn(Opcodes.DUP); + mv.visitTypeInsn(Opcodes.INSTANCEOF, + "org/perlonjava/runtime/runtimetypes/TaintedEvalException"); + Label catchableEvalFailure = new Label(); + mv.visitJumpInsn(Opcodes.IFEQ, catchableEvalFailure); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(catchableEvalFailure); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/operators/WarnDie", "catchEval", diff --git a/src/main/java/org/perlonjava/frontend/parser/StatementParser.java b/src/main/java/org/perlonjava/frontend/parser/StatementParser.java index 80951d629e..8c4a52b8f3 100644 --- a/src/main/java/org/perlonjava/frontend/parser/StatementParser.java +++ b/src/main/java/org/perlonjava/frontend/parser/StatementParser.java @@ -1449,6 +1449,17 @@ public static Node parseUseDeclaration(Parser parser, LexerToken token) { // execute the statement immediately, using: // `require "fullName.pm"` + ScopedSymbolTable.FastStack savedRequireStrict = + cloneIntegerStack(ctx.symbolTable.strictOptionsStack); + ScopedSymbolTable.FastStack savedRequireFeatures = + cloneIntegerStack(ctx.symbolTable.featureFlagsStack); + ScopedSymbolTable.FastStack savedRequireWarnings = + cloneBitSetStack(ctx.symbolTable.warningFlagsStack); + ScopedSymbolTable.FastStack savedRequireFatalWarnings = + cloneBitSetStack(ctx.symbolTable.warningFatalStack); + ScopedSymbolTable.FastStack savedRequireDisabledWarnings = + cloneBitSetStack(ctx.symbolTable.warningDisabledStack); + // Setup the caller stack - use getSourceLocationAccurate to honor #line directives ErrorMessageUtil.SourceLocation loc = ctx.errorUtil.getSourceLocationAccurate(useTokenIndex); CallerStack.push( @@ -1461,15 +1472,23 @@ public static Node parseUseDeclaration(Parser parser, LexerToken token) { // execute 'require(fullName)' RuntimeScalar ret; - if (evalRequireOverride) { - RuntimeArray requireArgs = new RuntimeArray(); - RuntimeArray.push(requireArgs, new RuntimeScalar(fullName)); - RuntimeList result = RuntimeCode.apply( - GlobalVariable.getGlobalCodeRefForFreshLookup("CORE::GLOBAL::require"), - requireArgs, RuntimeContextType.SCALAR); - ret = result.isEmpty() ? scalarUndef : result.getFirst(); - } else { - ret = ModuleOperators.require(new RuntimeScalar(fullName)); + try { + if (evalRequireOverride) { + RuntimeArray requireArgs = new RuntimeArray(); + RuntimeArray.push(requireArgs, new RuntimeScalar(fullName)); + RuntimeList result = RuntimeCode.apply( + GlobalVariable.getGlobalCodeRefForFreshLookup("CORE::GLOBAL::require"), + requireArgs, RuntimeContextType.SCALAR); + ret = result.isEmpty() ? scalarUndef : result.getFirst(); + } else { + ret = ModuleOperators.require(new RuntimeScalar(fullName)); + } + } finally { + restoreStack(ctx.symbolTable.strictOptionsStack, savedRequireStrict); + restoreStack(ctx.symbolTable.featureFlagsStack, savedRequireFeatures); + restoreStack(ctx.symbolTable.warningFlagsStack, savedRequireWarnings); + restoreStack(ctx.symbolTable.warningFatalStack, savedRequireFatalWarnings); + restoreStack(ctx.symbolTable.warningDisabledStack, savedRequireDisabledWarnings); } // A module loaded by `use` may invoke re->import while its // own compilation unit is active. That pragma is lexical to diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java index 33540a0b24..a8a828472b 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java @@ -5991,8 +5991,7 @@ public static RuntimeList evalStringWithInterpreter( /** Perl forbids compiling tainted eval STRING input while -T is active. */ public static void rejectTaintedEval(RuntimeScalar code) { if (code != null && code.isTainted() && GlobalContext.isTaintModeActive()) { - throw new PerlCompilerException( - "Insecure dependency in eval while running with -T switch"); + throw new TaintedEvalException(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java new file mode 100644 index 0000000000..2ba3a03c44 --- /dev/null +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java @@ -0,0 +1,8 @@ +package org.perlonjava.runtime.runtimetypes; + +/** Security failure raised when tainted source is passed to eval under -T. */ +public final class TaintedEvalException extends PerlCompilerException { + public TaintedEvalException() { + super("Insecure dependency in eval while running with -T switch"); + } +} diff --git a/src/main/perl/lib/Safe.pm b/src/main/perl/lib/Safe.pm index 6646f81ee7..105ff2b708 100644 --- a/src/main/perl/lib/Safe.pm +++ b/src/main/perl/lib/Safe.pm @@ -60,6 +60,8 @@ sub _masked_operation { sub reval { my ($self, $code, $strict) = @_; + my $caller_package = caller; + if (my $op = $self->_masked_operation($code)) { $@ = "'$op' trapped by operation mask"; return undef; @@ -68,9 +70,13 @@ sub reval { # For PerlOnJava, we trust CPAN metadata - no sandboxing needed # The $strict parameter is ignored (would enable 'use strict' in real Safe) - # Wrap code to disable strict vars - CHECKSUMS files use $cksum without declaration - # The 'no strict "vars"' must be part of the eval'd code itself - my $wrapped = qq{no strict 'vars'; $code}; + # Safe::share records symbols from the caller's package. Evaluate in that + # package so strict subs can resolve a shared bareword sub call, while + # retaining this compatibility layer's existing strict-vars behavior. + my $eval_package = $self->{shared_package} || $caller_package || 'Safe'; + $eval_package = 'Safe' + unless $eval_package =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/; + my $wrapped = qq{package $eval_package; no strict 'vars'; $code}; # Simple eval - just return the result my $result = eval $wrapped; @@ -146,12 +152,14 @@ sub mask { # Share variables with compartment - stub sub share { my ($self, @vars) = @_; + $self->{shared_package} //= caller; push @{$self->{share} //= []}, @vars; return $self; } sub share_from { my ($self, $pkg, $vars) = @_; + $self->{shared_package} //= $pkg; push @{$self->{share_from}{$pkg} //= []}, @$vars; return $self; } diff --git a/src/test/resources/unit/safe_shared_sub_strict.t b/src/test/resources/unit/safe_shared_sub_strict.t new file mode 100644 index 0000000000..0d7c035e62 --- /dev/null +++ b/src/test/resources/unit/safe_shared_sub_strict.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Safe; +use Test::More; + +{ + package SafeSharedSubProbe; + sub value() { $_ } + + our $COMPARTMENT; + BEGIN { + $COMPARTMENT = Safe->new; + $COMPARTMENT->permit(':base_core'); + $COMPARTMENT->share('value'); + } + + sub check { + local $_ = 3; + my $result = $COMPARTMENT->reval('value == 3'); + die $@ if $@; + return $result; + } +} + +ok(SafeSharedSubProbe::check(), + 'Safe::share makes a shared sub visible to strict compartment eval'); + +done_testing(); diff --git a/src/test/resources/unit/strict_isa_declared_after_assignment.t b/src/test/resources/unit/strict_isa_declared_after_assignment.t new file mode 100644 index 0000000000..540ed34bd5 --- /dev/null +++ b/src/test/resources/unit/strict_isa_declared_after_assignment.t @@ -0,0 +1,22 @@ +use warnings; +use Test::More; + +{ + package StrictIsaDeclaredAfterAssignment; + package StrictIsaBase; + + package StrictIsaDeclaredAfterAssignment; + use Pod::Simple; + @ISA = qw(Pod::Simple); + use strict; + use vars qw($VERSION @ISA); + + our $VERSION = '0'; +} + +ok(StrictIsaDeclaredAfterAssignment->isa('Pod::Simple'), + 'use vars declaration permits earlier @ISA assignment'); +is_deeply(\@StrictIsaDeclaredAfterAssignment::ISA, ['Pod::Simple'], + '@ISA retains its assigned parent'); + +done_testing(); diff --git a/src/test/resources/unit/tainted_eval_security_propagation.t b/src/test/resources/unit/tainted_eval_security_propagation.t new file mode 100644 index 0000000000..067b53471f --- /dev/null +++ b/src/test/resources/unit/tainted_eval_security_propagation.t @@ -0,0 +1,23 @@ +#!perl -T +use strict; +use warnings; +use Test::More; + +my $tainted_source = '1' . substr($0, 0, 0); + +sub render_tainted_source { + my $result = eval $tainted_source; + return $@ ? 'template error' : $result; +} + +my $completed = eval { + render_tainted_source(); + 1; +}; + +ok(!defined($completed), + 'tainted eval security error propagates past the attempted eval'); +like($@, qr/^Insecure dependency in eval while running with -T switch/, + 'outer eval receives the taint security error'); + +done_testing(); From 455ff0acc3a0872b04b8b870aa1f9ac85984a764 Mon Sep 17 00:00:00 2001 From: "Flavio S. Glock" Date: Thu, 12 Nov 2026 17:20:30 +0100 Subject: [PATCH 2/2] fix: limit Safe shared subs to the compartment Install explicitly shared code symbols into the Safe compartment namespace before eval, keeping unrelated caller subs unavailable. Add regression coverage for both shared and unshared subroutines. Refs: #2033 Generated with OpenAI Codex (https://openai.com/codex) Co-Authored-By: OpenAI Codex <158243242+openai-codex[bot]@users.noreply.github.com> --- src/main/perl/lib/Safe.pm | 41 +++++++++++++++---- .../resources/unit/safe_shared_sub_strict.t | 21 ++++++++++ 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/src/main/perl/lib/Safe.pm b/src/main/perl/lib/Safe.pm index 105ff2b708..88c8988025 100644 --- a/src/main/perl/lib/Safe.pm +++ b/src/main/perl/lib/Safe.pm @@ -57,11 +57,24 @@ sub _masked_operation { return; } +sub _install_shared_subs { + my ($self) = @_; + my $namespace = $self->{namespace}; + return unless $namespace =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/; + + no strict 'refs'; + for my $source_package (keys %{$self->{shared_subs} // {}}) { + next unless $source_package =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/; + for my $name (keys %{$self->{shared_subs}{$source_package}}) { + my $code = *{"${source_package}::${name}"}{CODE}; + *{"${namespace}::${name}"} = $code if $code; + } + } +} + sub reval { my ($self, $code, $strict) = @_; - my $caller_package = caller; - if (my $op = $self->_masked_operation($code)) { $@ = "'$op' trapped by operation mask"; return undef; @@ -70,10 +83,11 @@ sub reval { # For PerlOnJava, we trust CPAN metadata - no sandboxing needed # The $strict parameter is ignored (would enable 'use strict' in real Safe) - # Safe::share records symbols from the caller's package. Evaluate in that - # package so strict subs can resolve a shared bareword sub call, while - # retaining this compatibility layer's existing strict-vars behavior. - my $eval_package = $self->{shared_package} || $caller_package || 'Safe'; + # Install only explicitly shared subs into the compartment stash, then + # evaluate there so strict subs resolves those names without exposing the + # rest of the caller's package. + _install_shared_subs($self); + my $eval_package = $self->{namespace}; $eval_package = 'Safe' unless $eval_package =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/; my $wrapped = qq{package $eval_package; no strict 'vars'; $code}; @@ -152,14 +166,25 @@ sub mask { # Share variables with compartment - stub sub share { my ($self, @vars) = @_; - $self->{shared_package} //= caller; + my $source_package = caller; + for my $requested_name (@vars) { + my $name = $requested_name; + $name =~ s/^&//; + next unless $name =~ /\A[A-Za-z_]\w*\z/; + $self->{shared_subs}{$source_package}{$name} = 1; + } push @{$self->{share} //= []}, @vars; return $self; } sub share_from { my ($self, $pkg, $vars) = @_; - $self->{shared_package} //= $pkg; + for my $requested_name (@$vars) { + my $name = $requested_name; + $name =~ s/^&//; + next unless $name =~ /\A[A-Za-z_]\w*\z/; + $self->{shared_subs}{$pkg}{$name} = 1; + } push @{$self->{share_from}{$pkg} //= []}, @$vars; return $self; } diff --git a/src/test/resources/unit/safe_shared_sub_strict.t b/src/test/resources/unit/safe_shared_sub_strict.t index 0d7c035e62..50611e953b 100644 --- a/src/test/resources/unit/safe_shared_sub_strict.t +++ b/src/test/resources/unit/safe_shared_sub_strict.t @@ -25,4 +25,25 @@ use Test::More; ok(SafeSharedSubProbe::check(), 'Safe::share makes a shared sub visible to strict compartment eval'); +{ + package SafeUnsharedSubProbe; + sub hidden() { 3 } + + our $COMPARTMENT; + BEGIN { + $COMPARTMENT = Safe->new; + $COMPARTMENT->permit(':base_core'); + } + + sub check { + return $COMPARTMENT->reval('hidden() == 3'); + } +} + +my $unshared_result = SafeUnsharedSubProbe::check(); +ok(!defined($unshared_result), + 'Safe compartment eval cannot call a sub that was not shared'); +like($@, qr/Undefined subroutine .*hidden/, + 'unshared sub failure is reported by the compartment'); + done_testing();