interpolation proposals and safety

Paul Backus snarwin at gmail.com
Thu Aug 29 14:18:48 UTC 2024


On Thursday, 22 August 2024 at 19:34:32 UTC, kdevel wrote:
> Now i forget to `import lib.html` and to call `html` on the IES:
>
> ```
> void main() {
> 	string name = "<script>alert(-1)</script>";
> 	auto element = i"<foo>$(name)</foo>";
>
> 	import std.stdio;
> 	writeln(element);
> }
> ```
>
> ```
> $ dmd htmli.d
> $ ./htmli
> <foo><script>alert(-1)</script></foo>
> ```
>
> `name` may have been a URL parameter or may be part of the POST 
> body. The important part is that it is attacker supplied and 
> controlled.
>
> `writeln` should not print unadorned interpolated string 
> expressions.

The real problem here is that the type system does not 
distinguish between strings that are controlled by the user (and 
thus may contain malicious data) and strings that are controlled 
by the programmer. If you define a separate type for 
user-controlled strings, the mistake is easily caught at compile 
time:

```d
struct UserString
{
	string unwrap;
	@disable string toString();
}

void main() {
	auto name = UserString("<script>alert(-1)</script>");
	auto element = i"<foo>$(name)</foo>";

	import std.stdio;
	writeln(element);
	// Error: static assert:  "UserString cannot be formatted
	// because its `toString` is marked with `@disable`"
}
```


More information about the Digitalmars-d mailing list