Rectangle 27 6

A simple idea is to generate a random guid and store it in the user data section of the cookie. Then, when a user logs out, you retrieve the guid from the user data and write it in a server side repository with an annotation that this "session" has ended.

Then, have an http module that checks upon every request whether or not the guid from the userdata section of your cookie doesn't point to a ended session. If yes, terminate the request with a warning that expired cookie is reused.

This comes with a cost of an additional lookup per request.

An additional cost is that this approach does not scale well, because in a heavily-used web app you will soon have a huge table full of GUIDs. Wouldn't it be better to store the GUID of the current session in the user row in the database and set it to NULL when the user logs out? This way, you'll have a maximum of <number of users> GUIDs to store.

@to0om: this could lead to suble issues when the same user has multiple active independent sessions (e.g. in different browsers) and terminates some of them without terminating others.

That's right. If one wants to support multiple concurrent sessions, then a separate session GUID table with a one-to-many relationship could solve the problem. I just don't like the idea of storing expired GUIDs, because if you take this seriously, you have to store them forever in order not to re-enable old sessions later. Storing active GUIDs, maybe combined with a plausible limit of 10 concurrent sessions, limits the maximum number of GUIDs one would have to store.

@to0om: a possible workaround would be to just store guids for limited period of time, I don't think you need an unlimited history.

@WiktorZychla I would err on the side of caution if a user explicitly clicks the "Log out" button - destroy all sessions server side for the identity. If the user wants to maintain two sessions on different user agents, or different machines, they're probably not going to be clicking "Log out". Conversely, you wouldn't want to assume that when the user did click "Log out" that they meant "just this session, not the others" - high risk assumption IMO. Terminate all of them and save the server-side session tracking complexity. - Form Authentication - Cookie replay attack - protection - St... security
Rectangle 27 3

The way is to keep track on your server that the user is logged out and what time, so even if its going to see a page using a valid authenticated cookie, you double check if this user is also logged on your server records or not.

This means that you must have an extra table on your database to keep and check the login logout of your users status and not been 100% count on the authentication cookie.

Is there a way to completely destroy the forms authentication session on logout

In the worst scenario that the cookie is stolen, you actually can't.

Why is that, because the form authentication is actually keep on the cookie all the data (like when is expired, who user is, etc). So you can not delete that, is on the cookie, and the alternative is to synchronize that with your custom data on the server and have an extra level of security.

The user data section of the cookie can be used to store an additional information you could use to correlate forms cookies with server-side persisted information. Thus, you actually CAN detect whether or not a cookie is reused after the session has been ended.

@WiktorZychla But if the hacker get and replace both the session cookie with the logged in cookie ? Then is by pass your check.

There is a single, encrypted forms cookie, with guid in session data. This guid corresponds not to server side session but is just an additional unique guarding token. - Form Authentication - Cookie replay attack - protection - St... security
Rectangle 27 2

It confused the heck out of me, luckily, I was able to remote to my production machine, run the stock MVCOpenId project, step through the debug and see the error. The error was This message has already been processed. This could indicate a replay attack in progress, and it seems to be related to a setting on DotNetOpenAuth (I wish I could some how see that message without having to debug the code!). A setting in the web.config solved it, change the maxAuthenticationTime to 0:10:

<openid maxAuthenticationTime="0:10" ... ...

Thanks all for looking. mvc - DotNetOpenAuth & MvcOpenID - Works locally but not on pr... openid dotnetopenauth
Rectangle 27 2

The token is tied to a session cookie; when the session goes away and the cookie disappears the token will be rendered invalid. The reason replays work in Fiddler is that Fiddler is capturing (and replaying) both the session cookie and the form token.

You could simulate session expiration by removing the request's Cookie header from within Fiddler before replaying. The server should then reject the form's __RequestVerificationToken field.

Jup i see i removed the cookie value/token _RequestVerificationToken_Lw_ but how it is easy to steal that cookie that holds __RequestVerificationToken_Lw token? And when that session cookie expires on server

AntiForgeryToken validation Asp.Net MVC 3 - Stack Overflow csrf antiforgerytoken
Rectangle 27 1

You likely have two places that are trying to respond to the access token request. The one that's failing would be the second one. You should only have one place parsing this request to avoid this false "replay attack" error.

You presumably have an INonceStore implementation in your project. Set a breakpoint in the StoreNonce method then repro the problem. You'll likely see two hits to the StoreNonce method. You'll be able to observe the callstacks of both calls to determine which one you want to keep and which one to delete.

Told you I was stupid. It was a db problem (column length too short)... Thanks a lot, you show me the right direction to look for. (btw and totally out of scope, do you have some roadmap for next release of the oauth2 part ?)

You're welcome. The OAuth 2.0 spec seems forever in a holding pattern of draft revisions. DotNetOpenAuth won't likely release an update until the spec is finalized. mvc - DotNetOpenAuth oAuth2 Message already been processed - S... oauth-2.0 dotnetopenauth
Rectangle 27 1

One way, is to have a base class(Which inturn inherits the class - "page") and all your aspx pages should inherit this base class. so that whenever a aspx page loads, your base pageLoad method is called. In this method you can check the authentication and authorization.

public class BasePage : System.Web.UI.Page

        public BasePage()
            this.Load += new EventHandler(BasePage_Load);

     void BasePage_Load(object sender, EventArgs e)
     //Check authentication/authorized
    //if authenticated/authorized leave it.. If not redirect to error page

    public partial class Forms_CreateUser : BasePage
        protected void Page_Load(object sender, EventArgs e)

    public partial class Forms_CreateRole : BasePage
        protected void Page_Load(object sender, EventArgs e)

security - preventing HTTP Replay Attack - Stack Overflow security
Rectangle 27 1

Ben, there are a few different types of attacks you need to be concerned with. For example simply encrypting the identifier with a private key doesn't prevent someone who can intercept the encrypted value from simply replaying it to your server (and appear to be the user). Some common security risks are detailed here (and in associated links at bottom of this page):

Session management can be quite complex and depending on the level of security you require, it is not something you want to tackle yourself, because likely your development environment / framework already has a solution that has been vetted moreso than a homebrew solution. Here is a link detailing some things to consider, unfortunately this topic has more to it than a simple Stack Overflow post:

thx for the input ill check those links

security - How to remember users with cookies in a secure way? - Stack...

security session-cookies
Rectangle 27 0

Calling the SignOut method only removes the forms authentication cookie. The Web server does not store valid and expired authentication tickets for later comparison. This makes your site vulnerable to a replay attack if a malicious user obtains a valid forms authentication cookie.

They give three ways to mitigate this risk. Only the last method (using persistent storage to keep track of login status yourself) will prevent the actual user from replaying the request. The first method just reduces the window of time of the vulnerability, and the second method keeps cookies secure from 3rd parties.

c# - What is the best way to log someone out of a web application? - S...

c# security session-state fiddler
Rectangle 27 0

If you hash in a time-stamp along with the user name and password, you can close the window for replay attacks to within a couple of seconds. I don't know if this meets your needs, but it is at least a partial solution.

Note that if the time-stamp/cookie is not encrypted or is otherwise spoof-able at the user-agent layer then this won't help as a hacker will just manipulate the time-stamp value. - How do I prevent replay attacks? - Stack Overflow security encryption
Rectangle 27 0

Can you use memory or a database to maintain any information about the user or request at all?

If so, then on request for the form, I would include a hidden form field whose contents are a randomly generated number. Save this token to in application context or some sort of store (a database, flat file, etc.) when the request is rendered. When the form is submitted, check the application context or database to see if that randomly generated number is still valid (however you define valid - maybe it can expire after X minutes). If so, remove this token from the list of "allowed tokens".

Thus any replayed requests would include this same token which is no longer considered valid on the server. - How do I prevent replay attacks? - Stack Overflow security encryption
Rectangle 27 0

(Replay attacks can easily be all about an IP/MAC spoofing, plus you're challenged on dynamic IPs )

It is not just replay you are after here, in isolation it is meaningless. Just use SSL and avoid handcrafting anything..

ASP.Net ViewState is a mess, avoid it. While PKI is heavyweight and bloated, at least it works without inventing your own security 'schemes'. So if I could, I'd use it and always go for mutual authent. Server-only authentification is quite useless. - How do I prevent replay attacks? - Stack Overflow security encryption
Rectangle 27 0

Along with cookie encryption, you should also implement a rotating token to prevent replay attacks.

The idea being that the encrypted cookie contains some value which can be compared to a known value on the server. If the data matches, then the request succeeds. If the data doesn't match then you are experiencing a replay attack and need to kill the session.

UPDATE One of the comments asked if I meant to store the value in the cookie. The answer is yes. The ENTIRE cookie should be encrypted, which can be automatically done through the use of an HttpModule. Inside the encrypted cookie is any of your normal information + the changing token.

On each post back, check the token. If it's valid, allow the transaction, create a new random token, store in the cookie, and send that back to the browser. Again, in an encrypted form.

The result is that your cookie is secure (you are using 3DES?) and any attacker would have an extremely limited window of opportunity to even attempt a replay attack. If a token didn't pass muster, you could simply sound the alarm and take appropriate measures.

All that's needed server side is to keep track of the user and their current token. Which is usually a much smaller db hit than having to look up little things like the users name on each page load.

UPDATE 2 I've been trying to figure out whether this is better or worse than keeping the changing value stored in session. The conclusion I've come to is that storing a rotating value in session on the web server does absolutely nothing to prevent replay attacks and is therefore less secure than putting that value in a cookie.

Consider this scenario. Browser makes request. Server looks at the session id and pulls up the session objects, work is then performed, and the response is sent back to the browser. In the meantime, BlackHat Bob recorded the transaction.

Bob then sends the exact same request (including session id) to the server. At this point there is absolutely no way for the server to know that this is a request from an attacker. You can't use IP as those might change due to proxy use, you can't use browser fingerprinting as all of that information would have been recorded in the initial exchange. Also, given that sessions are usually good for at least 30 minutes and sometimes much longer, the attacker has a pretty good sized window to work in.

So, no matter what, to prevent replay you have to send a changing token to the browser after each request.

Now this leaves us with the question about whether to also store values such as the user id in an encrypted cookie or store it server side in a session variable. With session you have concerns such as higher memory and cpu utilization as well as potential issues with load balancing etc. With cookies you have some amount of data that is less than 4kb, and, properly done, in the 1kb or less range that gets added to each request. I guess it will boil down to whether you would rather add more / larger servers and internal networking equipment to handle the requests (session) or pay for a slightly larger internet pipe (cookie).

You should be more specific. I assume that you do not mean to store the token in the cookie?

that makes sense, I thought you might be referencing to an anti CSRF token, which can't be stored in a cookie. This is a great solution to storing secure data in a cookie, but I don't see any advantage over traditional sessions.

c# - Is putting data in cookies secure? - Stack Overflow

c# .net security encryption cryptography
Rectangle 27 0

Sounds like POSTing tokens should resolve the issue, at least in this most obvious scenario you describe. Haven't used JWT tokens but SAML tokens are usually POSTed. I bet the server can be configured to post jwt tokens as well. - How do you prevent replay attacks with Thinktecture Identity... security thinktecture-ident-server thinktecture-ident-model
Rectangle 27 0

I created a little example of this using thr IpgaedList interface as per rob connerys. I actually pointed another SO user at it a while baclk. You can find the replay here:

along with links to the download for the full example.

> Yes this was my first attempt but it is not handling already existing url(querystring values) and its really this that is the hard part. I replaced the IPagedList with a another ListSettings class that fits my site better. Thanks for the suggestion.

oh well, at least you've gone down the road of 'discounting' approaches. good luck in the search

c# - Paging with ASP.NET MVC (URL manipulation?) - Stack Overflow

Rectangle 27 0

Aside from using a SSL connection for your application to make sure nobody steals the cookie to begin with, there is no fool-proof way to prevent replay attacks that utilize a stolen authentication cookie.

Your best bet is to set the cookie expiration to something pretty low and require the users re-enter their credentials after that timeout. Ideally, this would be a sliding window, but you could make it an absolute one if you don't mind really ticking off your users.

iphone - Protect api from replay attacks - Stack Overflow

iphone security api
Rectangle 27 0

You can place the users security token, IP address, and a time-stamp in a string. Encrypt the string with a symmetric algorithm such as AES and place it as a cookie. Then change your code to read from the cookie. You can validate that the ip address in the cookie matches the users ip address, this will prevent someone stealing the cookie value and replaying it. Here is the MSDN documentation on AES (Rjindael is the original name). In this scheme, the token will not expire until the cookie expires and/or your timeout is reached. I do highly recommend you put a timeout and not make it forever or persistent, it will make the scheme less secure to exclude a timeout. Also put the time-stamp at the beginning of your cookie value, because of CBC mode on these algorithms it will affect the way the encrypted string looks because of the changes in bits at the begining (Avalanche effect).

The ASP.NET membership provider also has an authentication cookie so this cookie should not expire before the membership cookie. Sessions have to expire on a timeout because there is no guarantee that the user is still there as HTTP is stateless whereas the cookie is under the control of the user and is passed every single time a request is made.

protected UserData getUsr()
        UserData usr = new UserData();

        string token = Request.Cookies["secToken"].Value;

        // implement RijndaelManaged encryption/decryption scheme
        // this can also be serialized as an object to make cleaner
        var tokenValues = Decrypt(token).Split(',');

        // The timeout expired
        if (DateTime.Now > DateTime.Parse(tokenValues[1]))
            throw new Exception("Timeout");

        // someone stole this cookie or is on a different internet connection
        if (tokenValues[0] != System.Web.HttpContext.Current.Request.UserHostAddress)
            throw new Exception("Invalid IP");

        // You're ok everything checks out
        usr.SecurityToken = tokenValues[3].ToString();

        MembershipUser mvcUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
        usr.Id = (int)mvcUser.ProviderUserKey;

        return usr;
    catch (Exception ex)
        log.Debug("Could not create usr object", ex);
        throw new Exception("Could not authenticate");

I'm worried about the security of this approach; is it industry standard to store this kind of information in a cookie? Also, and more importantly, how do I handle timeouts? membership cookie resets the timeout to 30 minutes every time the user hits a page, which means I'd need to rewrite my auth cookie each time too. Would I need to override the default behavior of some ASP.NET method?

One issue could be that the IP address the user is coming from could be a shared IP and therefore a user on the same network could hijack the cookie. As far as the security of the data being compromised, I would say it is highly unlikely that the cookie could be decrypted based on the algorithm (AES) itself, it will depend on your key generation, where and how you store that key. Sessions can be hijacked as well because the session id is sent as a cookie, an intermediary can steal and replay it and do the same thing. showed how that can be done.

As for timeouts you just need to put a datetime stamp in your cookie value as part of what is encrypted, you can reset that for 30 minutes each time the cookie is verified and re-write the cookie, that may be a little overkill though so maybe only do it if there is a short time left, e.g. set it for 30 minutes and if there's only 5 minutes left then recreate and rewrite the cookie. This way you're not writing the cookie for every single request.

Also the forms authentication ticket works in much the same way. Here is some information on how the authentication ticket works mvc - MVC save a token in session - Stack Overflow session authentication
Rectangle 27 0

This is due to cookie replay - what happens is that your browser sends the cookie with old authentication ticket which is accepted as a new session as the Web server does not store valid and expired authentication tickets for later comparison. This makes your site vulnerable to a replay attack if a malicious user obtains a valid forms authentication cookie. To improve security when using a forms authentication cookie see MSDN link below:

IIS7 ASP.NET in-proc session NOT being lost after app recycle - Stack ... session iis-7 session-state
Rectangle 27 0

I am new to some aspects of web programming but I was reading up on this the other day. I believe you need to use a Nonce. - How do I prevent replay attacks? - Stack Overflow security encryption
Rectangle 27 0

If you only accept each key once (say, make the key a GUID, and then check when it comes back), that would prevent replays. Of course, if the attacker responds first, then you have a new problem... - How do I prevent replay attacks? - Stack Overflow security encryption
Rectangle 27 0

Is this WebForms or MVC? If it's MVC you could utilize the AntiForgery token. This seems like it's similar to the approach you mention except it uses basically a GUID and sets a cookie with the guid value for that post. For more on that see Steve Sanderson's blog:

Another thing, have you considered checking the referrer on the postback? This is not bulletproof but it may help.

The question states that he can't rely on cookies for authentication. The MVC Anti-Forgery token in fact does rely on cookies, so it is unlikely that this would work for the question's scenario. Also, we should be careful about what we mean by "replay attacks" - anti-forgery tokens are designed to prevent CSRF attacks. Replay attack can come in various flavors - including from the originating user - in which case anti-forgery token would be useless. - How do I prevent replay attacks? - Stack Overflow security encryption