On Flask, Semgrep, and Secure Coding

Photo by Gary Butterfield on Unsplash

Writing the first lines of code

Insecure Flask application
Running the application from the terminal
Flask application returning a dynamic string

What is wrong with this code?

name = request.args.get('name')return f'Hello {name}!,  Welcome to Flask'
XSS in Flask application

How to perform input sanitization in Flask?

Flask escape documentation
name = escape(request.args.get('name'))
Using Flask escape function
XSS attempt

Flask and Static Code Analysis

Semgrep rules for Flasy by r2c
semgrep --config "p/flask"
Flask’s semgrep rules

Let’s create our own rule

rules:- id: my_pattern_idpatterns:- pattern: flask.request.args.get(...)message: Flask, Improper input data validation!languages: [python]severity: ERROR
semgrep --config semgrep-rule.yml
semgrep rule in action

Dealing with False Positives

semgrep rule still triggers
rules:- id: my_pattern_idpatterns:- pattern: flask.request.args.get(...)- pattern-not-inside: escape(...)message: Flask, Improper input data validation!languages: [python]severity: ERROR
Semgrep rule multiple patterns

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store