Created
February 10, 2022 23:56
-
-
Save rodorgas/6784ca4febb4841412effd69aaa0f4c2 to your computer and use it in GitHub Desktop.
Validate Django session with JavaScript or Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# python version | |
import hmac, base64, hashlib | |
const secret = '??' | |
def validate_session(session_data): | |
try: | |
hash, serialized = base64.b64decode(session_data).decode('utf-8').split(':', 1) | |
print(serialized) | |
salt = 'django.contrib.sessionsSessionStore' + secret | |
key = hashlib.sha1(salt.encode('utf-8')).digest() | |
expected_hash = hmac.new(key, msg=serialized.encode('utf8'), digestmod=hashlib.sha1).hexdigest() | |
except Exception as e: | |
return false | |
if not hmac.compare_digest(expected_hash, hash): | |
print('suspicious operation') | |
return false | |
return true | |
# js version | |
const crypto = require('crypto') | |
const salt = `django.contrib.sessionsSessionStore${secret}` | |
const secret = '??' | |
const decodeSessionData = (sessionData) => { | |
const sessionDataDec = Buffer.from(sessionData, 'base64') | |
const sepIndex = sessionDataDec.indexOf(':') | |
return [ | |
sessionDataDec.slice(0, sepIndex), | |
sessionDataDec.slice(sepIndex + 1), | |
] | |
} | |
const validateSession = (sessionData) => { | |
try { | |
const [hash, serialized] = decodeSessionData(sessionData) | |
const key = crypto.createHash('sha1').update(secret) | |
const expected_hash = crypto | |
.createHmac('sha1', key.digest()) | |
.update(serialized) | |
} | |
catch (error) { | |
console.error('suspicious operation') | |
return false | |
} | |
if (!crypto.timingSafeEqual(hash, expected_hash)) { | |
print('suspicious operation') | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment