My application has a Session Fixation Vulnerability. To fix that vulnerability, I am changing the session id after login.
I am having below web pages in different folders Master and Transaction.
~/Master/Login.aspx : After the credentials validated, I am setting
Response.Cookies["ASPFIXATION"].Value ="xyz";
Session["ASPFIXATION"] = "xyz"
and redirect to ~/Master/Home.aspx
~/Master/Home.aspx : In this page, I am checking the session value with the cookie value on page load event.
string cookie_value = string.Empty;
string session_value = string.Empty;
if (Request.Cookies["ASPFIXATION"] != null)
cookie_value = Request.Cookies["ASPFIXATION"].Value;
if (HttpContext.Current.Session["ASPFIXATION"] != null)
session_value = HttpContext.Current.Session["ASPFIXATION"].ToString();
if (cookie_value != g_SessionFix)
{
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = null;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-1);
}
if (Request.Cookies["ASPFIXATION"] != null)
{
Response.Cookies["ASPFIXATION"].Value = null;
Response.Cookies["ASPFIXATION"].Expires = DateTime.Now.AddDays(-1);
}
Response.Redirect("~/Master/Login.aspx", false);
}
Here the Session has the value and it is validated.
~/Transaction/Report.aspx : If i redirect to this page and have to check the same session and cookie value logic in this page load. But here the value of HttpContext.Current.Session["ASPFIXATION"] is null and value of HttpContext.Current.Session.IsNewSession also true
Try to reassign the value after reading the values, sometimes it clears the values after reading from the session:
if (Request.Cookies["ASPFIXATION"] != null)
{
cookie_value = Request.Cookies["ASPFIXATION"].Value;
Request.Cookies["ASPFIXATION"].Value = cookie_value;
}
if (HttpContext.Current.Session["ASPFIXATION"] != null)
{
session_value = HttpContext.Current.Session["ASPFIXATION"].ToString();
HttpContext.Current.Session["ASPFIXATION"] = session_value;
}
If it still doesn't work for you then you have one other option to do it,
if your session data is not confidential then try to pass it in query string and on page redirection retrieve this value.
Response.Redirect("~/Master/Login.aspx?data=" + session_value +");
Related
When I attempt to access a cookie, I get the following exception:
Object reference not set to an instance of an object.
This is the line in question:
if (Request.Cookies["selectBoxValue"].Value != null)
Controller
[Authorize]
public ActionResult Index()
{
if (Request.Cookies["selectBoxValue"].Value != null)
{
HttpCookie groupId = new HttpCookie("selectBoxValue");
groupId = Request.Cookies["selectBoxValue"];
// Collect all comments connected to current group
int t = Convert.ToInt32(groupId.Value);
pv.ListofComments = db.Comments.Where(dp => dp.GroupID == t).ToList();
// Show only groups connected to current user
var CurrentUser = User.Identity.GetUserId();
var groupUser = db.GroupUsers.Where(u => u.ApplicationUserId == CurrentUser).Select(gr => gr.GroupId).ToList();
pv.GroupList = db.Groups.Where(g => groupUser.Contains(g.Id));
return View(pv);
}
Your error is because something in that chain is not there:
if (Request.Cookies["selectBoxValue"].Value != null)
Things to check:
var myCookie = Request.Cookies["selectBoxValue"];
myCookie!= null;
myCookie.Length > 0;
Most likely you don't have a cookie coming in on the Request that's called selectBoxValue. Since selectBoxValue (from its name) sounds like it's something on your form itself, I'm curious as to why you'd be checking a cookie for it? If it's a persisted value from a previous page (not the one that sent the Request to the server), then call it something more intuitive than selectBoxValue.
To learn more about how to write a cookie and to read a cookie; see this Stack Overflow answer.
If you expect the user to have a cookie called selectBoxValue and they don't, then you have a specific issue: wherever you're setting that cookie, it's not getting sent to the user in the Response.
If you are OK with that (that is, some codepaths expect that cookie and others do not) then you can set the object you're playing with to a sane value if that cookie doesn't exist:
int defaultGroupId = 1;
var obj = Request.Cookies["selectBoxValue"] ?? defaultGroupId;
Your code also has some issues:
if (Request.Cookies["selectBoxValue"].Value != null)
{
HttpCookie groupId = new HttpCookie("selectBoxValue"); //why create one?
groupId = Request.Cookies["selectBoxValue"];
// Collect all comments connected to current group
int t = Convert.ToInt32(groupId.Value);
}
Why are you creating a cookie only not to use it?
A Cookie is only meant to be created if you're going to send it somewhere. So here you should write something like:
int defaultGroupId = 1;
int groupId = defaultGroupId;
if (Request.Cookies["selectBoxValue"] != null) {
var parsed = Int.TryParse(Request.Cookies["selectBoxValue"].Value, out groupId);
if (!parsed) {
// the incoming cookie value wasn't an integer or couldn't be parsed to integer. In this case do you want to set it to an appropriate value (say whatever comes out of your query?
}
//At this point you either have a valid `groupId` or you have your `defaultGroupId` so you can use `groupId` normally.
}
You are checking if the value of your cookie is null, which it may or may not be. If the cookie hasn't been set yet, then the cookie itself is null, which means you get an exception if you tryto access the value of the cookie.
Here's a code snippet of what you need to check.
//retrieve the cookie
var cookieSelectBoxValue = Request.Cookies["selectBoxValue"];
//Check if the cookie itself is null
if(cookieSelectBoxValue != null)
{
//Retrieve the value of the cookie
var cookieValue = cookieSelectBoxValue.Value;
//Check if the value of the cookie is null
if(cookieValue!= null)
{
//The rest of your logic goes here
}
}
To set the cookie, you can use the Response.SetCookie() method in your Controller Action. Here's a quick example:
public ActionResult Index()
{
if (Request.Cookies["selectBoxValue"] != null)
{
var cookie = new HttpCookie("selectBoxValue")
{
Expires = DateTime.Now.AddYears(1),
Value = "CookieValueGoesHere"
};
Response.Cookies.Add(cookie);
}
return View("Index");
}
I want to prevent My Web Application from the CSRF attacks.
I'm applying this solution for the same in Master Page, all the Web Pages are inherited from this Master Page.
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value;
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
//Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true,
//Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
};
//If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
responseCookie.Secure = true;
//Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
//If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of
Anti-XSRF token failed.");
}
}
}
}
With this Solution I'm not able to achieve what I want.
If User A logs in, does some activity and capture the Request from Fiddler and it logs out and now User B logs in and I fire the captured Request and it successfully does it task. So My application is not prevented.
I can see Request.Cookies[AntiXsrfTokenKey] value is same for a particular session and for a new session Request.Cookies[AntiXsrfTokenKey] value is different.
What should I do insted of this line
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
On LogOut Button Click I clear each and everything.
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
HttpCookie cookies = Context.Request.Cookies[FormsAuthentication.FormsCookieName];//Or Response
cookies.Expires = DateTime.Now.AddDays(-1);
Context.Response.Cookies.Add(cookies);
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
}
if (Request.Cookies["AuthToken"] != null)
{
Response.Cookies["AuthToken"].Value = string.Empty;
Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
}
if (Request.Cookies[AntiXsrfTokenKey] != null)
{
Response.Cookies[AntiXsrfTokenKey].Value = string.Empty;
Response.Cookies[AntiXsrfTokenKey].Expires = DateTime.Now.AddMonths(-20);
}
//Response.Redirect("Logon.aspx");
FormsAuthentication.RedirectToLoginPage();
Just add #Html.AntiForgeryToken() in the form that send the data. Then decorate the action method or controller with the [ValidateAntiForgeryToken]: msdn
Use "AntiForgeryToken" to prevent CSRF attack. For better understanding refer the below links:
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks
http://www.codeproject.com/Articles/686881/Hack-Proof-Your-ASP-NET-Applica
I am setting cookie value in a usercontrol[A] and reading the value in the another usercontrol [B].
But the value is only available on page refresh in the server side. I can see the updated value in firebug cookie tab.
If i refersh the page the correct value is diplaying inthe page.
How to fix this issue?Below is the code i am using to read the cookie in usercontrol[B].
Its always the old value not the new value that i set in the usercontrol[A]
HttpCookie cookieTool = Request.Cookies["previousTool"];
string strSessionReturnToolTitle = "";
string strSessionReturnToolURL = "";
if (cookieTool != null)
{
// Response.Write("<BR>Cookie value " + cookieTool["returnToolurl"].ToString());
if (Request.UrlReferrer == null)
{
cookieTool.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookieTool);
}
else
{
strSessionReturnToolTitle = cookieTool["returnTooltitle"];
strSessionReturnToolURL = Server.UrlDecode(cookieTool["returnToolurl"]);
}
}
Request.Cookies is incoming. Response.Cookies is outgoing.
Request.Cookies only knows about the current request. I don't think it updates until the following request when you add via Response.Cookies.
You could try getting the cookie via Response.Cookies["previousTool"] in case Request.Cookies["previousTool"] is null.
If that doesn't work you'll need another way, such as storing the value in the Session or HttpContext.Current.Items.
Good day..! I have some issue getting the value of my cookie when called in a class..
here's my code in my default.aspx.. I can retrieve the value on the when inside the aspx page
HttpCookie myCookie = new HttpCookie("SAMPLE");
myCookie["value"] = HttpUtility.UrlEncode(value);
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
if (Request.Cookies["SAMPLE"] != null)
{
string userSettings;
if (Request.Cookies["SAMPLE"]["value"] != null)
{ userSettings = Request.Cookies["SAMPLE"]["value"]; }
}
But when i called the cookie inside a class using this code HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["SAMPLE"]["value"]) it doesn't have any value.. Any idea..? Hope to hear from you soon..
Regards,
Link
You can replace with Response
....
Response.Cookies.Add(myCookie);
if (Response.Cookies["SAMPLE"] != null)
{
...
}
I have built a shopping cart that uses Session State to keep the shopping cart data while the user is browsing the store.
I have an issue where if I leave the browser window open for a long time on step1 of the shopping cart, then press "go to step 2", my actions throw an error because the step2 action assumes the session hasn't expired and the ShopCart object is in the correct state.
I would like this scenario to be nicer for my users, but I think i need to somehow detect if the session has expired so that on next request I can throw them to Step1.
I found the following code that claims to to solve the problem, but it doesn't work for me.
The IsNewSession condition is true but the condition
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) {
// handle expired session
}
always returns false and it never handles the invalid session. I'm confused.
Is this possible in ASP.NET (and MVC)?
Way 1
Put this code in the Init / Load event of Page 2...
if (Context.Session != null)
{
if (Context.Session.IsNewSession)
{
string sCookieHeader = Request.Headers["Cookie"];
if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Response.Redirect("Error Page");
}
}
}
Way 2
Alternative you can check whether the Session object exists before proceeding to work with it in Page 2, like this:
if (Session["Key"] != null)
{
Object O1 = (Object) Session["Key"];
}
else
{
Response.Redirect("ErrorPage.aspx");
}
The King 's answer does not work for me. I have added FormsAuthentication.SignOut() in OnActionExcuting(). The Response.Redirect will not work!
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
This is my complete method
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
if (ctx.Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
RedirectResult rr = new RedirectResult(loginUrl);
filterContext.Result = rr;
//ctx.Response.Redirect("~/Home/Logon");
}
}
}
base.OnActionExecuting(filterContext);
}
}
You need to create the Session_OnEnd method In Global.asax.cs file in your project.
this is my code and I am able to Detecting Session expiry on ASP.NET MVC
protected void Session_OnEnd(object sender, EventArgs e)
{
int userid = 0;
userid = Convert.ToInt32(Session["UserID"]);
if (userid != 0)
{
var userActivity = DependencyResolver.Current.GetService<IUserRepo>();
var responce = userActivity.LogOutUsers(userid);
if (responce == true)
{
Session.Clear();
Session.Abandon();
}
}
}
more