for cookie poisoning demo, write and read cookies in vb.net - asp.net

I would like to test cookie poisoning so I want to edit one of my projects. There, I would like to write cookies which will contain subtotal of products and the checkout page will use it again to show the subtotal. I am not sure whether my thinking is correct or not and also my cookies are not working.
First, I put these codes under addcart button method:
Dim aCookie As New HttpCookie("SubTotal")
aCookie.Value = objShopCart.ComputeSubTotal().ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
HttpContext.Current.Response.Cookies.Add(aCookie)
And in the checkout page;
If (Request.Cookies("aCookie") IsNot Nothing) Then
Dim subTotal As String
If (Request.Cookies("aCookie")("SubTotal") IsNot Nothing) Then
subTotal = Request.Cookies("aCookie")("SubTotal")
lblSubTotal.Text = subTotal
End If
End If
According to the above codes, I cannot read the cookies. The Request.Cookies("aCookie") is always nothing I don't know why. And for the cookie poisoning demo is I intend to intercept the cookie of when I put things into the shopcart and edit it so when I got to checkout page, its shown with wrong info of subtotal etc. Appreciate to any help.

You need to retrieve the cookie value by the same name you saved it. For example,
If (Request.Cookies("SubTotal") IsNot Nothing) Then
Dim subTotal As String
subTotal = Request.Cookies("SubTotal").Value
End If
Just FYI, you do not want to save the subtotal in cookie, because it can be manipulated easily at client side. Save it in session state or recalculate it in check out page again.

Related

Paypal Sandbox Return Url not working vb.net

I am in the beginning stages of working with paypal checkout in my website and I am trying to use a sandbox account to test some things out. I am able to go through and purchase the item with another sandbox account but after I purchase the item, it stays on the paypal checkout page and tells me that I have completed my payment and I will receive an email notification. I need it to return to some other website url so that I can try to get details of the transaction in my code behind. My code posted below is very basic and I do not have anything in the code itself about the return URL, I have filled it in under my sandbox account settings.
The second part of the problem is that I have not published my website yet, I am using the visual basic debugger to view and test my site in a browser and when I attempt to put my "local host" url into the return url it gives an error: "We were unable to validate the URL you have entered. Please check your entry and try again." an example of the url I am trying to put in is
http://localhost:11111/WebSite1/Parts_Catalog.aspx
As a test url just to attempt to start getting data back from the transaction I just put in google.com thinking that it would at least return to google with either an error or the returned query strings but it doesn't attempt to load any pages at all after the transaction.
How can I get the paypal sandbox return url to actually return to a URL? How can I enter my local host URL into the website preferences return url and actually get it to recognize my url as listed above?
Here is the markup code
<asp:ImageButton ID="AddToCartBtn" runat="server"
RowIndex='<%# Container.DisplayIndex %>'
ImageUrl="~/Pictures/ShoppingCart.png"
OnClick="AddToCartBtn_Click" />
Here is the code I have so far for my addToCart button, I don't know if I need to add anything here or not for the return url
Protected Sub AddToCartBtn_Click(sender As Object, e As ImageClickEventArgs)
Dim Item As String = "Test"
Dim price As String = cost
Dim business As String = "test#aol.com"
Dim itemNumber As String = str2
Dim itemAmount As String = price
Dim currencyCode As String = "USD"
Dim addItem As Integer = 1
Dim ppHref As StringBuilder = New StringBuilder()
ppHref.Append("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart")
ppHref.Append("&business=" + business)
ppHref.Append("&item_name=" + itemName)
ppHref.Append("&item_number=" + itemNumber)
ppHref.Append("&amount=" + itemAmount)
ppHref.Append("&currency_code=" + currencyCode)
ppHref.Append("&add=" + addItem.ToString("#0"))
Response.Redirect(ppHref.ToString(), True)
Dim ReturnQaunity As String = itemAmount
GetRouteUrl("/v1/payments/orders/<Order-Id>")
End Sub
I don't currently have anything in my page load event that deals with paypal.
Andre is right, the return URL must be accessible to PayPal.
What you can do is use a generic URL (I guess google.com would work but it might be better to use one of your own) then edit the URL in the browser window.
So return to something like http://www.test.com/return.html?paypalparms...
Then when it displays in your browser change the URL to
http://localhost/return.html?paypalparms...
Then press enter.
I have used a similar technique with PayPal PDT and IPN testing and it works fine.
I would have replied to your comment but I haven't yet reached the dizzy heights of 50 reputation which allows me to comment everywhere.

asp.net vb2010 How to log Windows Authentication events - i.e. save user name and login time

Just now getting into the asp.net environment with VB 2010. I have designed an intranet page that we will be using to auction off old equipment to employees. I've had some very good luck getting the whole thing working, but I have hit a snag on one minor issue: I would like to keep a database table of user logins and times.
Several methods have presented themselves, but so far none of them have been adequate. The main problem seems to be that regardless of the event I use to record the login, they fire multiple times resulting in as many as 4 or 5 entries in the login database for the same login event, not to mention additional times when something on the page changes for whatever reason.
The system uses Windows Authentication, so the user must login with his/her company credentials.
I can't remember what all I have tried, but the first thing I tried was the Page_Load event because it seemed obvious. I've learned that because the page updates the display every ten seconds, Page_Load event fires numerous times throughout the session.
Fighting my way through other ideas, all of which failed, I came to the WindowsAuthentication_OnAuthenticate event in the Global_asax class, shown below:
Imports System.Web.SessionState
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.UI.WebControls
--------------------------------------------
Public Sub WindowsAuthentication_OnAuthenticate(ByVal sender As Object, ByVal args As WindowsAuthenticationEventArgs)
Dim strLoginName = args.Identity.Name
Dim sqlCommandString As String = "INSERT into tblLogin (UserLogin,DateTime) VALUES ('" & _
strLoginName & "','" & _
Format(Now, "MMM dd, yyyy hh:mm:ss") & "');"
Dim sqlConn As New SqlConnection(strConnectionString)
Dim sqlCommand As SqlCommand = New SqlCommand(sqlCommandString, sqlConn)
sqlCommand.Connection.Open()
sqlCommand.ExecuteNonQuery()
sqlCommand.Connection.Close()
End Sub
which also seems to fire multiple times. I then tried to work a way where setting a Boolean value to TRUE upon authentication so that the data would be written to the database only once:
Public Sub WindowsAuthentication_OnAuthenticate(ByVal sender As Object, ByVal args As WindowsAuthenticationEventArgs)
If Not boolUserIsLoggedIn Then
boolUserIsLoggedIn = True
Dim strLoginName = args.Identity.Name
Dim sqlCommandString As String = "INSERT into tblLogin (UserLogin,DateTime) VALUES ('" & _
strLoginName & "','" & _
Format(Now, "MMM dd, yyyy hh:mm:ss") & "');"
Dim sqlConn As New SqlConnection(strConnectionString)
Dim sqlCommand As SqlCommand = New SqlCommand(sqlCommandString, sqlConn)
sqlCommand.Connection.Open()
sqlCommand.ExecuteNonQuery()
sqlCommand.Connection.Close()
End If
End Sub
and subsequent authentication iterations would skip the database write code; but then I needed to find a way to clear the Boolean value when the user logged off or closed the session. I couldn't figure out how to trap a "Logged Off" event, and the Session_End and Application_End events didn't work as I had hoped.
I feel like this is getting too convoluted to make sense. To put it simply, I just need a way to record a user's login name and date only once per session. Can anyone help?
[Edit: Although this is not really an essential element of the page, it has become a crusade for me to get it to work if not for any other reason than to understand the process.]
Researching more about JDB's suggestion using the session ID property, I discovered another property that seems to be doing exactly what I need: The IsNewSession property.
With that in mind, I have this code in my default.aspx's Page_Load event:
If Context.Session.IsNewSession Then
Login()
End If
Which calls the Login sub that writes the login information to the database:
Protected Sub Login()
Dim strConnectionString As String = "Data Source = toponet\sqlexpress; initial catalog = TopoAuction; Integrated security = True"
Dim strLoginName = System.Web.HttpContext.Current.User.Identity.Name
Dim sqlCommandString As String = "INSERT into tblLogin (UserLogin,DateTime) VALUES ('" & _
strLoginName & "','" & _
Format(Now, "MMM dd, yyyy hh:mm:ss") & "');"
Dim sqlConn As New SqlConnection(strConnectionString)
Dim sqlCommand As SqlCommand = New SqlCommand(sqlCommandString, sqlConn)
sqlCommand.Connection.Open()
sqlCommand.ExecuteNonQuery()
sqlCommand.Connection.Close()
End Sub
So far, testing has shown that it fires only once per session. Even if the browser moves to another site and comes back, it will not count that as a new session. This seems to be the perfect solution.
I'm open to hear any comments or concerns about this, anybody?
I think, perhaps, you are getting hung up on the request/response cycle of a web page. If you have only ever used WebForms and come from a desktop development background, the statelessness of the HTTP protocol can be very confusing.
Essentially, the client (the browser) requests information from the server (where your .NET code is running). Each request is completely independent from every other request - the server maintains no memory of prior requests.
Now, WebForms was an attempt to bridge the gap by shoe-horning on a sort of pseduo-statefullness on top of HTTP. This is where ViewState and other similar concepts come in. Basically, WebForms includes additional information about the state of the web application in each Response, which is then included again in following Requests, maintaining the application's state and giving the appearance of statefulness. There are other tricks too, like server variables, which can be used to maintain some "memory" of past transactions.
However, this statefulness is easily broken. For example, if you include a basic anchor tag (not an ASP.NET server control), and you redirect to another page (or even the same page) without including the view state, then you will lose some of your application state. Even if you are using server controls and maintaining your view state, you must pay careful attention to the WebForms Page lifecycle. If you are handling the wrong event (such as Page_Load) or attempting to access a property at the wrong time (before the web page has had a chance to reload it's state), you may not get the results you are expecting.
In this scenario, I recommend you check the user's Session ID. It changes very infrequently. If you have a user ID coming in with a session ID you've not seen before (or that's not been associated with that user in some amount of time - say 30 minutes), then you probably have a unique logon event. If you have seen that user ID/Session ID combo, then that user has probably already "logged in" and you don't need to record it again.
Alternatively, just store the user's login state in a session variable. You can check that variable on each Page_Load and branch (using an If statement) based on your needs.

Session becoming Null after Response.redirect

I set two sessions which I fill from a database:
Session("username") = reader.Item("user_name").ToString
Session("department") = reader.Item("user_department").ToString
to add restrictions depending on department the user is signing in from (IT department, customer service, etc..)
Sessions are readable from the form LogIn.aspx to the form Default.aspx
But in other pages:
IF Session("Department")<>"IT"
Response.Redirect("LogIn.aspx")
End If
This redirects to LogIn.aspx and Session("Department") equals Nothing
Any idea on why it is doing so? I tried searching for something missing in my code and I couldn't find anything.
The key is case sensitive, so change it to "department". Currently it's set to "Department"
Instead of this
IF Session("Department")<>"IT"
use this
IF Session("department")<>"IT"
spell mistake( Keys are case sensitive).
And use if condition with safety like this
If Session("department") IsNot Nothing AndAlso Not Session("department").ToString().Equals("IT") Then

ASP.NET ScriptManager History url hash lost after redirect

I have seen several posts online complaining that Firefox maintains the history url hash after redirecting.. That is the behavior I am hoping for - and it happens in Firefox (11.0), Chrome (18.0), and Opera (11.61), but not IE (9) or Safari (5.1.2).
On my page, I have ASP.NET 4.0 history points set up and working (has been working for a couple years). I also pass a few querystring params to the page. What I am trying to do now is check the value of a new querystring param, and if it does not match what I am expecting, redirect to the same page with an updated value. I am using this mechanism to track the session of individual tabs of a browser so that when they have the same page open in multiple tabs, the session values dont step on each other from tab to tab.
Anyway, I have everything working correctly including the back/forward using ASP.NET History points - and when I visit a bookmark and the querystring param does not match, I redirect and change the querystring param to track the session, and the history state that is in the url of the bookmark is then used to reload the page to the state I want. But that only works in Firefox, Chrome, and Opera. Not IE which is the big one for me (based solely on our user base), and not Safari.
I have identified that in addition to (or perhaps because of) the fact that the url history state is not present, ScriptManager.Navigate is not called after the redirect in IE or Safari.
Is there a setting/option that I can set on the ScriptManager or during the redirect to maintain the History state in the url? If the history state was in the url, I could call ScriptManager.Navigate directly if I needed to, but the values are not present in the url.
If it helps at all, here's a listing of where I do the check and redirect. The ReportRunID is then appended to the session variable keys that need to be unique to each tab. I keep a listing of previous ReportRunIDs to keep track and to clean them out (after a certain time period, or when more than [MAX] ids are encountered) so that I dont overload server memory with these session entries.
Private Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
If IsPostBack = False Then
Dim rrid As String = Request.QueryString("RRID")
If ReportRunIDExists(rrid) = False Then
ReportRunID = Now.ToString("_HHmmssfff")
Dim url As String = Request.Url.PathAndQuery
If String.IsNullOrEmpty(rrid) Then
Response.Redirect(String.Format("{0}&RRID={1}", url, _reportRunID))
Else
Dim idx As Integer = url.IndexOf("&RRID=")
Response.Redirect(String.Format("{0}&RRID={1}{2}", url.Substring(0, idx), _reportRunID, url.Substring(idx + 6 + rrid.Length)))
End If
End If
End If
End Sub
Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
'save current RRID/Page/Time to session
UpdateSessionReportRunID(_reportRunID)
End Sub
...
If my bookmarked url looks like:
mysite.com/mypage.aspx?Rpt=123&RRID=_095224678#&&state1=abc&state2=def...
In FF/Chrome/Opera after the redirect, my url looks like:
mysite.com/mypage.aspx?Rpt=123&RRID=_102176253#&&state1=abc&state2=def...
But in IE/Safari after redirect, my url looks like:
mysite.com/mypage.aspx?Rpt=123&RRID=_102176253
Any ideas?
After much more searching, I have come to the realization that History State hash is not sent to the server. It is stored in the querystring so that it is included in bookmarks, but it is accessed by the client-side scriptmanager which causes a postback to load the state values. Since the Server never sees the hash value in the querystring, I have no way of finding those values when a user follows a bookmark to that page.
This problem was introduced as I was trying to start tracking the session state of different browser tabs individually. In my code above, if the RRID parameter is empty or invalid, I have to redirect to self with a new RRID value. When I do that redirect the History State hash was being lost for IE and Safari (but not for the other browsers).
My workaround:
The problem is that I needed to include the hash value in my redirect, but that is not available from the server, so I decided to inject some javascript to the page to perform the redirect from the client where the hash is available.
I already had a Client Redirect extension helper method that I have used in different scenarios, and I modified it to include the current hash value:
<System.Runtime.CompilerServices.Extension()>
Public Sub ClientRedirect(ByVal Response As HttpResponse, ByVal url As String, Optional ByVal target As Target = Nothing, Optional ByVal windowFeatures As String = Nothing, Optional includeCurrentHash As Boolean = False)
If IsNothing(target) Then
If windowFeatures = String.Empty Then
target = ResponseHelper.Target._self
Else
target = ResponseHelper.Target._blank
End If
End If
Dim page As Page = CType(HttpContext.Current.Handler, Page)
url = page.ResolveClientUrl(url)
Dim script As String
script = "window.open(""{0}"", ""{1}"", ""{2}"");"
script = String.Format(script, url & If(includeCurrentHash, "#"" + window.location.hash + """, String.Empty), target.ToString, windowFeatures)
If target = ResponseHelper.Target._self Then
'execute after page has loaded
page.ClientScript.RegisterStartupScript(GetType(Page), "Redirect_" & Now.ToString("HHmmssfff"), script, True)
Else
'execute as page is loading
page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Redirect_" & Now.ToString("HHmmssfff"), script, True)
End If
End Sub
Then in my Page_PreInit where I do the redirects, I changed that to do the ClientRedirect including the current hash, and that has gotten the desired result:
Redirecting the browser while maintaining the History State hash on all browsers.
'redirect from the client so that we keep the History State URL hash
Response.ClientRedirect(String.Format("{0}&RRID={1}", Request.Url.PathAndQuery, _reportRunID), , , True)

Why is the Request.Form.AllKeys collection empty after a POST and Redirect?

I have an aspx page where I want to post values to a new page and then redirect to that new page. I don't get any errors and the redirection occurs but the AllKeys collection is always empty.
Here's an example of my code:
Try
With strPost
.Append("User=" & strUserName)
.Append("&Session=" + strValue)
End With
Dim objRequest As Net.HttpWebRequest = _
Net.WebRequest.Create("http://localhost:57918/testproject/test.aspx")
With objRequest
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = strPost.ToString().Length
End With
Dim objStream As IO.StreamWriter = _
New IO.StreamWriter(objRequest.GetRequestStream())
objStream.Write(strPost.ToString)
objStream.Close()
Catch ex As Exception
Debug.Print(ex.Message)
Exit Sub
End Try
Response.Redirect("http://localhost:57918/testproject/test.aspx")
I have seen a few articles similar to this problem but none of them have helped. What am I doing wrong?
Why don't you just have your main page post directly to this other page?
If the process is:
Page A rendered to client
Client posts back to Page A
Page A code behind generates a request to Page B
Page A code behind redirects user to Page B
Page B rendered to client
Then between steps 4 and 5 you will lose all the post params. That's just how it works.
However, you could do the following:
Page A rendered to client, with the form post action set to Page B
Clients enters information and clicks submit
Post values go to page B for handling.
Another path would be to have Page A perform a redirect and pass the values on the query string. For example, Response.Redirect("/PageB.aspx?param1=value&param2=value")
If I'm correct in understanding this, you are expecting the POST values to be available in /testproject/test.aspx after the redirect.
Unfortunately it won't work like that. When you perform the WebRequest it's a one-shot post. A new request is created your page executes and then the request ends and all data associated with that page will be discarded.
When you redirect at the end of the example given that is a completely new GET request to a new instance of test.aspx. Your previous request's POST data will never be available.
You can either:
Redirect to the page and pass the User and Session values in the querystring
Store User and Session in the Session collection then redirect
If strUserName and strValue originate from another postback your could use Server.Transfer to transfer control to test.aspx and keep the current request's Form and QueryString collections intact.
The code above will result in two requests being made to http://localhost:57918/testproject/test.aspx
The webserver itself POSTs the values to the url. When the page runs this time the AllKeys collection will contain the values you posted.
The client's web-browser will perform a GET request against the page. Nothing will be posted. This time the keys will be blank.
In order to pass the parameters to the other page you could encode the values in the redirect URL:
Dim url as String = "http://localhost:57918/testproject/test.aspx"
url = url + "?User=" + strUserName
url = url + "&Session=" + strValue
Response.Redirect(url)
The values would then be available using the request object (e.g. Request["User"]).
update
If you don't want to show the data to the user; then you've really only got two other options:
Move the processing that was being carried out by test.aspx to the page that was generating the original query.
Save the User and Session values the the session state.

Resources