This commit is contained in:
aitzol 2023-11-23 23:03:44 +01:00
parent 4fe1bec588
commit 9cc6bf6290
5 changed files with 53 additions and 145 deletions

125
app.py
View File

@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import bottle
from bottle import get, post, static_file, request, route, template
from bottle import get, post, static_file, request, route, template, error
from bottle import SimpleTemplate
from bottle.ext import beaker
from configparser import ConfigParser
@ -121,10 +121,8 @@ def get_index():
@get('/_2fa')
def get_index():
#newSession().get()
try:
reload(newSession().get()['username'], None, None)
#add_auth_attribute_step1(newSession().get()['username'], None, None)
return _2fa_tpl(data=newSession().get(), str=i18n.str)
except Exception as e:
return index_tpl(str=i18n.str)
@ -137,49 +135,6 @@ def get_index():
except Exception as e:
return index_tpl(str=i18n.str)
@post('/auth')
def post_user():
form = request.forms.getunicode
def error(msg):
return index_tpl(alerts=[('error', msg, 'fadeOut')], str=i18n.str)
if len(form('username')) < 3:
return error(i18n.msg[2])
elif not tools.input_validation(form('username')):
return error(i18n.msg[3])
if not tools.pwd_validation(form('password')):
return error(i18n.msg[21])
#username = form('username')
#password = form('password')
try:
login(form('username'), form('password'))
except Error as e:
LOG.warning("Unsuccessful attempt to login %s: %s" % (form('username'), e))
return error(str(e))
#data=[form('username'),form('password'),newSession().get()['id'],newSession().get()['authCode']]
#print('N:',newSession().get()['id'])
key = cryptocode.encrypt(form('password'), newSession().get()['id'])
#key = cryptocode.encrypt(data, newSession().get()['id'])
print(key)
key = base64.urlsafe_b64encode(str.encode(key))
print(key)
try:
if(check_2fa_step1(form('username'))):
print('kk')
#logout(form('username'))
return index_tpl(two_factor_authentication=True, key=key, str=i18n.str)
except Error as e:
LOG.warning("Erabiltzailea ez da aurkitu???")
return user_tpl(alerts=[('success', '%s %s' % (i18n.msg[1], form('username').capitalize()), 'fadeOut' )], data=newSession().get(), str=i18n.str)
'''
@post('/user')
def post_user():
form = request.forms.getunicode
@ -200,43 +155,51 @@ def post_user():
except Error as e:
LOG.warning("Unsuccessful attempt to login %s: %s" % (form('username'), e))
return error(str(e))
try:
#if(check_2fa_step1(form('username'))):
if(newSession().get()['secureAuth']):
# encrypt and store the credentials
sid = newSession().get()['id']
data = ';'.join([form('username'),form('password'),newSession().get()['authCode']])
data_enc = cryptocode.encrypt(data, newSession().get()['id'])
data_to_url = base64.urlsafe_b64encode(str.encode(data_enc))
memo.get(data_enc)
memo.sid=sid
logout(form('username'))
return index_tpl(two_factor_authentication=True, path=data_to_url, str=i18n.str)
except Error as e:
LOG.warning("Erabiltzailea ez da aurkitu???")
return user_tpl(alerts=[('success', '%s %s' % (i18n.msg[1], form('username').capitalize()), 'fadeOut' )], data=newSession().get(), str=i18n.str)
'''
@post('/user_step2/<key>')
def post_user_step2(key):
@post('/user/<path>')
def post_user_step2(path):
form = request.forms.getunicode
secret = newSession().get()['authCode']
username = newSession().get()['username']
password = base64.urlsafe_b64decode(key)
print(password)
password = cryptocode.decrypt(password.decode('utf-8'), newSession().get()['id'])
print(password)
#password = cryptocode.decrypt(key, newSession().get()['id'])
# decrypt url
path = base64.urlsafe_b64decode(path)
path = cryptocode.decrypt(path.decode('utf-8'), memo.sid)
data = path.split(';')
print('key:',key)
print("sid:",newSession().get()['id'])
print('pwd:',password)
logout(newSession().get()['username'])
username = data[0]
password = data[1]
secret = data[2]
def error(msg):
return index_tpl(alerts=[('error', msg, 'fadeOut')], str=i18n.str)
#if not tools._2fa_validation(form('code'), newSession().get()['authCode']):
if not tools._2fa_validation(form('code'), secret):
#logout(newSession().get()['username'])
#logout(username)
return error('Kode okerra. Saio hasierak huts egin du.')
else:
try:
login(username, password)
except Error as e:
LOG.warning("Unsuccessful attempt to login %s: %s" % (form('username'), e))
LOG.warning("Unsuccessful attempt to login %s: %s" % (username, e))
return error(str(e))
print(newSession().get())
return user_tpl(alerts=[('success', '%s %s' % (i18n.msg[1], newSession().get()['username']), 'fadeOut' )], data=newSession().get(), str=i18n.str)
@post('/signup')
@ -376,7 +339,6 @@ def post_enable_2fa():
username=newSession().get()['username']
add_auth_attribute_step1(username, tools.gen_secret(), action='enable')
except Error as e:
#add_auth_attribute_step1(newSession().get()['username'], None, None)
reload(newSession().get()['username'], None, None)
LOG.warning(e)
return error('2 urratseko autentifikazioa birgaitua izan da.')
@ -398,7 +360,6 @@ def post_disable_2fa():
username=newSession().get()['username']
add_auth_attribute_step1(username, None, action='disable')
except Error as e:
#add_auth_attribute_step1(newSession().get()['username'], None, None)
reload(newSession().get()['username'], None, None)
LOG.warning(e)
return error(str(e))
@ -509,6 +470,11 @@ def connect_ldap(conf, **kwargs):
return Connection(server, raise_exceptions=True, **kwargs)
@error(404)
@error(405)
def error404(error):
return index_tpl(str=i18n.str)
#LOGIN
def login(username, password):
@ -565,17 +531,7 @@ def login_user_ldap(conf, username, password):
#check if exists 2fa qr image
if(newSession().get()['secureAuth']):
tools.gen_qr(newSession().get()['authCode'])
#if(newSession().get()['secureAuth'] and not newSession().secure_logged_in):
#logout(newSession().get()['username'])
'''
def new_session(user_dn, c, conf, two_factor_auth):
while(two_factor_auth):
newSession().set(get_user_data(user_dn, c))
update_login_info(conf, user_dn)
if(newSession().get()['secureAuth']):
tools.gen_qr(newSession().get()['authCode'])
LOG.debug("%s logged in to %s" % (newSession().get()['username'], conf['base']))
'''
#LOGOUT
def logout(username):
n = N
@ -862,7 +818,6 @@ def add_auth_attribute_step2(conf, *args):
raise Error(i18n.msg[23])
def add_auth_attribute_step3(conf, username, code, action):
#set current LDAP
superUser = SuperUsers(conf)
@ -888,6 +843,7 @@ def add_auth_attribute_step3(conf, username, code, action):
reload=add_auth_attribute_step1
# CHECK SECUREAUTH
'''
def check_2fa_step1(username):
changed = []
@ -939,6 +895,7 @@ def check_2fa_step3(conf, username):
return(secure_auth_status)
#c.modify(user_dn, {'mail': [( MODIFY_REPLACE, new_email_addresses )]})
#newSession().set(get_user_data(user_dn, c))
'''
#CHANGE PASSWORD
def change_passwords(username, old_pass, new_pass):
@ -1191,6 +1148,16 @@ def update_login_info(conf, user_dn):
class Error(Exception):
pass
# TEMPORAL MEMORY
class tMemory(object):
def __init__(self):
self.data = None
self.sid = None
def get(self, data):
self.data = data
memo = tMemory()
#SESSIONS MANAGEMENT
def newSession():

Binary file not shown.

13
enc.py
View File

@ -1,13 +0,0 @@
import base64
def encrypt2(message,key):
return base64.encodestring("".join([chr(ord(message[i]) ^ ord(key[i % len(key)])) for i in xrange(len(message))]))
def decrypt2(message, key):
from itertools import cycle
decoded = base64.decodestring(message)
return "".join(chr(a ^ b) for a, b in zip(map(ord, decoded), cycle(map(ord, key))))
print(encrypt2("Jo ta ke irabazi arte", "0d0cc0c959044abbb8ba20a4531cea0f"))
print(decrypt2(encrypt2("Jo ta ke irabazi arte", "0d0cc0c959044abbb8ba20a4531cea0f"), "0d0cc0c959044abbb8ba20a4531cea0f"))

View File

@ -17,12 +17,12 @@
%try:
%if two_factor_authentication:
<form method="post" action="/user_step2/{{key}}">
<form method="post" action="/user/{{path}}">
<label for="code">kodea</label>
<input id="code" name="code" value="" type="text" required autofocus>
%end
%except:
<form method="post" action="/auth">
<form method="post" action="/user">
<label for="username">{{ str['usrn'] }}</label>
<input id="username" name="username" value="{{ get('username', '') }}" type="text" required autofocus>

View File

@ -1,46 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>{{ str['login'] }}</title>
<link rel="stylesheet" href="{{ url('static', filename='style.css') }}">
</head>
<body>
<main>
<h1>{{ str['login'] }}</h1>
%try:
%if two_factor_authentication:
<form method="post" action="/user_step2">
<label for="code">kodea</label>
<input id="code" name="code" value="" type="text" required autofocus>
%end
%except:
<form method="post" action="/auth">
<label for="username">{{ str['usrn'] }}</label>
<input id="username" name="username" value="{{ get('username', '') }}" type="text" required autofocus>
<label for="password">{{ str['pwd'] }}</label>
<input id="password" name="password" type="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,24}$" oninvalid="setCustomValidity('{{ str['pwd-pattern'] }}')" oninput="setCustomValidity('')" required>
%end
<button class="green" type="submit">{{str['login']}}</button>
<a href="/signup">{{ str['or-sign-up'] }}</a>
</form>
%for type, text, animation in get('alerts', []):
<div class="alerts {{ animation }}">
<div class="alert {{ type }}">{{ text }}</div>
</div>
%end
</main>
</body>
</html>