简体   繁体   中英

Print bytes into file using printf shell command

I am trying to print the following data into file, but i get the following error: "/bin/sh: 1: Syntax error: Unterminated quoted string". Here is my program:

int main(void)
{
char* argv[] =  {"/bin/sh", "-c","printf '%b' '\x7f\x45\x4c\x46\x01\x00\x02\x03' > file.bin", NULL };
execve("/bin/sh", argv, NULL);

  return 1;
}

The problem is in the null byte in the middle of above text: \x7f\x45\x4c\x46\x01\x00\x02\x03" Is there any way to do this like above?

The problem with your code is that the backslashes are interpreted in the C string, while you want to pass it as argument for the sh command.

Therefore you must double escape each backslash character.

int main(void)
{
    char* argv[] =  {"/bin/sh", "-c","printf '%b' '\\x7f\\x45\\x4c\\x46\\x01\\x00\\x02\\x03' > file.bin", NULL };
    execve("/bin/sh", argv, NULL);
    return 1;
}

There's a compiler extension that allows R"(printf '%b' '\x7f\x45\x4c\x46\x01\x00\x02\x03' > file.bin)" -- see Does C support raw string literals? , but for portability don't use it.

Also, it's not possible to pass raw null byte into execve , see those questions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM