Skip to content

Replace recursive regex with linear scan in isAlphaNumber() to fix StackOverflowError#4017

Open
bann6578-boop wants to merge 2 commits into
google:masterfrom
bann6578-boop:fix-alphanumber-stackoverflow
Open

Replace recursive regex with linear scan in isAlphaNumber() to fix StackOverflowError#4017
bann6578-boop wants to merge 2 commits into
google:masterfrom
bann6578-boop:fix-alphanumber-stackoverflow

Conversation

@bann6578-boop

Copy link
Copy Markdown

Patch Proposal: Replace recursive regex in PhoneNumberUtil.isAlphaNumber()

Context

  • Issue 525896790:
    "PhoneNumberUtil.isAlphaNumber() lacks an input length limit. A specially crafted numeric string of approximately 1,684 characters triggers recursive regex evaluation, causing a StackOverflowError and terminating the calling thread."
  • This issue is classified as a memory-related issue based on the “buganizer-system@google.com” response, requiring reproduction using OSS-Fuzz on an existing fuzzing target, or a merged patch accompanied by evidence from the original report. Java fuzzing is not currently integrated into this project’s OSS-Fuzz test coverage. The current testing scope is limited to C++ https://storage.googleapis.com/oss-fuzz-coverage/libphonenumber/reports/20260428/linux/src/libphonenumber/cpp/src/phonenumbers/report.html
    Therefore, this PR is submitted as a direct patch following the second approach.
image

Issue

The isAlphaNumber() function does not check the length of the input before evaluation VALID_ALPHA_PHONE_PATTERN ((?:.?[A-Za-z]){3}.). A string containing approximately 1,684 numeric characters can cause deep recursive evaluation in java.util.regex, resulting in a StackOverflowError, which has been confirmed on JDK 21 and JDK 25.

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
StringBuilder sb = new StringBuilder("+");
for (int i = 0; i < 1684; i++) sb.append('1');
phoneUtil.isAlphaNumber(sb.toString()); // throws StackOverflowError
  • This has been confirmed to occur consistently across more than 5 independent JVM processes, on both JDK 21
    and JDK 25, in two separate commits (593719a (June 18, 2026), 5f4c9f0(2026-6-19), one day apart.

Proposed Solution: Completely Remove the Regular Expression

Instead of simply safeguarding the existing regrex expression by checking its length, this PR
replaces VALID_ALPHA_PHONE_PATTERN with an equivalent linear character-scanning algorithm.
This eliminates the root cause of errors caused by recursive evaluation,
regardless of any length constraints:

+private static boolean hasAtLeastThreeAlphaChars(CharSequence number) {
+  int alphaCount = 0;
+  for (int i = 0; i < number.length(); i++) {
+    char c = number.charAt(i);
+    if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
+      if (++alphaCount >= 3) {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
 public boolean isAlphaNumber(CharSequence number) {
   if (!isViablePhoneNumber(number)) {
     // Number is too short, or doesn't match the basic phone number pattern.
     return false;
   }
   StringBuilder strippedNumber = new StringBuilder(number);
   maybeStripExtension(strippedNumber);
-  return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
+  return hasAtLeastThreeAlphaChars(strippedNumber);
 }

Equivalence proof

VALID_ALPHA_PHONE_PATTERN.matches() returns true if and only if the input contains at least 3 characters that match [A-Za-z] (the (?:.?[A-Za-z]){3} part requires 3 such characters, in any position, with arbitrary characters allowed to appear between or around them via the ".?" and the ".*"part at the end). In fact, this is exactly what directly counting the number of alphabetic characters checks for. It uses the same ASCII range as the base character set [A-Za-z].
Therefore, the behavior is the same for all inputs, not just equivalent.
This fix:

  • Has a time complexity of O(n) and does not use backtracking or recursion in any form. Errors of the StackOverflowError type cannot structurally occur here, rather than simply being prevented.
  • It does not require a length limit for safety, so there are no arbitrary thresholds that need to be explained or maintained.
    -Is faster than the regex for all inputs (single linear scan vs. regex engine overhead).
  • Removes the single call to VALID_ALPHA_PHONE_PATTERN, eliminating the insecure pattern from the codebase rather than just removing a reference to it.

Optional, secondary: input length guard

  • Regardless of the fix described above, the parse() function is protected by MAX_INPUT_STRING_LENGTH = 250 in the parseHelper() function; meanwhile, the isAlphaNumber() function currently has no corresponding limit. Once the regular expression above is removed, this safeguard will no longer be necessary for security purposes.
  • The hasAtLeastThreeAlphaChars() function does not involve recursion or backtracking regardless of the input length. I leave it to the maintainer to decide whether to add this limit to ensure consistency with the class’s other input-handling conventions:
public boolean isAlphaNumber(CharSequence number) {
+  if (number.length() > MAX_INPUT_STRING_LENGTH) {
+    return false;
+  }
   if (!isViablePhoneNumber(number)) {

Verification

len=500: OK (fixed), result=false
len=1683: OK (fixed), result=false
len=1684: OK (fixed), result=false
len=2000: OK (fixed), result=false
len=5000: OK (fixed), result=false
len=50000: OK (fixed), result=false

isAlphaNumber("1800MICROSOFT") = true
isAlphaNumber("325-CARS") = true
isAlphaNumber("0800 REPAIR") = true
isAlphaNumber("1-800-MY-APPLE") = true
isAlphaNumber("+14155552671") = false (expected: false)
image
  • No StackOverflowError occurred at any of the tested lengths, up to 50,000 characters. All examples of custom phone numbers (vanity numbers) from a widely referenced libphonenumber tutorial (Baeldung) still return true correctly; a phone number
    consisting only of digits still returns false correctly.
    The full official test suite passed after the fix:
mvn test -Dtest=PhoneNumberUtilTest
...
Tests run: 121, Failures: 0, Errors: 0, Skipped: 0
BUILD SUCCESS
image

Proposed Additional Tests

To capture both the fixes and the unchanged behavior in the test suite
(location:
java/libphonenumber/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java):

public void testIsAlphaNumber_longNumericInputDoesNotThrow() {
  StringBuilder sb = new StringBuilder("+");
  for (int i = 0; i < 5000; i++) {
    sb.append('1');
  }
  // Should return false (no alphabetic characters present), not throw.
  assertFalse(phoneUtil.isAlphaNumber(sb.toString()));
}

public void testIsAlphaNumber_behaviorUnchangedForValidInputs() {
  // Existing valid vanity numbers still recognized.
  assertTrue(phoneUtil.isAlphaNumber("1-800-MICROSOFT"));
  assertTrue(phoneUtil.isAlphaNumber("325-CARS"));
  // Plain numeric numbers still correctly rejected.
  assertFalse(phoneUtil.isAlphaNumber("123456789"));
  // Fewer than 3 alphabetic characters still correctly rejected.
  assertFalse(phoneUtil.isAlphaNumber("AB"));
}
  • If this PR is merged, it will meet the second condition that the administration team described in issue #525896790 on Buganizer (the merged patch includes proof of the original report).
  • I will follow up on that issue by providing a link to the PR, the merge commit, and the original report for re-evaluation.

…t StackOverflowError

isAlphaNumber() did not limit input length before evaluating
VALID_ALPHA_PHONE_PATTERN, allowing a numeric-only input of ~1684
characters to cause an uncaught StackOverflowError via unbounded
regex recursion. Unlike parse(), which is guarded by
MAX_INPUT_STRING_LENGTH, this method had no such bound.

This adds the same MAX_INPUT_STRING_LENGTH guard already used in
parseHelper() as defense-in-depth, and additionally replaces the
recursive regex VALID_ALPHA_PHONE_PATTERN with an equivalent linear
character scan (hasAtLeastThreeAlphaChars), eliminating the
recursion-based failure mode at its root rather than only guarding
against it. The replacement matches the exact ASCII [A-Za-z] range
of the original pattern, so behavior is unchanged for all valid
inputs.

Verified:
- Input up to 50,000 characters no longer throws StackOverflowError
- isAlphaNumber("1800MICROSOFT"), "325-CARS", "0800 REPAIR",
  "1-800-MY-APPLE" all still return true (no behavior change)
- isAlphaNumber("+14155552671") still returns false
- Full PhoneNumberUtilTest suite passes: 121 tests, 0 failures, 0 errors

Related: Google OSS VRP / Buganizer issue 525896790
@bann6578-boop bann6578-boop requested a review from a team as a code owner June 21, 2026 01:04
@google-cla

google-cla Bot commented Jun 21, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant