About Format String Attack for D's *writef*()

Derek Parnell derek at nomail.afraid.org
Thu Oct 5 01:06:52 PDT 2006


On Thu, 5 Oct 2006 07:01:30 +0000 (UTC), is91042 wrote:


> The problem is *writef*() can interpret not only the first but also many
> parameters as format strings.

Agreed. 

The way I handle this is to only use the first parameter to specify the
formatting tokens, and to specify one for each subsequent parameter. 

Another is to make safe any user entered data.

For example:

 import std.stdio;
 import std.cstream;
 import std.string;

 // Replace all occurrences of '%' with '%%'
 char[] safe(char[] a)
 {
    int i;
    int j;
    j = 0;
    while(j < a.length)
    {
        i = std.string.find(a[j..$], '%');
        if (i < 0)
            break;
        i += j;
        a = a[0..i] ~ "%" ~ a[i..$];
        j = i + 2;
    }

    return a;
 }

 void main()
 {
    char[] user_name;
    writefln("Please Input your name: ");
    din.readf("%s", &user_name);

    // Safer
    writefln("A,Your name is ", safe(user_name), 
             ". And my name is Peter.");

    // My preference
    writefln("B,Your name is %s. And my name is Peter.", user_name);
 }

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
5/10/2006 6:01:41 PM



More information about the Digitalmars-d-bugs mailing list