diff --git a/xml/System/Uri.xml b/xml/System/Uri.xml index 5ca2166590c..b2e3491d474 100644 --- a/xml/System/Uri.xml +++ b/xml/System/Uri.xml @@ -188,6 +188,36 @@ Uri uri1 = new Uri("C:/test/path/file.txt") // Implicit file path. Uri uri2 = new Uri("file:///C:/test/path/file.txt") // Explicit file path. ``` These implicit file paths are not compliant with the URI specification and so should be avoided when possible. When using .NET Core on Unix-based systems, implicit file paths can be especially problematic, because an absolute implicit file path is *indistinguishable* from a relative path. When such ambiguity is present, default to interpreting the path as an absolute URI. + +## Security Considerations + +Because of security concerns, your application should use caution when accepting instances from untrusted sources and with `dontEscape` set to `true` in the [constructor](xref:System.Uri.%23ctor(System.String,System.Boolean)). You can check a URI string for validity by calling the method. + +When dealing with untrusted user input, confirm assumptions about the newly created `Uri` instance before trusting its properties. +This can be done in the following way: + +```csharp +string userInput = ...; + +Uri baseUri = new Uri("https://myWebsite/files/"); + +if (!Uri.TryCreate(baseUri, userInput, out Uri newUri)) +{ + // Fail: invalid input. +} + +if (!baseUri.IsBaseOf(newUri)) +{ + // Fail: the Uri base has been modified - the created Uri is not rooted in the original directory. +} +``` + +This validation can be used in other cases, like when dealing with UNC paths, by simply changing the `baseUri`: + +```csharp +Uri baseUri = new Uri(@"\\host\share\some\directory\name\"); +``` + ## Performance Considerations If you use a *Web.config *file that contains URIs to initialize your application, additional time is required to process the URIs if their scheme identifiers are nonstandard. In such a case, initialize the affected parts of your application when the URIs are needed, not at start time. @@ -203,9 +233,6 @@ Uri uri2 = new Uri("file:///C:/test/path/file.txt") // Explicit file path. ]]> - - Because of security concerns, your application should use caution when accepting instances from untrusted sources and with set to .You can check a URI string for validity by calling the method. -