Why is flask-session in plain text? - python

I have a server-side session file created and I am new to web applications. I don't understand why the session files when opened with text file has plain content inside it. I have a secret key setup and all but why is it not encrypted?
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sessions import Session
app = Flask(__name__)
app.config['SECRET_KEY'] = 'keykeykey'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SESSION_USE_SIGNER'] = True
server_session = Session(app)
And on login the file route is
app.route('/login', methods=['GET', 'POST'])
def login_page():
session['email'] = email
return redirect(url_for('home_page'))
And on logout the route is
#app.route("/logout")
def logout():
session.pop('email', None)
return redirect(url_for("home_page"))
WHen the session is started a file is created in dir/flask-sessions/2029240f6d1128be89ddc32729463129, there are two files generated for each time and when I open it with notepad I can see the email id in plain text that is
Mø`.€•i }”(Œ
_permanent”ˆŒ
csrf_token”Œ(fb90d22be1adc1237c52730fadf95d1e07936cdd9e”Œemail”Œemail#email.com”u.
the ending email#email.com is the input from the form.
My questions are
Why is the content not encrypted even though it is stored in my server?
When I do session.pop() why is the file not deleted?
EDIT:
I guess the issue is because I use from cachelib import FileSystemCache instead of from werkzeug.contrib.cache import FileSystemCache?? Is that the issue? How can I overcome this as latest version of werkzeug doesn't have .contrib?

Trying to answer it to the best of my knowledge.
1) Why is the content not encrypted?
You do not really need to worry about the session stored in your server as long as your server is secured. The vulnerability is the session stored as cookies in the browser. To bypass that, the 'SECRET_KEY' is used to let the server sign the session variables before storing them in the browser. That is the reason why you might still see the session in plain text on the server. It will be signed in the browser cookie-data though.
2) When I do session.pop() why is the file not deleted?
To understand what the session.pop does, I did a little exercise.
At first, my flask session looked like this:
Session is: <SecureCookieSession {'id': '27260b14-405d-440a-9e38-daa32d9a7797', 'loggedin': True, 'username': 'Rajat Yadav'}>
When I pop all the keys in the session dict mapping, I am left with this:
New Session is: <SecureCookieSession {}>
The clarity is that the key:value pair gets deleted as we pop the session. One thing for sure is that pop does not delete the complete dictinary object but just the key:value pair inside.
To your question of the file not getting deleted, I believe deleting the dictionary object should do the trick.
Try:
del session
Let me know if this deletes the file.

Related

SESSION_COOKIE_SECURE does not encrypt session

I'm trying to put some security on my Flask web app. As a first step I'm going to make my session cookie secure by setting SESSION_COOKIE_SECURE to true.
But after I get my session cookie from "inspect element" I can decode session cookie easily and there is no difference whether I add SESSION_COOKIE_SECURE or not.
Here is my code:
from flask import Flask, request, app, render_template, session, send_file, redirect
MyApp = Flask(__name__)
MyApp.secret_key = "something"
application = MyApp
if __name__ == "__main__":
MyApp.debug = False
MyApp.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
)
MyApp.config["SESSION_PERMANENT"] = True
MyApp.run()
I also tried to add this attribute using the following syntax but this made no difference:
MyApp.config['SESSION_COOKIE_SECURE'] = True
When I try to print SESSION_COOKIE_SECURE I get this error
Traceback (most recent call last):
File "...", line ..., in <module>
print(MyApp.session_cookie_secure)
AttributeError: 'Flask' object has no attribute 'session_cookie_secure'
My Flask version is 1.0.2, and I'm on HTTPS.
Setting SESSION_COOKIE_SECURE does not encrypt the cookie value, no. When set, this causes Flask to create cookies with the "Secure" flag set. This means that a browser can only return the cookie to the server over an encrypted connection, nothing more. The setting doesn't change anything about the cookie value itself.
Flask produces cookies that are cryptographically signed, by default. That means that the cookie contents can be decoded but not altered, because a third party without access to the server secret can't create a valid signature for the cookie.
You generally don't need to encrypt your session cookie if you a) use HTTPS (which encrypts the data from outsiders) and b) protect your web app from XSS attacks. Without an XSS attack vector, attackers can't get access to your cookie contents at all anyway.
You certainly don't need to do so here, as SESSION_COOKIE_HTTPONLY means that the browser will never expose the cookie to JavaScript, and only someone with full access to the browser can see the cookie value.
Flask doesn't have a 'encrypt cookie' setting, because it is not deemed necessary when you can secure the cookie in other ways. You should not store information in a session cookie so sensitive that it should be protected from the end-user with access to the browser storage; keep such data on the server and only store a unique identifier in the session to retrieve that secret data later on.
If for some reason you can't keep such secrets out of the session cookie and are unwilling to accept that the end-user can read this data, then you'll have to encrypt the cookie yourself or use an alternative session provider for Flask, such as EncryptedSession.
As for the attribute error: only a few configuration settings are accessible as attributes on the Flask object. To print arbitrary configuration settings, use the app.config object:
print(MyApp.config['SESSION_COOKIE_SECURE'])

Moving a file using a python web service [duplicate]

this is a two-part question: I have seen individual pieces discussed, but can't seem to get the recommended suggestions to work together. I want to create a web service to store images and their metadata passed from a caller and run a test call from Postman to make sure it is working. So to pass an image (Drew16.jpg) to the web service via Postman, it appears I need something like this:
For the web service, I have some python/flask code to read the request (one of many variations I have tried):
from flask import Flask, jsonify, request, render_template
from flask_restful import Resource, Api, reqparse
...
def post(self, name):
request_data = request.get_json()
userId = request_data['UserId']
type = request_data['ImageType']
image = request.files['Image']
Had no problem with the data portion and straight JSON but adding the image has been a bugger. Where am I going wrong on my Postman config? What is the actual set of Python commands for reading the metadata and the file from the post? TIA
Pardon the almost blog post. I am posting this because while you can find partial answers in various places, I haven't run across a complete post anywhere, which would have saved me a ton of time. The problem is you need both sides to the story in order to verify either.
So I want to send a request using Postman to a Python/Flask web service. It has to have an image along with some metadata.
Here are the settings for Postman (URL, Headers):
And Body:
Now on to the web service. Here is a bare bones service which will take the request, print the metadata and save the file:
from flask import Flask, request
app = Flask(__name__)
# POST - just get the image and metadata
#app.route('/RequestImageWithMetadata', methods=['POST'])
def post():
request_data = request.form['some_text']
print(request_data)
imagefile = request.files.get('imagefile', '')
imagefile.save('D:/temp/test_image.jpg')
return "OK", 200
app.run(port=5000)
Enjoy!
Make sure `request.files['Image'] contains the image you are sending and follow http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ to save the file to your file system. Something like
file = request.files['Image']
file.save('./test_image.jpg')
might do what you want, while you will have to work out the details of how the file should be named and where it should be placed.

Simple server-side Flask session variable

What is the easiest way to have a server-side session variable in Flask?
Variable value:
A simple string
Not visible to the client (browser)
Not persisted to a DB -- simply vanishes when the session is gone
There is a built-in Flask session, but it sends the session data to the client:
session["secret"] = "I can see you"
The data is Base64 encoded and sent in a cryptographically signed cookie, but it is still trivial to read on the client.
In many frameworks, creating a server-side session variable is a one-liner, such as:
session.secret = "You can't see this"
The Flask solutions I have found so far are pretty cumbersome and geared towards handling large chunks of data. Is there a simple lightweight solution?
I think the Flask-Session extension is what you are looking for.
Flask-Session is an extension for Flask that adds support for Server-side Session to your application.
From the linked website:
from flask import Flask, session
from flask_session import Session # new style
# from flask.ext.session import Session # old style
app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
#app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')
This answer is from June 2020 for flask-session 0.3.2.
The documentation is here.
There are several available SESSION_TYPESs. filesystem is the most straightforward while you're testing. The expectation is you already have a Redis, database, etc. setup if you are going to use the other SESSION_TYPEs. Section on SESSION_TYPE and requirements
null: NullSessionInterface (default)
Redis: RedisSessionInterface
Memcached: MemcachedSessionInterface
filesystem: FileSystemSessionInterface
MongoDB: MongoDBSessionInterface
SQLAlchemy: SqlAlchemySessionInterface
Code example from the documentation. If you go to /set/ then the session['key'] is populated with the word 'value'. But if you go to /get/ first, then `session['key'] will not exist and it will return 'not set'.
from flask import Flask, session
from flask_session import Session
app = Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
#personal style preference compared to the first answer
Session(app)
#app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')

How to delete a particular key(for current session) from Flask-KVSession?

I am using Flask kvsession to avoid replay attacks, as the client side cookie based session used by Flask-login are prone to it.
Eg: If on /index page your cookie in the header is set for your app header like
myapp_session : 'value1'
and if you navigate to /important page you will get a new header like
myapp_session : 'value2' so if a hacker gets 'value1' he can perform replay attacks and misuse it, as it is never invalidated.
To solve this I am using flask-kvsession which stores the session cookie header value in a cache or some backend. SO basically only one myapp_session is generated and invalidated when you logout. But the problem is :-
__init__.py
from simplekv.memory.redisstore import RedisStore
import redis
store = RedisStore(redis.StrictRedis())
#store = memcache.Client(['127.0.0.1:11211'], debug =0)
store.ttl_support = True
app = create_app(__name__)
current_kvsession = KVSessionExtension(store, app)
If you look at the cleanup_session part of the code for kv-session
http://pythonhosted.org/Flask-KVSession/#flask_kvsession.KVSessionExtension.cleanup_sessions
It only deletes the expired sessions. But If I want to explicitly delete the value for the current myapp_session for a particular user on logout, how do I do that?
#app.before_request
def redirect_if_logout():
if request.path == url_for('logout'):
for key in app.kvsession_store.keys():
logger.debug(key)
m = current_kvsession.key_regex.match(key)
logger.debug('found %s', m)
app.kvsession_store.delete(key)
But this deletes all the keys as I don`t know what the unique key for the current session is.
Q2. Also, how to use memcache instead of redis as it doesn`t have the app.kvsession_store.keys() function and gives i/o error.
I think I just figured the 1st part of your question on how you can delete the specific key on logout.
As mentioned in the docs:
Internally, Flask-KVSession stores session ids that are serialized as
KEY_CREATED, where KEY is a random number (the sessions “true” id) and
CREATED a UNIX-timestamp of when the session was created.
Sample cookie value that gets created on client side (you can check with that cookie manager extenion for firefox):
c823af88aedaf496_571b3fd5.4kv9X8UvyQqtCtNV87jTxy3Zcqc
and session id stored in redis as key:
c823af88aedaf496_571b3fd5
So on logout handler, you just need to read the cookie value, split it and use the first part of the string:
Sample Code which worked for me:
import redis
from flask import Flask
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
app = Flask(__name__)
KVSessionExtension(store, app)
#Logout Handler
#app.route('/logout', methods=['GET'])
def logout():
#here you are reading the cookie
cookie_val = request.cookies.get('session').split(".")[0]
store.delete(cookie_val)
and since you have added ttl_support:
store.ttl_support = True
It will match the TTL(seconds) value from permanent_session_lifetime, if you have set that in config file or in the beginning of your app.py file.
For example, in my application I have set in the beginning of app.py file as:
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)
now, when I logout, it deletes the key in redis but it will not be removed until TTL for that turns to 0 from 300 (5 Min as mentioned in permanent_session_lifetime value ).
If you want to remove it from redis immediately, for that you can manually change the app.permanent_session_lifetime to 1 second, which will in turn change TTL for redis.
import redis
import os
from flask import Flask
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
app = Flask(__name__)
KVSessionExtension(store, app)
#Logout Handler
#app.route('/logout', methods=['GET'])
def logout():
cookie_val = request.cookies.get('session').split(".")[0]
app.permanent_session_lifetime = timedelta(seconds=1)
store.delete(cookie_val)
Using the above code, I was able to thwart session replay attacks.
and solution to your 2nd question:
3 possible mistakes that I can see are:
1: In the beginning of your code you have created:
store = RedisStore(redis.StrictRedis())
but in the loop you are using it as kvsession_store instead of just store:
app.kvsession_store.keys()
To use it without any errors/exceptions you can use it as store.keys() instead of app.store.keys():
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
for key in store.keys():
print key
store.delete(key) is not deleting the all keys, you are running it inside the loop which is one by one deleting all keys.

Flask-Login: Does not work on local machine but fine on hosting

I have a flask app, and I use flask-login, following tutorials (nothing fancy here)
works fine on hosting
works fine on my local MAC computer (at home)
does not work on my local Linux computer (at office, which may be behind a firewall, but I am able to do port-forwarding and connect to the database)
does not work on Chrome or Firefox
does not work if I serve on localhost instead of 127.0.0.1.
from flask.ext.login import LoginManager
login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.init_app(app)
login_manager.login_view = 'login'
def login():
error = None
form = LoginForm()
if request.method == 'POST':
user = db.users.find_one({"username": form.username.data})
pass_hash = generate_password_hash(form.password.data)
if user and User.validate_login( pass_hash, user['password'] ):
user_obj = User(user['username'])
session['logged_in'] = True
login_user(user_obj,remember=True)
flash("Logged in successfully", category='success')
print 'logged in: OK'
#return redirect(request.args.get("next") or url_for("index"))
return redirect( url_for("index"))
error = 'Invalid credentials'
return render_template('login.html', title='login', **locals())
well, when I enter my password wrong, it gives the "Invalid credentials" error. When I enter my password correctly, I do not see "Logged in successfully" flash, but on console I see "logged in OK". So there is no problem with DB connection. However I am not logged in. For example,
g.user.is_authenticated()
gives false in the template (this occurs only on my local Linux, on the other hand hosting and MAC successfully logs in the user).
Where and how are you saving the session in the browser?
Consider a session stored in a browser cookie for the production domain example.com, which you have also configured locally (by adding an override to your /etc/hosts file).
If your office server is configured to use a different subdomain, for example office.example.com, and REMEMBER_COOKIE_DOMAIN is set to example.com, the office server will not be able to read the cookie. The fix is to use a cross-domain cookie: REMEMBER_COOKIE_DOMAIN=.example.com (note the preceding dot).
Ref: https://flask-login.readthedocs.org/en/latest/#cookie-settings
With sessions come session management...
Are you using a client-based session management?
possible issues with the cookies e.g. cookie size, too much data in cookie
possible issues with the server secret key e.g. generating a new secret key each time
Are you using server-based session management (e.g. flask-kvsession)?
possible issues trying to access the same backend as prod e.g. firewall preventing access to a redis server
It is possible that you are trying to store more session data when hitting your dev server (e.g. longer server urls, debug data, etc...), which can be a pain to deal with when session management is done on the client.

Categories

Resources