What is the best way to escape Python strings in PHP? -
i have php application needs output python script, more bunch of variable assignment statements, eg.
subject_prefix = 'this string user input' msg_footer = """this 1 too."""
the contents of subject_prefix et al need written take user input; such, need escape contents of strings. writing following isn't going cut it; we're stuffed uses quote or newline or else i'm not aware of hazardous:
echo "subject_prefix = '".$subject_prefix."'\n";
so. ideas?
(rewriting app in python isn't possible due time constraints. :p )
edit, years later:
this integration between web-app (written in php) , mailman (written in python). couldn't modify install of latter, needed come way talk in language manage configuration.
this really bad idea.
do not try write function in php. inevitably wrong , application inevitably have arbitrary remote execution exploit.
first, consider problem solving. presume trying data php python. might try write .ini file rather .py file. python has excellent ini syntax parser, configparser. can write obvious, , potentially incorrect, quoting function in php , nothing serious happen if (read: when) wrong.
you write xml file. there many xml parsers , emitters php , python me list here.
if really can't convince terrible, terrible idea, can @ least use pre-existing function python has doing such thing: repr()
.
here's handy php function run python script you:
<?php function py_escape($input) { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w") ); $process = proc_open( "python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'", $descriptorspec, $pipes); fwrite($pipes[0], $input); fclose($pipes[0]); $chunk_size = 8192; $escaped = fread($pipes[1], $chunk_size); if (strlen($escaped) == $chunk_size) { // important security. die("that string's big.\n"); } proc_close($process); return $escaped; } // example usage: $x = "string \rfull \nof\t crappy stuff"; print py_escape($x);
the chunk_size
check intended prevent attack whereby input ends being 2 long strings, ("hello " + ("." * chunk_size))
, '; os.system("do bad stuff")
respectively. now, naive attack won't work exactly, because python won't let single-quoted string end in middle of line, , quotes in system()
call quoted, if attacker manages line continuation ("\") right place , use os.system(map(chr, ...))
can inject code run.
i opted read 1 chunk , give if there more output, rather continuing read , accumulate, because there limits on python source file line length; know, attack vector. python not intended secure against arbitrary people writing arbitrary source code on system area unlikely audited.
the fact had think of this trivial example example of why shouldn't use python source code data interchange format.
Comments
Post a Comment