def signin_2fa_auth_post_(request): sess = define.get_weasyl_session() # Only render page if the password has been authenticated (we have a UserID stored in the session) if '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] session_life = arrow.now( ).timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: # Maximum secondary authentication time: 5 minutes _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode. error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) elif two_factor_auth.verify(tfa_userid, request.params["tfaresponse"]): # 2FA passed, so login and cleanup. _cleanup_2fa_session() login.signin(tfa_userid) ref = request.params["referer"] or "/" # User is out of recovery codes, so force-deactivate 2FA if two_factor_auth.get_number_of_recovery_codes(tfa_userid) == 0: two_factor_auth.force_deactivate(tfa_userid) return Response( define.errorpage( tfa_userid, errorcode.error_messages[ 'TwoFactorAuthenticationZeroRecoveryCodesRemaining'], [["2FA Dashboard", "/control/2fa/status"], ["Return to the Home Page", "/"]])) # Return to the target page, restricting to the path portion of 'ref' per urlparse. raise HTTPSeeOther(location=urlparse.urlparse(ref).path) elif sess.additional_data['2fa_pwd_auth_attempts'] >= 5: # Hinder brute-forcing the 2FA token or recovery code by enforcing an upper-bound on 2FA auth attempts. _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode.error_messages[ 'TwoFactorAuthenticationAuthenticationAttemptsExceeded'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) else: # Log the failed authentication attempt to the session and save sess.additional_data['2fa_pwd_auth_attempts'] += 1 sess.save = True # 2FA failed; redirect to 2FA input page & inform user that authentication failed. return Response( define.webpage( request.userid, "etc/signin_2fa_auth.html", [ define.get_display_name(tfa_userid), request.params["referer"], two_factor_auth.get_number_of_recovery_codes(tfa_userid), "2fa" ], title="Sign In - 2FA"))
def signin_2fa_auth_post_(request): sess = define.get_weasyl_session() # Only render page if the session exists //and// the password has # been authenticated (we have a UserID stored in the session) if not sess.additional_data or '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] session_life = arrow.now().timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: # Maximum secondary authentication time: 5 minutes _cleanup_2fa_session() return Response(define.errorpage( request.userid, errorcode.error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]] )) elif two_factor_auth.verify(tfa_userid, request.params["tfaresponse"]): # 2FA passed, so login and cleanup. _cleanup_2fa_session() login.signin(request, tfa_userid, ip_address=request.client_addr, user_agent=request.user_agent) ref = request.params["referer"] or "/" # User is out of recovery codes, so force-deactivate 2FA if two_factor_auth.get_number_of_recovery_codes(tfa_userid) == 0: two_factor_auth.force_deactivate(tfa_userid) return Response(define.errorpage( tfa_userid, errorcode.error_messages['TwoFactorAuthenticationZeroRecoveryCodesRemaining'], [["2FA Dashboard", "/control/2fa/status"], ["Return to the Home Page", "/"]] )) # Return to the target page, restricting to the path portion of 'ref' per urlparse. raise HTTPSeeOther(location=urlparse.urlparse(ref).path) elif sess.additional_data['2fa_pwd_auth_attempts'] >= 5: # Hinder brute-forcing the 2FA token or recovery code by enforcing an upper-bound on 2FA auth attempts. _cleanup_2fa_session() return Response(define.errorpage( request.userid, errorcode.error_messages['TwoFactorAuthenticationAuthenticationAttemptsExceeded'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]] )) else: # Log the failed authentication attempt to the session and save sess.additional_data['2fa_pwd_auth_attempts'] += 1 sess.save = True # 2FA failed; redirect to 2FA input page & inform user that authentication failed. return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(tfa_userid), request.params["referer"], two_factor_auth.get_number_of_recovery_codes(tfa_userid), "2fa"], title="Sign In - 2FA"))
def test_force_deactivate(): user_id = db_utils.create_user() tfa_secret = pyotp.random_base32() tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret) _insert_2fa_secret(user_id, tfa_secret_encrypted) _insert_recovery_code(user_id) # Verify that force_deactivate() functions as expected. assert tfa.is_2fa_enabled(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 tfa.force_deactivate(user_id) assert not tfa.is_2fa_enabled(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0
def signin_2fa_auth_get_(request): sess = define.get_weasyl_session() # Only render page if the password has been authenticated (we have a UserID stored in the session) if '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] # Maximum secondary authentication time: 5 minutes session_life = arrow.now( ).timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: _cleanup_2fa_session() return Response( define.errorpage( request.userid, errorcode. error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) else: ref = request.params["referer"] if "referer" in request.params else "/" return Response( define.webpage( request.userid, "etc/signin_2fa_auth.html", [ define.get_display_name(tfa_userid), ref, two_factor_auth.get_number_of_recovery_codes(tfa_userid), None ], title="Sign In - 2FA"))
def test_force_deactivate(): user_id = db_utils.create_user() tfa_secret = pyotp.random_base32() tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret) _insert_2fa_secret(user_id, tfa_secret_encrypted) _insert_recovery_code(user_id) # Verify that force_deactivate() functions as expected. assert tfa.is_2fa_enabled(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 tfa.force_deactivate(user_id) assert not tfa.is_2fa_enabled(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0
def signin_2fa_auth_get_(request): sess = define.get_weasyl_session() # Only render page if the session exists //and// the password has # been authenticated (we have a UserID stored in the session) if not sess.additional_data or '2fa_pwd_auth_userid' not in sess.additional_data: raise WeasylError('InsufficientPermissions') tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] # Maximum secondary authentication time: 5 minutes session_life = arrow.now( ).timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: _cleanup_2fa_session() raise WeasylError('TwoFactorAuthenticationAuthenticationTimeout') else: ref = request.params["referer"] if "referer" in request.params else "/" return Response( define.webpage( request.userid, "etc/signin_2fa_auth.html", [ define.get_display_name(tfa_userid), ref, two_factor_auth.get_number_of_recovery_codes(tfa_userid), None ], title="Sign In - 2FA"))
def test_verify(): user_id = db_utils.create_user() tfa_secret = pyotp.random_base32() tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret) totp = pyotp.TOTP(tfa_secret) _insert_2fa_secret(user_id, tfa_secret_encrypted) _insert_recovery_code(user_id) # Codes of any other length than tfa.LENGTH_TOTP_CODE or tfa.LENGTH_RECOVERY_CODE returns False assert not tfa.verify(user_id, "a" * 5) assert not tfa.verify(user_id, "a" * 21) # TOTP token matches current expected value (Successful Verification) tfa_response = totp.now() assert tfa.verify(user_id, tfa_response) # TOTP token with space successfully verifies, as some authenticators show codes like # "123 456"; verify strips all spaces. (Successful Verification) tfa_response = totp.now() # Now split the code into a space separated string (e.g., u"123 456") tfa_response = tfa_response[:3] + ' ' + tfa_response[3:] assert tfa.verify(user_id, tfa_response) # TOTP token does not match current expected value (Unsuccessful Verification) assert not tfa.verify(user_id, "000000") # Recovery code does not match stored value (Unsuccessful Verification) assert not tfa.verify(user_id, "z" * tfa.LENGTH_RECOVERY_CODE) # Recovery code matches a stored recovery code (Successful Verification) assert tfa.verify(user_id, recovery_code) # Recovery codes are case-insensitive (Successful Verification) _insert_recovery_code(user_id) assert tfa.verify(user_id, recovery_code.lower()) # Recovery codes are consumed upon use (consumed previously) (Unsuccessful Verification) assert not tfa.verify(user_id, recovery_code) # When parameter `consume_recovery_code` is set to False, a recovery code is not consumed. _insert_recovery_code(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 assert tfa.verify(user_id, 'a' * tfa.LENGTH_RECOVERY_CODE, consume_recovery_code=False) assert tfa.get_number_of_recovery_codes(user_id) == 1
def tfa_status_get_(request): return Response( define.webpage(request.userid, "control/2fa/status.html", [ tfa.is_2fa_enabled(request.userid), tfa.get_number_of_recovery_codes(request.userid) ], title="2FA Status"))
def test_get_number_of_recovery_codes(): user_id = db_utils.create_user() # This /should/ be zero right now, but verify this for test environment sanity. assert 0 == d.engine.scalar(""" SELECT COUNT(*) FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0 _insert_recovery_code(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 d.engine.execute(""" DELETE FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0
def signin_post_(request): form = request.web_input(username="", password="", referer="", sfwmode="nsfw") form.referer = form.referer or '/' logid, logerror = login.authenticate_bcrypt(form.username, form.password, request=request, ip_address=request.client_addr, user_agent=request.user_agent) if logid and logerror is None: if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) # Invalidate cached versions of the frontpage to respect the possibly changed SFW settings. index.template_fields.invalidate(logid) raise HTTPSeeOther(location=form.referer) elif logid and logerror == "2fa": # Password authentication passed, but user has 2FA set, so verify second factor (Also set SFW mode now) if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) index.template_fields.invalidate(logid) # Check if out of recovery codes; this should *never* execute normally, save for crafted # webtests. However, check for it and log an error to Sentry if it happens. remaining_recovery_codes = two_factor_auth.get_number_of_recovery_codes(logid) if remaining_recovery_codes == 0: raise RuntimeError("Two-factor Authentication: Count of recovery codes for userid " + str(logid) + " was zero upon password authentication succeeding, " + "which should be impossible.") # Store the authenticated userid & password auth time to the session sess = define.get_weasyl_session() # The timestamp at which password authentication succeeded sess.additional_data['2fa_pwd_auth_timestamp'] = arrow.now().timestamp # The userid of the user attempting authentication sess.additional_data['2fa_pwd_auth_userid'] = logid # The number of times the user has attempted to authenticate via 2FA sess.additional_data['2fa_pwd_auth_attempts'] = 0 sess.save = True return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(logid), form.referer, remaining_recovery_codes, None], title="Sign In - 2FA" )) elif logerror == "invalid": return Response(define.webpage(request.userid, "etc/signin.html", [True, form.referer])) elif logerror == "banned": reason = moderation.get_ban_reason(logid) return Response(define.errorpage( request.userid, "Your account has been permanently banned and you are no longer allowed " "to sign in.\n\n%s\n\nIf you believe this ban is in error, please " "contact %s for assistance." % (reason, MACRO_SUPPORT_ADDRESS))) elif logerror == "suspended": suspension = moderation.get_suspension(logid) return Response(define.errorpage( request.userid, "Your account has been temporarily suspended and you are not allowed to " "be logged in at this time.\n\n%s\n\nThis suspension will be lifted on " "%s.\n\nIf you believe this suspension is in error, please contact " "%s for assistance." % (suspension.reason, define.convert_date(suspension.release), MACRO_SUPPORT_ADDRESS))) raise WeasylError("Unexpected") # pragma: no cover
def test_verify(): user_id = db_utils.create_user() tfa_secret = pyotp.random_base32() tfa_secret_encrypted = tfa._encrypt_totp_secret(tfa_secret) totp = pyotp.TOTP(tfa_secret) _insert_2fa_secret(user_id, tfa_secret_encrypted) _insert_recovery_code(user_id) # Codes of any other length than tfa.LENGTH_TOTP_CODE or tfa.LENGTH_RECOVERY_CODE returns False assert not tfa.verify(user_id, "a" * 5) assert not tfa.verify(user_id, "a" * 21) # TOTP token matches current expected value (Successful Verification) tfa_response = totp.now() assert tfa.verify(user_id, tfa_response) # TOTP token with space successfully verifies, as some authenticators show codes like # "123 456"; verify strips all spaces. (Successful Verification) tfa_response = totp.now() # Now split the code into a space separated string (e.g., u"123 456") tfa_response = tfa_response[:3] + ' ' + tfa_response[3:] assert tfa.verify(user_id, tfa_response) # TOTP token does not match current expected value (Unsuccessful Verification) assert not tfa.verify(user_id, "000000") # Recovery code does not match stored value (Unsuccessful Verification) assert not tfa.verify(user_id, "z" * tfa.LENGTH_RECOVERY_CODE) # Recovery code matches a stored recovery code (Successful Verification) assert tfa.verify(user_id, recovery_code) # Recovery codes are case-insensitive (Successful Verification) _insert_recovery_code(user_id) assert tfa.verify(user_id, recovery_code.lower()) # Recovery codes are consumed upon use (consumed previously) (Unsuccessful Verification) assert not tfa.verify(user_id, recovery_code) # When parameter `consume_recovery_code` is set to False, a recovery code is not consumed. _insert_recovery_code(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 assert tfa.verify(user_id, 'a' * tfa.LENGTH_RECOVERY_CODE, consume_recovery_code=False) assert tfa.get_number_of_recovery_codes(user_id) == 1
def test_get_number_of_recovery_codes(): user_id = db_utils.create_user() # This /should/ be zero right now, but verify this for test environment sanity. assert 0 == d.engine.scalar(""" SELECT COUNT(*) FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0 _insert_recovery_code(user_id) assert tfa.get_number_of_recovery_codes(user_id) == 1 d.engine.execute(""" DELETE FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id) assert tfa.get_number_of_recovery_codes(user_id) == 0
def signin_2fa_auth_get_(request): sess = define.get_weasyl_session() # Only render page if the password has been authenticated (we have a UserID stored in the session) if '2fa_pwd_auth_userid' not in sess.additional_data: return Response(define.errorpage(request.userid, errorcode.permission)) tfa_userid = sess.additional_data['2fa_pwd_auth_userid'] # Maximum secondary authentication time: 5 minutes session_life = arrow.now().timestamp - sess.additional_data['2fa_pwd_auth_timestamp'] if session_life > 300: _cleanup_2fa_session() return Response(define.errorpage( request.userid, errorcode.error_messages['TwoFactorAuthenticationAuthenticationTimeout'], [["Sign In", "/signin"], ["Return to the Home Page", "/"]])) else: ref = request.params["referer"] if "referer" in request.params else "/" return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(tfa_userid), ref, two_factor_auth.get_number_of_recovery_codes(tfa_userid), None], title="Sign In - 2FA"))
def signin_post_(request): form = request.web_input(username="", password="", referer="", sfwmode="nsfw") form.referer = form.referer or '/' logid, logerror = login.authenticate_bcrypt(form.username, form.password, request=request, ip_address=request.client_addr, user_agent=request.user_agent) if logid and logerror == 'unicode-failure': raise HTTPSeeOther(location='/signin/unicode-failure') elif logid and logerror is None: if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) # Invalidate cached versions of the frontpage to respect the possibly changed SFW settings. index.template_fields.invalidate(logid) raise HTTPSeeOther(location=form.referer) elif logid and logerror == "2fa": # Password authentication passed, but user has 2FA set, so verify second factor (Also set SFW mode now) if form.sfwmode == "sfw": request.set_cookie_on_response("sfwmode", "sfw", 31536000) index.template_fields.invalidate(logid) # Check if out of recovery codes; this should *never* execute normally, save for crafted # webtests. However, check for it and log an error to Sentry if it happens. remaining_recovery_codes = two_factor_auth.get_number_of_recovery_codes(logid) if remaining_recovery_codes == 0: raise RuntimeError("Two-factor Authentication: Count of recovery codes for userid " + str(logid) + " was zero upon password authentication succeeding, " + "which should be impossible.") # Store the authenticated userid & password auth time to the session sess = define.get_weasyl_session() # The timestamp at which password authentication succeeded sess.additional_data['2fa_pwd_auth_timestamp'] = arrow.now().timestamp # The userid of the user attempting authentication sess.additional_data['2fa_pwd_auth_userid'] = logid # The number of times the user has attempted to authenticate via 2FA sess.additional_data['2fa_pwd_auth_attempts'] = 0 sess.save = True return Response(define.webpage( request.userid, "etc/signin_2fa_auth.html", [define.get_display_name(logid), form.referer, remaining_recovery_codes, None], title="Sign In - 2FA" )) elif logerror == "invalid": return Response(define.webpage(request.userid, "etc/signin.html", [True, form.referer])) elif logerror == "banned": reason = moderation.get_ban_reason(logid) return Response(define.errorpage( request.userid, "Your account has been permanently banned and you are no longer allowed " "to sign in.\n\n%s\n\nIf you believe this ban is in error, please " "contact [email protected] for assistance." % (reason,))) elif logerror == "suspended": suspension = moderation.get_suspension(logid) return Response(define.errorpage( request.userid, "Your account has been temporarily suspended and you are not allowed to " "be logged in at this time.\n\n%s\n\nThis suspension will be lifted on " "%s.\n\nIf you believe this suspension is in error, please contact " "[email protected] for assistance." % (suspension.reason, define.convert_date(suspension.release)))) elif logerror == "address": return Response("IP ADDRESS TEMPORARILY BLOCKED") return Response(define.errorpage(request.userid))
def tfa_status_get_(request): return Response(define.webpage(request.userid, "control/2fa/status.html", [ tfa.is_2fa_enabled(request.userid), tfa.get_number_of_recovery_codes(request.userid) ], title="2FA Status"))