Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing CSRF while using CORS?

I am making a bookmarklet so that a user can cross domain post to my server using CORS from any page. The user has to authenticate before posting and cookies are used. Is there any way to prevent a malicious website from imbedding javascript code in their webpage to do cross domain post to my server using the user's credential?

like image 354
coolsuntraveler Avatar asked Nov 13 '22 00:11

coolsuntraveler


1 Answers

In theory, there may be a solution for this.

  1. Embed a unique CSRF token in each user's bookmarklet.
  2. Wrap the code in the bookmarklet in an anonymous function, so the page won't have access to it.
  3. Embed a strong hash function in your bookmarklet. This has to be placed entirely within the bookmarklet's code, to ensure it can't be tampered with.
  4. In your XMLHttpRequest, you send:
    1. The message
    2. The hash of:
      1. The message
      2. Your CSRF token
      3. A unique, long salt
      4. A UserID
      5. A timestamp (just to make sure the message was sent now and not at another time)
    3. The salt
    4. The timestamp
    5. A userID
  5. At your server, you validate:
    1. That the timestamp is within the allowed error margin (which is necessary because a user's computer clock may be off)
    2. That the hash is correct
  6. If everything is correct, you can post the message.

There is one flaw with this concept: if a website tampers with any of the functions used by the bookmarklet (such as Array()), the malicious website may still be able to intercept, copy and / or modify the message, userID or CSRF token.

like image 67
user2428118 Avatar answered Jun 11 '23 00:06

user2428118