What is the use of =? in links? - asp.net

I saw my friend doing some Web Development, and one of his code caught my attention is the Response.Redirect.
What is the use of Home?=, isn't it the LogIn.aspx is the name of the page how come it's still redirecting if it has Home?=. Can someone answer this question of mine please, and explain it very well.
String url = "LogIn.aspx?Home?=" + Username;
Response.Redirect(url);

Update
Working from all your comments, the answer is: The query string parameter name (key) is actually "Home?", not just "Home". Details (including why the code generating that is technically incorrect) below.
how come it's still redirecting if it has Home?=?
Because there's no reason it shouldn't redirect. Granted the URL is invalid (? is a reserved character, it cannot appear unencoded in the query string, so the second ? in the URL is incorrect), but browsers are pretty content to deal with invalid URLs.
Separately, unless Username has already been URL-encoded, the URL could have other errors depending on the content of Username. (All query string parameters must be URL-encoded, in .Net you do that with HttpUtility.UrlEncode.)
Re your comment:
what i mean is i don't know why he use Home?= and what is the use of it
It has no use, it's an error. He probably just meant (no, apparently not, see below after your next comment)
String url = "LogIn.aspx?Home=" + Username;
...which would more correctly be:
String url = "LogIn.aspx?Home=" + HttpUtility.UrlEncode(Username);
(Technically, you have to URL-encode both the keys and values [both "Home" and Username], but the URL-encoded form of "Home" is "Home", so we can get away without making the call for the key. Not true if the key needs to have any of the URL reserved characters in it.)
Re your further comment consisting entirely of this code:
string retrieveValue;
protected void Page_Load(object sender, EventArgs e) {
this.lblUsername.Text = Request.QueryString["Home?";
retrieveValue = this.lblUsername.Text;
}
Assuming the syntax error in the above is fixed (missing ] on line 3), it would appear that he's actually using "Home?" as a key (parameter name). That means the redirect should be:
String url = "LogIn.aspx?" + HttpUtility.UrlEncode("Home?") + "=" + HttpUtility.UrlEncode(Username);
...because the key has a reserved character in it (?). Because that will be decoded for you on receipt, that should make the code above work.
Note that most browsers will probably let you get away with the string as he specified it. It's incorrect, but in a way browsers probably allow.

Regardless of the errors that T.J covered, what he meant to do was load the page LogIn.aspx with the variable "Home" being set to the visitors username. This allows the page to "GET" the variable and use it. Its basically a way of sending data from one page to another.

Related

returnUrl drops second querystring parameter

I am using MVC 5. The problem is that after SSO redirects back to the app after authentication the login method returnUrl drops the applicaitonId querystring parameter. Please help!
Here is the flow.
The app redirects unauthorized users to a login method, preserving the original request in the returnUrl.
The original request is
http://localhost:25451/shared/download?documentGroup=133&applicationId=3153
the returnUrl is
/shared/download?documentGroup=133&applicationId=3153
The app redirects to a SSO CAS server, sending along the HttpUtility.Encode returnUrl as a parameter along with login Url both part of the service parameters.
https://{redacted}/cas/login?service=http://localhost:25451/account/login%3freturnUrl%3d%2fshared%2fdownload%3fdocumentGroup%3d133%26applicationId%3d3153
After authentication, the CAS server appends the authorized ticket and redirects back to the service URL. This is what fiddler shows.
http://localhost:25451/account/login?returnUrl=/shared/download?documentGroup=133&applicationId=3153&ticket={redacted}
Here is the issue. The returnuRL in the login method is simply
/shared/download?documentGroup=133.
The returnUrl no longer has the applicationId.
Interestingly enough, the line works just fine.
var ticket = Request.QueryString.Get("ticket");
I have tried to encode the whole serviceUrl and tried to encode just the returnUrl(see below) but I get the same missing ApplicationId issue.
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
var ticket = Request.QueryString.Get("ticket");
if (!string.IsNullOrEmpty(ticket))
{
//verify the ticket...
return RedirectToLocal(returnUrl);
}
var serviceUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port) + "/account/login" + "?returnUrl=" + HttpUtility.UrlEncode(returnUrl);
var authenCasUrl = string.Format("{0}login?service={1}", "https://{redacted}/", serviceUrl);
return Redirect(authenCasUrl);
}
Since this site will be actually called by your URL, I don't think they just throw away parts of it.
Lets try something here since I have encountered a similar problem with parameter in url strings in combination with asp.NET.
First, lets get the unedited URL from your Request:
string UneditedUrl = Request.RawUrl;
Since we are not needing anything before the ? mark, we shorten it a little bit:
string QueryString = (UneditedUrl.IndexOf('?') < UneditedUrl.Length - 1) ? UneditedUrl.Substring(UneditedUrl.IndexOf('?') + 1) : String.Empty;
This line also includes the possibility on neither having a ? mark or parameters and will return an empty string if so. Just for good measure, we don't want any exceptions here. Here you can check QueryString if it has both or more of your parameters you entered.
If there are not complete here, its not your code at fault. Something will already work on your URL before you do, probably your host then. Maybe check the settings of your IIS.
If your parameters are correctly in the edited QueryString, you can continue getting them by following this:
I learned that there is a way to let your framework do the job of parsing parameters into name/value collections. So lets give it a go:
NameValueCollection ParaCollection = HttpUtility.ParseQueryString(QueryString);
You can now check you params and their values by either using an index like ParaCollection[0] or ParaCollection["documentGroup"].
EDIT:
I've found the question which brought me to the conclusion of using Request.RawUrl. Since this may not be the answer, it will maybe help a little bit more to understand that Request.RawUrl is the actual URL the user called and not the one the server executes: RawURL vs URL
I have no experience with asp or SSO, but you may need to also HttpUtility.UrlEncode the value of the serviceUrl variable?
var authenCasUrl = string.Format("{0}login?service={1}", "https://{redacted}/", HttpUtility.UrlEncode(serviceUrl));
Since the service parameter is decoded by the CAS once, and then the value of returnUrl gets decoded by your server.
var returnUrl = "/shared/download?documentGroup=133&applicationId=3153";
var serviceUrl = "http://localhost:25451/account/login?returnUrl=" + HttpUtility.UrlEncode(returnUrl);
var casUrl = "https://{redacted}/cas/login?service=" + HttpUtility.UrlEncode(serviceUrl);
Which gives:
serviceUrl = http://localhost:25451/account/login?returnUrl=%2Fshared%2Fdownload%3FdocumentGroup%3D133%26applicationId%3D3153
casUrl = https://{redacted}/cas/login?service=http%3A%2F%2Flocalhost%3A25451%2Faccount%2Flogin%3FreturnUrl%3D%252Fshared%252Fdownload%253FdocumentGroup%253D133%2526applicationId%253D3153
Explanation attempt:
You make a HTTP request to the CAS server. It's implementation splits the query parameters and decodes each value (and possibly key). One of which is the service parameter and is now (after decoding) a valid URL.
The CAS server makes a HTTP request with the URL from the service parameter (to your server) with the ticket appended.
You split the query parameters and decode each value (and possibly key).
If you only encoded the returnUrl once, your serviceUrl will look like what you showed in your third point:
http://localhost:25451/account/login?returnUrl=/shared/download?documentGroup=133&applicationId=3153&ticket={redacted}
How does the algorithm splitting the query string differentiate between a ? or & in the serviceUrl and the ones in the returnUrl?
How should it know that ticket does not belong to the returnUrl?
As you can see in my code above, you are not encoding the returnUrl twice.
You are putting one URL in the parameters of another URL and then you put that URL in the parameters of a third URL.
You need to call UrlEncode for each value (and possibly key) when you put together a query. It does not matter whether that value is a URL, JSON, or arbitrary user input.

How to force unencoded url to show in users browser?

I'm using ASP.NET and am looking to redirect users to a page that includes an easily human readable URL. Every method I've tried takes in the URL and encodes it.
Since none of the parameters are taken in to the page or processed in any way, I don't believe there's any security concerns with turning the %20 into a space. If there is an IIS rule this would work on, I would be fine to turn off encoding on this one page, but I can't turn it off for the whole page as this is a special use case.
I've already tried having Response.Redirect and Server.Transfer, and I cannot use Literals as putting the query into the page somewhere could allow an XSS vulnerability.
Expected:
example.com/test?message=Hello World
Actual:
example.com/test?message=Hello%20World
Edit For More Clarity:
<script>
console.log(window.location.pathname + window.location.search);
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
console.log(window.location.pathname + replaceAll(window.location.search, '%20', ' '));
window.history.pushState(window.location.search, "Title", window.location.pathname + replaceAll(window.location.search, '%20', ' '));
</script>
This will write the current URL to the console, then the URL I'd like to see, but then the pushState does not actually update the URL to one without the encoding - it automatically re-encodes it.
I understand this may be impossible, but if someone could explain why then I will at least be able to stop trying so hard to find a solution.
As per Brando Zhang's comment this appears impossible.

ASP.Net WebForms malformed querystring, ? rather than &

In one of our webforms apps we have external links coming to the site where there are 2 querystring parameters, but the second param is also preceded by a ?.
Normally, your querystring will only have one ?, which is at the beginning just before the first param, and any subsequent params are preceded by &. For example:
www.somesite.com?param1=a&param2=b <---- this is properly formed
www.somesite.com?param1=a?param2=b <---- this is malformed
Yes, I know that param values can contain question marks, and it is best to escape them, but we don't have that issue.
These urls are coming from an external source and we can't do anything about them right now, but we do need to parse the querystrings properly.
With the above malformed url, Request.QueryString["param1"] yields:
a?param2=b
But if the url were properly formed it would yield:
a
Also if properly formed, Request.QueryString["param2"] would yield:
b
How best to handle such a situation, if you are unable to fix the source of the problem? I might add that the url comes to the site urlencoded.
This is the solution that I have come up with. Just fix the querystring and redirect back. In the Page_Load, I call this ProcessQS method, and have added the fix qs code to it:
private bool ProcessQS()
{
var param1 = Request.QueryString["param1"];
if (string.IsNullOrWhiteSpace(param1))
return false;
// Workaround for external links that have ? instead of & for querystring parameter beyond the first.
// In this case, id should be preceded by &, this handles those urls that have a ? preceding id.
if (param1.Contains("?param2="))
{
var qs = Request.ServerVariables["QUERY_STRING"];
qs = HttpUtility.UrlDecode(qs);
Response.Redirect($"~/somepage.aspx?{qs.Replace("?param2=", "&param2=")}", true);
}
return true;
}

Request.Url.Authority doesn't return expected domain

I'm generating an e-mail in my website's controller with a link to my website:
"http://" & Request.Url.Authority & "/some-page"
This works when I tested it on my local machine (returns localhost:12345) and in production (returns www.company.com) but 1 person got this as a result:
http://www.company..com/some-page
As you can see there are 2 .. in the domain name. I can't reproduce this error, how is this possible?
Edit: a bit more information
The type of email I'm sending is a plain text email (no HTML or RTF)
The webserver logs show www.company.com as the domain when the problematic request was made
I only received a partial screenshot of the email. I think the email client is Outlook but I see no reason why Outlook would have misinterpreted the link.
It's certainly possible that this person (or malware) has edited the content of this email.
This is actually a problem with how the email is being encoded, see this answer: https://stackoverflow.com/a/6603002/186288. In summary, you should change the encoding to UTF8 to force base-64 encoding of the email, otherwise some email clients can misinterpret the default Content-Transfer-Encoding: Quoted-Printable; encoding and add in extra "."s in URLs that happen to hit a wrap point.
To do this, add this line before you send the email:
mail.BodyEncoding = System.Text.Encoding.UTF8;
I should have tried this sooner with a simple example:
Module Module1
Sub Main()
Dim SomeAddress As New Uri("http://www.example..com/test")
Console.WriteLine(SomeAddress.Authority)
End Sub
End Module
This will throw an exception in the constructor:
System.UriFormatException - Invalid URI: The hostname could not be
parsed
So the customer couldn't have received such an email from my code without editing it.
Why are you using Request.Url.Authority? I suggest you avoid to use it, and use Request.Url.Host. It's better to use Request.Url.Host or Uri class constructor, when consturcting incorrect URI it will throw exception and you can either log it or show error.
Anyway it's hard to predict why one user have got www.company..com Anyway your code with Request.Url.Authority concatenation can not produce it. So maybe error is in other location.

Get the full QueryString from URL in ASP.NET

I have an URL with the following format:
http://www.mysite.com/login.aspx?ref=~/Module/MyPage.aspx?par=1&par2=hello&par3=7
I use the content of the QueryString it to Redirect the user back to the page he was before logging in. In order to keep also the status of the page I need the parameters in the QueryString. The number of parameters changes depending on the Page calling the Login and its status.
Let's say I want to store everything in the URL after ref in the redirectURL variable. I tried:
redirectURL = Request.QueryString("ref") // "~/Module/MyPage.aspx?par=1"
it gets everything after ref but ignores everything after the &(included). If I use:
redirectURL =Request.Url.Query // "ref=~/Module/MyPage.aspx?par=1&par2=hello&par3=7"
it gets everything, ref included. In order to achieve my goal I need just to remove the first 4 characters from the redirectURL. But I think this solution is a bit "forced" and I am sure there should be some ASP.NET function that accomplish this task.
The &s in your URL are creating additional querystring arguments.
You need to escape the value of the ref parameter before putting it in the querystring.
This will replace the &s with %26.
To do this, call Uri.EscapeDataString().
When you fetch the property from Request.QueryString, it will automatically decode it.
Consider Encoding "~/Module/MyPage.aspx?par=1&par2=hello&par3=7" before passing it to the url.
Eg.:
String MyURL = "http://www.mysite.com/login.aspx?ref=" +
Server.UrlEncode("~/Module/MyPage.aspx?par=1&par2=hello&par3=7");
And then, you can get the redirectURL using:
String redirectURL = Request.QueryString("ref");

Resources