Cross-site request forgery (CSRF) vulnerabilities occur when attackers can trick a user to perform sensitive authenticated operations on a web application without his consent.

Imagine a web application where an authenticated user can do actions like changing his email address and which has no CSRF protection. A malicious website could forge a web page form to send the HTTP request that change the user email. When the user visits the malicious web page, the form is automatically submitted in his name and his account email is changed to an arbitrary email.

Such an attack is only possible if the web browser automatically sends authentication information to the trusted domain (e.g cookie based authentication)

Ask Yourself Whether

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Sensitive Code Example

For a Django application, the code is sensitive when,

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
] # Sensitive: django.middleware.csrf.CsrfViewMiddleware is missing
@csrf_exempt # Sensitive
def example(request):
    return HttpResponse("default")

For a Flask application, the code is sensitive when,

app = Flask(__name__)
app.config['WTF_CSRF_ENABLED'] = False # Sensitive
app = Flask(__name__) # Sensitive: CSRFProtect is missing

@app.route('/')
def hello_world():
    return 'Hello, World!'
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)

@app.route('/example/', methods=['POST'])
@csrf.exempt # Sensitive
def example():
    return 'example '
class unprotectedForm(FlaskForm):
    class Meta:
        csrf = False # Sensitive

    name = TextField('name')
    submit = SubmitField('submit')

Compliant Solution

For a Django application,

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware', # Compliant
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
def example(request): # Compliant
    return HttpResponse("default")

For a Flask application,

app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app) # Compliant
@app.route('/example/', methods=['POST']) # Compliant
def example():
    return 'example '

class unprotectedForm(FlaskForm):
    class Meta:
        csrf = True # Compliant

    name = TextField('name')
    submit = SubmitField('submit')

See