python-iptables
python-iptables copied to clipboard
comment match mangles comment if it contains a `'` character
>>> import iptc
>>> rule = iptc.Rule()
>>> match = rule.create_match('comment')
>>> match.comment = "don't"
>>> match.comment
"don\\'t"
This makes the comment on the rule when it is added by don\'t instead of what I tried to set.
The problem seems to be in the native library:
void xtables_save_string(const char *value)
{
static const char no_quote_chars[] = "_-0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char escape_chars[] = "\"\\'";
size_t length;
const char *p;
length = strspn(value, no_quote_chars);
if (length > 0 && value[length] == 0) {
/* no quoting required */
putchar(' ');
fputs(value, stdout);
} else {
/* there is at least one dangerous character in the
value, which we have to quote. Write double quotes
around the value and escape special characters with
a backslash */
printf(" \"");
for (p = strpbrk(value, escape_chars); p != NULL;
p = strpbrk(value, escape_chars)) {
if (p > value)
fwrite(value, 1, p - value, stdout);
putchar('\\');
putchar(*p);
value = p + 1;
}
/* print the rest and finish the double quoted
string */
fputs(value, stdout);
putchar('\"');
}
}
It quotes the characters ", \ and '. Let me think about a workaround here.
I pushed a commit with a workaround. Feel free to give it a shot, though I'm still thinking whether this is the right way to work around the issue.
Parsing also fails when the comment contains an exclamation mark. How about using shlex instead of a regex ?
@multun do you mean when parsing the output from save()?
@ldx yup https://github.com/ldx/python-iptables/blob/e42e691732ec93d1bc05a954012246e78827f8d3/iptc/ip4tc.py#L392