python-iptables icon indicating copy to clipboard operation
python-iptables copied to clipboard

comment match mangles comment if it contains a `'` character

Open nickhuber opened this issue 7 years ago • 5 comments

>>> 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.

nickhuber avatar May 15 '18 18:05 nickhuber

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.

ldx avatar May 24 '18 00:05 ldx

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.

ldx avatar May 24 '18 01:05 ldx

Parsing also fails when the comment contains an exclamation mark. How about using shlex instead of a regex ?

multun avatar Oct 22 '18 15:10 multun

@multun do you mean when parsing the output from save()?

ldx avatar Oct 23 '18 17:10 ldx

@ldx yup https://github.com/ldx/python-iptables/blob/e42e691732ec93d1bc05a954012246e78827f8d3/iptc/ip4tc.py#L392

multun avatar Oct 26 '18 07:10 multun