Skip to content

Fix code injection via unvalidated Op attr/arg names (GHSA-2xp6-8g4h-qw72) - #124374

Merged
copybara-service[bot] merged 6 commits into
tensorflow:masterfrom
prasanna8585:fix/ghsa-2xp6-8g4h-qw72-attr-arg-name-validation
Aug 27, 2026
Merged

copybara-service[bot] merged 6 commits into
tensorflow:masterfrom
prasanna8585:fix/ghsa-2xp6-8g4h-qw72-attr-arg-name-validation

Conversation

@prasanna8585

@prasanna8585 prasanna8585 commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the code-injection class reported in GHSA-2xp6-8g4h-qw72

Root cause: ValidateOpDef()/ValidateArg() in tensorflow/core/framework/op_def_util.cc validate the op's own name against IsValidOpName, but never validate the character set of OpDef.AttrDef.name() or OpDef.ArgDef.name() -- only their uniqueness. cc_op_gen.cc and python_op_gen.cc splice these names
directly into generated C++/Python source with no escaping, so a crafted name containing ", ), ;, or , breaks out of its syntactic context and injects arbitrary code, executed at compiletime (C++, dynamically confirmed in the advisory) or import time (Python).

This mirrors the fix already applied to the sibling file cc_op_fuzz_gen.cc (absl::CEscape on parsed proto strings), but that fix didn't cover the primary C++ generator or the Python generator.

Fix in this PR:

  1. Adds IsValidAttrOrArgName() -- a safe-identifier check requiring names to start with a letter/underscore and contain only letters/digits/underscores -- and applies it in both ValidateOpDef() (attr names) and ValidateArg() (arg names). This closes the bug at the single validation choke-point that all op registration paths go through, so it protects both known generators plus any future consumer, rather than requiring every downstream splice site to escape correctly and consistently.
  2. Applies absl::CEscape() at the cc_op_gen.cc splice site (.Attr("<name>", ...)) as defense-in-depth, matching the cc_op_fuzz_gen.cc precedent.

Verification: Standalone harness confirms the exact malicious attribute name from the advisory (evil"); system("touch /tmp/PWNED..."); //) is rejected by the new validator, while legitimate names (dtype, T, num_threads_2, _internal, etc.) continue to pass. Independently, the CEscape defense-in-depth was verified to neutralize the same payload into an inert string literal even in isolation.

…qw72)

ValidateOpDef()/ValidateArg() in op_def_util.cc validated the op's own
name against IsValidOpName but never validated the character set of
attribute names (OpDef.AttrDef.name()) or argument names
(OpDef.ArgDef.name()) -- only their uniqueness.

TensorFlow's op-wrapper code generators (cc_op_gen.cc, python_op_gen.cc)
splice these names directly into generated C++/Python source with no
escaping. A crafted attr/arg name containing ", ), ;, or a comma can
break out of its syntactic context and inject arbitrary code, executed
at compile time (C++) or import time (Python) of the generated wrapper.
This is the same class of bug already fixed in the sibling file
cc_op_fuzz_gen.cc (escaping via absl::CEscape).

This change:
  1. Adds IsValidAttrOrArgName(), a safe-identifier check (must start
     with a letter/underscore, contain only letters/digits/underscores),
     and applies it in ValidateOpDef() and ValidateArg(). This closes
     the injection class at the single validation choke-point, so it
     protects every current and future downstream consumer -- not just
     the two known generators.
  2. Applies absl::CEscape() to graph_attr.name() at the cc_op_gen.cc
     splice site as defense-in-depth, matching the precedent already
     merged in cc_op_fuzz_gen.cc.

Fixes GHSA-2xp6-8g4h-qw72.
@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Jul 30, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces validation for attribute and argument names in TensorFlow OpDefs to ensure they only contain safe characters (letters, digits, and underscores starting with a letter or underscore), preventing code injection when generating C++ and Python wrappers. It also escapes graph attribute names in C++ code generation. The review feedback suggests improving the IsValidAttrOrArgName implementation by using Abseil's locale-independent ASCII utility functions (absl::ascii_isalpha and absl::ascii_isalnum) instead of std::isalpha and Scanner.

…rArgName

Per gemini-code-assist review feedback on PR tensorflow#124374: std::isalpha is
locale-dependent and can behave unexpectedly depending on environment
locale settings, and mixing it with Scanner's strictly-ASCII character
classes was inconsistent. Replaces both with Abseil's locale-independent
ASCII utility functions (absl::ascii_isalpha, absl::ascii_isalnum),
which also simplifies the function and drops the Scanner dependency
entirely.

No behavioral change: verified against the same test vectors as before
(malicious attr name from the advisory rejected; legitimate names like
dtype, T, num_threads_2, _internal still accepted).
@keerthanakadiri
keerthanakadiri requested a review from a team July 31, 2026 03:19
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 31, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 31, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Findings

  1. Inconsistency in PR Description vs Implementation:
    The PR description mentions applying absl::CEscape to both C++ and Python generator paths for defense-in-depth. However, the changes in this PR only cover cc_op_gen.cc (C++) and op_def_util.cc (Validation). The Python generator path (python_op_gen.cc) is missing these changes.

    If defense-in-depth escaping is desired, it should be applied to python_op_gen.cc as well (e.g. where attribute names are spliced into Python string literals). If you believe validation is sufficient for Python, please update the description to reflect that absl::CEscape is only applied to the C++ generator.

  2. Defense-in-Depth Incomplete in C++ Generator:
    The absl::CEscape fix in cc_op_gen.cc only covers the .Attr(...) string literal splice site. However, attribute/argument names are also used as parameter names in generated function signatures (e.g. in GetConstructorDecl). If validation is bypassed, a malicious name will still appear unescaped in these signatures, likely causing compiler errors. While this acts as a blocker, it is inconsistent with the escaping applied elsewhere.

  3. Missing Unit Tests:
    The PR is missing regression tests to ensure that invalid names are correctly rejected by the validation logic, and that the defense-in-depth escaping works as expected.

Suggested Tests

You can add the following tests to tensorflow/core/framework/op_def_util_test.cc to verify the validation logic.

tensorflow/core/framework/op_def_util_test.cc

TEST_F(ValidateOpDefTest, InvalidAttrOrArgName) {
  // Invalid characters in attribute name
  ExpectFailure(
      TestProto("name: 'BadAttrName' attr { name: 'evil\\\"); system(\\\"touch /tmp/PWNED...\\\"); //' type: 'int' }"),
      "Invalid attr name");
  
  // Invalid start character in attribute name
  ExpectFailure(
      TestProto("name: 'BadAttrName' attr { name: '123_invalid' type: 'int' }"),
      "Invalid attr name");

  // Invalid characters in argument name
  ExpectFailure(
      TestProto("name: 'BadArgName' input_arg { name: 'evil\\\"); system(\\\"touch /tmp/PWNED...\\\"); //' type: DT_INT32 }"),
      "Invalid argument name");

  // Invalid start character in argument name
  ExpectFailure(
      TestProto("name: 'BadArgName' input_arg { name: '123_invalid' type: DT_INT32 }"),
      "Invalid argument name");
}

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Aug 2, 2026
Per review feedback on this PR:

1. The PR description claimed defense-in-depth escaping was applied to
   both generators, but python_op_gen.cc was untouched. Investigating
   why revealed the real issue: both generators splice names into
   IDENTIFIER positions (C++ parameter names, Python keyword argument
   names) via ApiDef.Arg/Attr.rename_to() -- a field entirely separate
   from the OpDef.ArgDef/AttrDef.name() fields validated by
   ValidateOpDef/ValidateArg. CEscape (for string literals) doesn't
   apply to identifier positions at all, so 'add escaping to
   python_op_gen.cc' was the wrong frame -- rename_to() needed
   validation, not escaping, in both generators.

2. This also directly addresses the GetConstructorDecl() case flagged
   in review: op_info.arg_names[i] traces to
   AvoidCPPKeywords(api_def_arg.rename_to()) in cc_op_gen_util.cc,
   which was unvalidated. Same pattern for the attr_name construction
   a few lines below it.

   Fix: expose IsValidAttrOrArgName() via op_def_util.h (previously
   file-local to op_def_util.cc) and validate rename_to() at its use
   sites in cc_op_gen_util.cc and python_op_gen.cc's ParamNames
   constructor, falling back to the original, already-validated
   OpDef name when rename_to() isn't a safe identifier. rename_to is
   a display-name preference, not required data, so a safe fallback
   is more appropriate than a hard failure.

3. Adds the suggested regression tests to op_def_util_test.cc,
   covering invalid characters and invalid start characters for both
   attribute and argument names.
@prasanna8585
prasanna8585 requested a review from dmiltr3 August 3, 2026 04:29
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 3, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 3, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Aug 3, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 4, 2026
@prasanna8585

Copy link
Copy Markdown
Contributor Author

Hi @dmiltr3 ,

Just following up to check if any additional changes or steps are needed on my end, or if this is ready to be merged.

Thanks!

@prasanna8585

Copy link
Copy Markdown
Contributor Author

Hi @dmiltr3 ,

Just following up to check if any additional changes or steps are needed on my end, or if this is ready to be merged.

@nithyak0204

Copy link
Copy Markdown

Hi @prasanna8585, Sorry for the delay, this PR is waiting for internal approvals. We are working on it. Thank you!

@dmiltr3
dmiltr3 self-requested a review August 24, 2026 18:15
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Aug 24, 2026

@dmiltr3 dmiltr3 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @prasanna8585,

Thank you for your contribution and for addressing the security issue in PR #124374!

During internal Google presubmit testing on import, the build failed due to a missing dependency in the Bazel BUILD file for op_def_util.

Error Details

In tensorflow/core/framework/op_def_util.cc, the change includes absl/strings/ascii.h for absl::ascii_isalpha and absl::ascii_isalnum. However, tensorflow/core/framework/BUILD does not declare @com_google_absl//absl/strings under the deps of cc_library(name = "op_def_util").

Under strict module and layering checks, this causes compilation to fail across downstream targets:

error: module //third_party/tensorflow/core/framework:op_def_util does not directly depend on a module exporting 'third_party/absl/strings/ascii.h', which is part of indirectly-used module third_party/absl/strings/ascii.h
see internal documentation

Suggested Fix

Please update tensorflow/core/framework/BUILD to add @com_google_absl//absl/strings to the deps attribute of the op_def_util target:

cc_library(
    name = "op_def_util",
    srcs = ["op_def_util.cc"],
    hdrs = ["op_def_util.h"],
    deps = [
        ":api_def_proto_cc",
        ":attr_value_proto_cc",
        ":attr_value_util",
        ":op_def_proto_cc",
        ":tensor",
        "@com_google_absl//absl/container:flat_hash_map",
        "@com_google_absl//absl/container:flat_hash_set",
        "@com_google_absl//absl/strings",
        "//tensorflow/core/lib/core:errors",
        ...
    ],
)

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Aug 24, 2026
@twubndgsijlc-netizen

twubndgsijlc-netizen commented Aug 24, 2026 via email

Copy link
Copy Markdown

@twubndgsijlc-netizen

twubndgsijlc-netizen commented Aug 24, 2026 via email

Copy link
Copy Markdown

@twubndgsijlc-netizen

twubndgsijlc-netizen commented Aug 24, 2026 via email

Copy link
Copy Markdown

@twubndgsijlc-netizen

twubndgsijlc-netizen commented Aug 24, 2026 via email

Copy link
Copy Markdown

Addresses dmiltr3's review: Google's internal presubmit on import
failed because tensorflow/core/framework/BUILD's op_def_util
cc_library target did not declare @com_google_absl//absl/strings in
its deps, even though op_def_util.cc includes absl/strings/ascii.h
(for absl::ascii_isalpha / absl::ascii_isalnum, used by this PR's own
fix). Under strict layering checks this failed compilation for
anything depending on op_def_util:

  error: module //third_party/tensorflow/core/framework:op_def_util
  does not directly depend on a module exporting
  'third_party/absl/strings/ascii.h' ...

Adds "@com_google_absl//absl/strings" to that target's deps, in the
same place and form as the reviewer's own suggested diff.

Verified: op_def_util.cc's use of absl/strings/ascii.h confirmed
current before editing. Basic Starlark/Python-like syntax check on
the whole BUILD file passes after the edit -- this sandbox has no
Bazel available, so a real 'bazel build' could not be run here; please
confirm CI passes.
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Aug 25, 2026
@prasanna8585
prasanna8585 requested a review from dmiltr3 August 25, 2026 14:51

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! All review points have been addressed, including the missing Abseil dependency in tensorflow/core/framework/BUILD and the regression tests for attribute/argument name validation. Internal presubmits and unit tests pass cleanly.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 25, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 25, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Presubmit Test Failures and Required Fix

1. Root Cause of Failures

The changes in this PR caused internal presubmit test failures across 1,400+ targets (including tensorflow/lite/python:interpreter_test, tensorflow/lite/testing/keras:dense_test, etc.).

During test initialization, op registration fails with a fatal error:

Check failed: RegisterAlreadyLocked(op_data_factory) is OK (INVALID_ARGUMENT: Invalid argument name: raw_outputs/box_encodings (must start with a letter or underscore and contain only letters, digits, and underscores); in OpDef: name: "TFLite_Detection_PostProcess" input_arg { name: "raw_outputs/box_encodings" type: DT_FLOAT } input_arg { name: "raw_outputs/class_predictions" type: DT_FLOAT } output_arg { name: "TFLite_Detection_PostProcess:1" type: DT_FLOAT } ...)

Why this occurs:

  • ValidateOpDef() and ValidateArg() in tensorflow/core/framework/op_def_util.cc run at runtime for every op registered in OpRegistry (both built-in and dynamically registered custom ops).
  • Several legitimate ops (such as TFLite_Detection_PostProcess registered in tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc and other custom ops) use input argument names containing / (e.g. raw_outputs/box_encodings) and output argument names containing : (e.g. TFLite_Detection_PostProcess:1).
  • Applying the strict identifier check IsValidAttrOrArgName inside ValidateOpDef() and ValidateArg() breaks backwards compatibility with these valid runtime op definitions.

2. Recommended Fix

The code injection vulnerability (GHSA-2xp6-8g4h-qw72) stems from the code generation tools (cc_op_gen.cc, python_op_gen.cc, cc_op_gen_util.cc) splicing unescaped attribute/argument names directly into generated C++ and Python source files.

The fix should protect the code generation splice sites rather than rejecting valid runtime OpDef argument names in op_def_util.cc:

  1. Remove runtime validation from ValidateArg() and ValidateOpDef() in tensorflow/core/framework/op_def_util.cc:
    Do not reject OpDef argument or attribute names containing valid characters like / or : at runtime.
    Keep IsValidAttrOrArgName() in tensorflow/core/framework/op_def_util.h / tensorflow/core/framework/op_def_util.cc as a utility function for code generators.

  2. Sanitize / escape at the code generator level:

    • In tensorflow/cc/framework/cc_op_gen.cc: Continue using absl::CEscape() for string literals (.Attr("<name>", ...)).
    • In tensorflow/cc/framework/cc_op_gen_util.cc: When creating C++ parameter names (op_info.arg_names), ensure non-identifier characters are sanitized or validated against IsValidAttrOrArgName() with a fallback to safe identifiers.
    • In tensorflow/python/framework/python_op_gen.cc: In ParamNames, continue ensuring that rename_to (and parameter names) are safe Python identifiers, falling back to a sanitized name if invalid characters are present.

3. Suggested Code Changes

In tensorflow/core/framework/op_def_util.cc:

--- a/tensorflow/core/framework/op_def_util.cc
+++ b/tensorflow/core/framework/op_def_util.cc
@@ -198,10 +198,6 @@ static absl::Status ValidateArg(const OpDef::ArgDef& arg, const OpDef& op_def,
       absl::StrCat(output ? " for output '" : " for input '", arg.name(), "'");
   VALIDATE(names->emplace(arg.name()).second, "Duplicate name: ", arg.name());
-  VALIDATE(IsValidAttrOrArgName(arg.name()),
-           "Invalid argument name: ", arg.name(),
-           " (must start with a letter or underscore and contain only "
-           "letters, digits, and underscores)");
   VALIDATE(HasAttrStyleType(arg), "Missing type", suffix);
 
   if (!arg.number_attr().empty()) {
@@ -305,10 +301,6 @@ absl::Status ValidateOpDef(const OpDef& op_def) {
   for (const auto& attr : op_def.attr()) {
     // Validate name
     VALIDATE(names.emplace(attr.name()).second,
              "Duplicate name: ", attr.name());
-    VALIDATE(IsValidAttrOrArgName(attr.name()),
-             "Invalid attr name: ", attr.name(),
-             " (must start with a letter or underscore and contain only "
-             "letters, digits, and underscores)");
     DataType dt;
     VALIDATE(!DataTypeFromString(attr.name(), &dt), "Attr can't have name ",

In tensorflow/core/framework/op_def_util_test.cc:

  • Update or remove unit tests that expect ValidateOpDef to fail on names with non-identifier characters if ValidateOpDef is no longer doing runtime rejection.

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Aug 25, 2026

@dmiltr3 dmiltr3 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @prasanna8585,

Thank you for your work addressing GHSA-2xp6-8g4h-qw72 in this PR!

During internal Google presubmit testing, the current changes caused 1,400+ internal test/build failures across TensorFlow (specifically in TFLite conversion, MLIR tests, and Keras test targets).

1. Root Cause of Presubmit Failures

During test initialization, op registration fails with a fatal error:

Check failed: RegisterAlreadyLocked(op_data_factory) is OK (INVALID_ARGUMENT: Invalid argument name: raw_outputs/box_encodings (must start with a letter or underscore and contain only letters, digits, and underscores); in OpDef: name: "TFLite_Detection_PostProcess" input_arg { name: "raw_outputs/box_encodings" type: DT_FLOAT } input_arg { name: "raw_outputs/class_predictions" type: DT_FLOAT } output_arg { name: "TFLite_Detection_PostProcess:1" type: DT_FLOAT } ...)

Why this occurs:

  • ValidateOpDef() and ValidateArg() in tensorflow/core/framework/op_def_util.cc execute at runtime for all OpDef registrations across the TensorFlow runtime (including dynamically registered custom ops and MLIR/TFLite converter definitions).
  • Several legitimate ops (such as TFLite_Detection_PostProcess in tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc) use scoped argument names containing / (e.g., raw_outputs/box_encodings) and indexed output names containing : (e.g., TFLite_Detection_PostProcess:1).
  • Enforcing the strict identifier check IsValidAttrOrArgName() inside ValidateArg() breaks backwards compatibility with these valid runtime op definitions.

2. Recommended Fix

The code injection vulnerability (GHSA-2xp6-8g4h-qw72) occurs when code generation tools (cc_op_gen.cc, cc_op_gen_util.cc, python_op_gen.cc) splice unescaped names directly into generated C++ or Python source files.

The protection belongs at the code generator splice sites rather than rejecting non-identifier argument names globally in ValidateArg() at runtime:

  1. Remove runtime argument rejection from ValidateArg() (and ValidateOpDef() for attr names) in tensorflow/core/framework/op_def_util.cc:

    • Keep IsValidAttrOrArgName() in tensorflow/core/framework/op_def_util.h / op_def_util.cc as a shared utility function for code generators.
    • Do not reject valid runtime OpDef argument names containing / or :.
  2. Protect the code generator splice sites:

    • In tensorflow/cc/framework/cc_op_gen.cc: Continue escaping string literals via absl::CEscape(graph_attr.name()).
    • In tensorflow/cc/framework/cc_op_gen_util.cc: When generating C++ parameter names, ensure names containing non-identifier characters are sanitized or fall back to safe identifiers via IsValidAttrOrArgName().
    • In tensorflow/python/framework/python_op_gen.cc: In ParamNames, ensure rename_to / parameter names fall back to safe identifiers when non-identifier characters are encountered.
  3. Update regression unit tests:

    • In tensorflow/core/framework/op_def_util_test.cc, update tests to reflect that ValidateOpDef/ValidateArg does not fail on argument names with / or :.

3. Suggested Diff

In tensorflow/core/framework/op_def_util.cc:

--- a/tensorflow/core/framework/op_def_util.cc
+++ b/tensorflow/core/framework/op_def_util.cc
@@ -198,10 +198,6 @@ static absl::Status ValidateArg(const OpDef::ArgDef& arg, const OpDef& op_def,
       absl::StrCat(output ? " for output '" : " for input '", arg.name(), "'");
   VALIDATE(names->emplace(arg.name()).second, "Duplicate name: ", arg.name());
-  VALIDATE(IsValidAttrOrArgName(arg.name()),
-           "Invalid argument name: ", arg.name(),
-           " (must start with a letter or underscore and contain only "
-           "letters, digits, and underscores)");
   VALIDATE(HasAttrStyleType(arg), "Missing type", suffix);
 
   if (!arg.number_attr().empty()) {
@@ -305,10 +301,6 @@ absl::Status ValidateOpDef(const OpDef& op_def) {
   for (const auto& attr : op_def.attr()) {
     // Validate name
     VALIDATE(names.emplace(attr.name()).second,
              "Duplicate name: ", attr.name());
-    VALIDATE(IsValidAttrOrArgName(attr.name()),
-             "Invalid attr name: ", attr.name(),
-             " (must start with a letter or underscore and contain only "
-             "letters, digits, and underscores)");
     DataType dt;
     VALIDATE(!DataTypeFromString(attr.name(), &dt), "Attr can't have name ",

Please let us know if you have any questions or need further clarification!

Addresses review: the runtime validation added to ValidateArg/
ValidateOpDef broke internal presubmit across 1,400+ targets. Root
cause: several legitimate, already-registered ops (e.g.
TFLite_Detection_PostProcess, registered in
tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc) use
argument names containing '/' and ':' ("raw_outputs/box_encodings",
"TFLite_Detection_PostProcess:1") for reasons unrelated to code
generation. Rejecting those at OpDef registration/validation time --
which runs for every op in the runtime, not just ones that go through
code generation -- broke that legitimate, pre-existing usage.

The actual injection risk only exists where a name is spliced,
unescaped, as a raw identifier into generated C++/Python source by
cc_op_gen.cc / cc_op_gen_util.cc / python_op_gen.cc. Moves the
defense to exactly those splice sites instead of the runtime-wide
check:

1. Removes the IsValidAttrOrArgName VALIDATE() calls from ValidateArg
   and ValidateOpDef, keeping IsValidAttrOrArgName itself as a utility
   function for code generators.

2. Both cc_op_gen_util.cc and python_op_gen.cc already had a fallback
   pattern for ApiDef rename_to() built on the assumption that the
   ORIGINAL arg/attr name was "already validated" by the runtime check
   removed in (1). That assumption no longer holds, so all three call
   sites are upgraded to a three-tier fallback: rename_to if safe, else
   the original name if THAT is safe, else a new SanitizeToIdentifier()
   helper (added alongside IsValidAttrOrArgName in op_def_util.{h,cc})
   that guarantees a syntactically safe identifier for any input by
   replacing unsafe characters with underscores.

3. Replaces op_def_util_test.cc's InvalidAttrOrArgName test (which
   asserted ValidateOpDef rejects non-identifier names) with direct
   unit tests of IsValidAttrOrArgName and SanitizeToIdentifier as pure
   functions, plus a positive regression test confirming ValidateOpDef
   now accepts TFLite_Detection_PostProcess's exact real-world argument
   names.

Verified with a standalone C++ harness (no Bazel available in this
environment) reproducing both functions exactly: 14 checks, including
confirming every SanitizeToIdentifier output itself re-passes
IsValidAttrOrArgName -- the invariant the whole three-tier fallback
depends on. All 14 pass. The exact GHSA-2xp6-8g4h-qw72 payload and
TFLite_Detection_PostProcess's real argument names are both correctly
rejected by IsValidAttrOrArgName and correctly sanitized into safe
identifiers by SanitizeToIdentifier.

Please confirm the real build and the 1,400+ previously-failing
presubmit targets pass in CI before merging -- this environment has no
Bazel to verify that directly.
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Aug 25, 2026
@prasanna8585
prasanna8585 requested a review from dmiltr3 August 25, 2026 19:51

@dmiltr3 dmiltr3 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you for moving the defense to the code-generation splice sites and adding comprehensive unit tests. All internal presubmit tests (11,900+ targets) passed cleanly.

@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Aug 25, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 25, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Presubmit Failure Summary

Static analysis (SensitiveApiFuzzingCheck) flagged unvalidated ApiDef rename_to values in the C++ operator wrapper generators:

  • tensorflow/cc/framework/cc_op_gen_util.cc
  • tensorflow/cc/framework/cc_op_gen.cc

Root Cause Analysis

While python_op_gen.cc was updated to sanitize rename_to via tensorflow::IsValidAttrOrArgName and tensorflow::SanitizeToIdentifier, several code-generation paths in the C++ op generator still concatenate raw api_def_arg.rename_to() and api_def_attr.rename_to() values directly into generated C++ source code templates (e.g. for output names and attribute structures in cc_op_gen_util.cc and constructor input bindings in cc_op_gen.cc).


Required Fix

Apply the same sanitization pattern to rename_to values in tensorflow/cc/framework/cc_op_gen_util.cc and tensorflow/cc/framework/cc_op_gen.cc.

Create a helper function (or inline check) to sanitize rename_to before passing to AvoidCPPKeywords or splicing into C++ code:

std::string SafeRenameTo(const std::string& name, const std::string& rename_to) {
  if (tensorflow::IsValidAttrOrArgName(rename_to)) {
    return rename_to;
  }
  if (tensorflow::IsValidAttrOrArgName(name)) {
    return name;
  }
  return tensorflow::SanitizeToIdentifier(name);
}

And use it when extracting argument/attribute names from ApiDef in cc_op_gen_util.cc (lines ~570, ~596, ~633) and cc_op_gen.cc (lines ~122, ~216, ~242).

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Aug 26, 2026
…he C++ op generators

Addresses review round 3 (SensitiveApiFuzzingCheck): several C++
operator-wrapper code-generation paths in cc_op_gen_util.cc and
cc_op_gen.cc still concatenated raw, unsanitized ApiDef rename_to()
values directly into generated C++ source, even after the previous
round fixed python_op_gen.cc and two call sites in cc_op_gen_util.cc.

Adds a single shared SafeRenameTo(name, rename_to) helper to
cc_op_gen_util.{h,cc} (the shared C++ code-gen utility file both
cc_op_gen.cc and cc_op_gen_util.cc already include), matching the
review's exact suggested signature and three-tier fallback: rename_to
if it's a safe identifier, else the original name if THAT is safe,
else SanitizeToIdentifier(name). Refactors the two previously-fixed
call sites to use this shared helper too, replacing duplicated inline
ternary chains with one implementation.

Fixes every remaining unsanitized splice site found, beyond the
reviewer's own list:
  - cc_op_gen_util.cc: output_names (mirrors the already-fixed input
    case in the same constructor)
  - cc_op_gen_util.cc's GetOpAttrStruct(): four separate splice points
    for the same attribute (the setter method name, the field-access
    expression, the static defaults function name, and the struct
    field declaration) -- computed once per loop iteration so all four
    agree on the same identifier
  - cc_op_gen.cc: the static Attrs::<Name>(x) helper generator (a
    near-duplicate of GetOpAttrStruct's setter-name generation)
  - cc_op_gen.cc's GetConstructorBody(): the input-arg declaration
    loop AND the separate .Input() reference loop, which reference the
    same generated local variable by name from two different loops
    over parallel ApiDef arg lists -- both fixed with the identical
    sanitization call so the generated .Input(_name) reference always
    matches its auto _name = ... declaration
  - cc_op_gen.cc's .Attr() value-reference (both the attrs.<name>_
    field-access form and the bare-identifier form)

Verified with standalone C++ harnesses (no Bazel in this environment):
SafeRenameTo itself passes 6 checks (normal case, unsafe-rename_to/
safe-name fallback, TFLite_Detection_PostProcess's real both-unsafe
case, the exact GHSA payload in both fields, empty rename_to, a
colon-suffixed output name), confirming every result is itself a
valid identifier. A second harness specifically confirms the
GetConstructorBody consistency invariant: the declaration loop and
the .Input() loop, called independently with the same (name,
rename_to) pair, always produce byte-identical output. Confirmed via
grep that zero unsanitized .rename_to() calls remain in either file --
every occurrence is now an argument to SafeRenameTo. Please confirm
the real build passes (specifically //tensorflow/cc:cc_ops or
equivalent) before merging.
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Aug 26, 2026
@prasanna8585
prasanna8585 requested a review from dmiltr3 August 26, 2026 04:08
@nithyak0204 nithyak0204 removed the kokoro:force-run Tests on submitted change label Aug 26, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. All feedback regarding the unvalidated rename_to splice sites in the C++ operator wrapper generators (cc_op_gen.cc and cc_op_gen_util.cc) has been addressed with the shared SafeRenameTo helper. All unit tests and presubmit builds pass cleanly.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 26, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 26, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 27, 2026
@copybara-service
copybara-service Bot merged commit 9ae9c96 into tensorflow:master Aug 27, 2026
15 of 16 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Aug 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kokoro:force-run Tests on submitted change ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

6 participants