Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

142 | Chapter 5: Security


Since a browser holding a cookie for the target site will send that cookie with each
request, the server receives the request and the cookie and performs the action.


A sample CSRF attack takes place as follows. This process is illustrated in Figure 5-1.



  1. The client receives code from the attacker, via either a compromised server or a
    script or image tag placed by the attacker on a third-party web site (possibly via
    XSS). The code references a URI of the target application that performs some
    action.

  2. The client requests that URI from the target application, sending the authentica-
    tion cookie (because the client is already authenticated to the target). The target
    then performs the action on the client’s behalf, even though the end user did not
    authorize the action.


CSRF mitigation


The first and foremost way to defend against CSRF is to use the proper HTT Pverbs.
This has been the mantra of the Rails core team since before Rails 1.0.GETandHEAD
requests should besafe: they can be called without changing server state.GET,HEAD,
PUT, andDELETEshould beidempotent: calling them once or 100 times should have
the same effect. (They are defined this way so that a client, unsure if a request has
completed, can retry the same request with no ill effects.)


So, the primary problem with the preceding example is that it used a verb that
should be safe (GET) with an action that caused side effects (instant_purchase). If the
action had in fact been free of side effects, there would have been no problem. No
confidential information could be leaked directly, as the response went directly from
the target to the client. The basic problem is that the wrong HTT Pverb was used.
We will revisit this discussion in Chapter 7, when we discuss the REST architectural
style.


Figure 5-1. Cross-Site Request Forgery


Attacker’s
site

Client 2 Target
GET /instant_purchase?id=123 HTTP/1.1
Cookie: auth_token=ao98gaw4

1 <img src="http://target/instant_purchase?id=123"/>
Free download pdf