0

I have a code which looks like this

public async Task DeleteUser(string userId)
{
   await httpClient.DeleteAsync($"/v1/api/users/{userId}");
}

The problem is that a malicious entry could delete something else than the expected user. For example, if one user has many blog posts, a malicious entry could be userId="/v1/api/users/12394/posts/4", which would delete a blog post rather than removing the user.

Now, it seems that the Uri class has 3 differents escape methods. Uri.EscapeUriString, Uri.EscapeString and Uri.EscapeDataString. However, the documentation around those and their differences either do not exist, or are really impossible to understand, requiring to read 3 RFCs to understand the purpose.

I remember I even saw additional methods (I think in a class called WebUtility) somewhere which also escape things in URL.

So what is the correct way of escaping a path segment?

EDIT:

I forgot HttpUtility.UrlEncode.

Nicolas Dorier
  • 7,383
  • 11
  • 58
  • 71
  • Do you have a chance to expect an integer value instead of a string? – Eldar May 21 '21 at 09:23
  • This is just an example, in this specific case yes, but in other case no. – Nicolas Dorier May 21 '21 at 09:23
  • You may want to consider [regular expressions](https://stackoverflow.com/questions/1342775/what-is-the-best-way-to-clean-a-url-with-a-title-in-it) to do the heavy lifting of cleaning URIs. You may also want to check to see if the URI is [well formed](https://learn.microsoft.com/en-us/dotnet/api/system.uri.iswellformedoriginalstring?view=net-5.0) and [prevent escaping on the URI](https://learn.microsoft.com/en-us/dotnet/api/system.uri?view=net-5.0#security-considerations) – DekuDesu May 21 '21 at 09:25
  • In this specific example, the malicious query is well formed. If it was not well formed, this would not be a problem since HttpClient would catch it. Regular expressions for something that is so ubiquitous seems overkill to me... – Nicolas Dorier May 21 '21 at 09:27
  • 1
    [`Uri.EscapeDataString`](https://stackoverflow.com/q/4396598/4137916). – Jeroen Mostert May 21 '21 at 09:28
  • It seems `EscapeDataString` is closer to what I want indeed. That said, the answer you link seems to be using it for the query string, not for path segment. – Nicolas Dorier May 21 '21 at 09:33
  • 1
    True, but the set of reserved characters is the same. – Jeroen Mostert May 21 '21 at 09:40

1 Answers1

0

Some after some search and answers in comments I found those links explaining things:

https://stackoverflow.com/a/47877559/19803

What's the difference between EscapeUriString and EscapeDataString?

The short answer is EscapeDataString.

Nicolas Dorier
  • 7,383
  • 11
  • 58
  • 71