What does it mean to use a string that was entered by the user as a format control and why is this a security breach?

I read this error prevention tip (3.1) in Deitel and Deitel, Java: How to Program. I do not understand what it means. I only know that it was a line of code below:

// display the name stored in object myAccount
System.out.printf("Name in object myAccount is:%n%s%n", myAccount.getName());

This paragraph is as follows:

Never use the string entered by the user as the control format. When a method System.out.printfevaluates a format control string in its first argument, the method performs tasks based on the conversion qualifiers (specifications) in that string. If a format control string was obtained from the user, an attacker could provide conversion qualifiers that would be executed by using it System.out.printf, which could lead to a security breach.

+4
source share
1 answer

Strictly speaking, using string input by the user to control the format would look like this:

String format=getFromUser(...);
System.out.printf(format, arg1, arg2, arg3...);

, , , @JohnKugelman, , :

  • - , WrongFormatConversion :
    @Test
    public void wrongMask()
    {
        String s="january";
        System.out.printf("%)/$#", s);
    }
  • , a MissingFormatArgumentException :
    @Test
    public void highArgumentIndex()
    {
        String s="january";
        System.out.printf("%1000$s%n", s);
    }
  • , ​​ , :
    @Test
    public void highFieldWidth()
    {
        String s="january";
        System.out.printf("%1000000s%n", s);
    }
  • , number, , , (, , ).
    @Test
    public void highArgumentWidth()
    {
        int n=12;
        System.out.printf("%01000000d%n", n);
    }

. , , , OutOfMemoryError .

( , , , ).

, , .

Update

, , , :

    public static void main(String[] args)
    {
        String format=args[0];
        int n=12;
        System.out.printf(format, n);
    }

, . :

  • %)/$#
  • %1000$d
  • %1000000d
  • %01000000d

Conclussion: ​​, .

+3

Source: https://habr.com/ru/post/1673845/


All Articles