forked from ungleich-public/ungleich-user
Keep passwords out of activation links
The activation link carried base64-encoded username, password, names
and email, so plaintext passwords ended up in mail archives, browser
history and proxy logs.
Registration now hashes the password to {SSHA} immediately and stores
it in a new PendingRegistration table (migration 0002). The emailed
link is /activate/<token>/ with a random token only, and activation
writes the stored hash into LDAP. Pending entries expire after 24h,
like reset tokens. This also drops the PseudoUser/token-generator
workaround.
Links in emails sent before deployment stop working; those users must
register again.
This commit is contained in:
parent
23ddf33d41
commit
dad66040ed
6 changed files with 81 additions and 90 deletions
26
dal/migrations/0002_pendingregistration.py
Normal file
26
dal/migrations/0002_pendingregistration.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
# Generated by Django 2.2.28 on 2026-11-06 12:02
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dal', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='PendingRegistration',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('token', models.CharField(max_length=64, unique=True)),
|
||||
('username', models.CharField(max_length=100)),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('firstname', models.CharField(max_length=255)),
|
||||
('lastname', models.CharField(max_length=255)),
|
||||
('password_hash', models.CharField(max_length=255)),
|
||||
('creation', models.BigIntegerField()),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
|
@ -17,6 +17,22 @@ class ResetToken(models.Model):
|
|||
creation = models.BigIntegerField()
|
||||
|
||||
|
||||
class PendingRegistration(models.Model):
|
||||
"""A sign-up waiting for its email to be confirmed.
|
||||
|
||||
Only the {SSHA} hash of the password is kept, and the activation link
|
||||
carries nothing but the random token.
|
||||
"""
|
||||
token = models.CharField(max_length=64, unique=True)
|
||||
username = models.CharField(max_length=100)
|
||||
email = models.EmailField(max_length=254)
|
||||
firstname = models.CharField(max_length=255)
|
||||
lastname = models.CharField(max_length=255)
|
||||
password_hash = models.CharField(max_length=255)
|
||||
# creation time in epoch (UTC), like ResetToken
|
||||
creation = models.BigIntegerField()
|
||||
|
||||
|
||||
def get_validation_slug():
|
||||
return make_password(None)
|
||||
|
||||
|
|
|
|||
|
|
@ -109,9 +109,7 @@ class RegisterTests(LdapTestCase):
|
|||
data = self.form()
|
||||
self.track(data["username"])
|
||||
self.client.post(REGISTER, data)
|
||||
link = self.last_mail_link().rstrip("/")
|
||||
bad = link.rsplit("/", 1)[0] + "/not-the-token/"
|
||||
self.assertEqual(self.client.get(bad).status_code, 404)
|
||||
self.assertEqual(self.client.get("/activate/not-the-token/").status_code, 404)
|
||||
self.assertIsNone(self.ldap_entry(data["username"]))
|
||||
|
||||
def test_uid_numbers_are_unique(self):
|
||||
|
|
@ -124,15 +122,19 @@ class RegisterTests(LdapTestCase):
|
|||
uids.append(int(self.ldap_entry(data["username"]).uidNumber.value))
|
||||
self.assertNotEqual(uids[0], uids[1])
|
||||
|
||||
@expectedFailure
|
||||
def test_bug_password_not_in_activation_link(self):
|
||||
"""SECURITY: link carries base64(password); it lands in mail/proxy logs."""
|
||||
def test_password_not_in_activation_link_or_db(self):
|
||||
"""The plaintext password must never be stored or put in a URL."""
|
||||
from dal.models import PendingRegistration
|
||||
import base64
|
||||
data = self.form(password1="Very-Secret-pw-1", password2="Very-Secret-pw-1")
|
||||
self.track(data["username"])
|
||||
self.client.post(REGISTER, data)
|
||||
link = self.last_mail_link()
|
||||
self.assertNotIn(base64.b64encode(b"Very-Secret-pw-1").decode(), link)
|
||||
self.assertNotIn("Very-Secret-pw-1", mail.outbox[-1].body)
|
||||
stored = PendingRegistration.objects.get(username=data["username"])
|
||||
self.assertTrue(stored.password_hash.startswith("{SSHA}"))
|
||||
self.assertNotIn("Very-Secret-pw-1", stored.password_hash)
|
||||
|
||||
@expectedFailure
|
||||
def test_bug_cannot_register_name_taken_by_staff(self):
|
||||
|
|
|
|||
|
|
@ -72,7 +72,12 @@ class LdapManager:
|
|||
return passwd
|
||||
|
||||
|
||||
def create_user(self, user, password, firstname, lastname, email):
|
||||
def hash_password(self, password):
|
||||
"""Return the {SSHA} hash of *password* (str) as an ascii str."""
|
||||
return self._ssha_password(password.encode("utf-8")).decode("ascii")
|
||||
|
||||
def create_user(self, user, password_hash, firstname, lastname, email):
|
||||
"""Create a customer entry. *password_hash* comes from hash_password()."""
|
||||
conn = self.get_admin_conn()
|
||||
uidNumber = self._get_max_uid() + 1
|
||||
logger.debug("uidNumber={uidNumber}".format(uidNumber=uidNumber))
|
||||
|
|
@ -109,9 +114,7 @@ class LdapManager:
|
|||
"loginShell": ["/bin/bash"],
|
||||
"homeDirectory": ["/home/{}".format(user).encode("utf-8")],
|
||||
"mail": email.encode("utf-8"),
|
||||
"userPassword": [self._ssha_password(
|
||||
password.encode("utf-8")
|
||||
)]
|
||||
"userPassword": [password_hash.encode("ascii")]
|
||||
}
|
||||
)
|
||||
logger.debug('Created user %s %s' % (user.encode('utf-8'),
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ urlpatterns = [
|
|||
path('index/', Index.as_view(), name="index"),
|
||||
path('logout/', LogOut.as_view(), name="logout"),
|
||||
path('reset/<str:user>/<str:token>/', ResetRequest.as_view()),
|
||||
path('activate/<str:user>/<str:pwd>/<str:firstname>/<str:lastname>/<str:email>/<str:token>/', ActivateAccount.as_view()),
|
||||
path('activate/<str:token>/', ActivateAccount.as_view(), name="activate"),
|
||||
path('reset/', ResetRequest.as_view(), name="reset"),
|
||||
path('otp/', SeedRetrieveCreate.as_view(), name="seed"),
|
||||
path('', Index.as_view(), name="login_index"),
|
||||
|
|
|
|||
102
dal/views.py
102
dal/views.py
|
|
@ -6,12 +6,11 @@ from django.contrib.auth.models import User
|
|||
from django.http import HttpResponse
|
||||
from django.core.validators import validate_email, ValidationError
|
||||
from django.urls import reverse_lazy
|
||||
from django.contrib.auth.tokens import PasswordResetTokenGenerator
|
||||
from django.core.mail import EmailMessage
|
||||
from django.views.decorators.cache import cache_control
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from .models import ResetToken
|
||||
from .models import PendingRegistration, ResetToken
|
||||
from .forms import LoginForm
|
||||
from .ungleich_ldap import LdapManager
|
||||
from decouple import config, Csv
|
||||
|
|
@ -28,8 +27,6 @@ logger = logging.getLogger(__name__)
|
|||
from base64 import b64encode, b64decode
|
||||
from datetime import datetime
|
||||
|
||||
from random import choice, randint
|
||||
import string
|
||||
import requests
|
||||
import json
|
||||
|
||||
|
|
@ -53,32 +50,17 @@ RESET_SESSION_MAX_AGE = 60 * 60
|
|||
|
||||
|
||||
def activate_account_link(base_url, user, pwd, firstname, lastname, email, epochutc):
|
||||
tokengen = PasswordResetTokenGenerator()
|
||||
pseudouser = PseudoUser()
|
||||
token = tokengen.make_token(pseudouser)
|
||||
buser = bytes(user, 'utf-8')
|
||||
bpwd = bytes(pwd, 'utf-8')
|
||||
bfirstname = bytes(firstname, 'utf-8')
|
||||
blasttname = bytes(lastname, 'utf-8')
|
||||
bemail = bytes(email, 'utf-8')
|
||||
userpart = b64encode(buser)
|
||||
pwdpart = b64encode(bpwd)
|
||||
fnpart = b64encode(bfirstname)
|
||||
lnpart = b64encode(blasttname)
|
||||
mailpart = b64encode(bemail)
|
||||
# create entry into the database
|
||||
newdbentry = ResetToken(user=user, token=token, creation=epochutc)
|
||||
newdbentry.save()
|
||||
# set up the link
|
||||
link = "{base_url}/activate/{user}/{pwd}/{fn}/{ln}/{mail}/{token}/".format(
|
||||
base_url=base_url, user=userpart.decode('utf-8'),
|
||||
pwd=pwdpart.decode('utf-8'),
|
||||
fn=fnpart.decode('utf-8'),
|
||||
ln=lnpart.decode('utf-8'),
|
||||
mail=mailpart.decode('utf-8'),
|
||||
token=token
|
||||
"""Store a pending registration and return its activation link.
|
||||
|
||||
The password is hashed right away; the link only carries a random token.
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
PendingRegistration.objects.create(
|
||||
token=token, username=user, email=email, firstname=firstname,
|
||||
lastname=lastname, password_hash=LdapManager().hash_password(pwd),
|
||||
creation=epochutc,
|
||||
)
|
||||
return link
|
||||
return "{base_url}/activate/{token}/".format(base_url=base_url, token=token)
|
||||
|
||||
|
||||
def clean_db():
|
||||
|
|
@ -87,10 +69,8 @@ def clean_db():
|
|||
# using utcnow() to have no headache with timezones
|
||||
cutoff = int(datetime.utcnow().timestamp()) - (24*60*60)
|
||||
# Get all tokens older than 24 hours
|
||||
oldtokens = ResetToken.objects.all().filter(creation__lt=cutoff)
|
||||
for token in oldtokens:
|
||||
# delete all tokens older than 24 hours
|
||||
token.delete()
|
||||
ResetToken.objects.filter(creation__lt=cutoff).delete()
|
||||
PendingRegistration.objects.filter(creation__lt=cutoff).delete()
|
||||
return True
|
||||
|
||||
class Index(FormView):
|
||||
|
|
@ -533,74 +513,38 @@ class LogOut(View):
|
|||
|
||||
|
||||
|
||||
# TO be clarified
|
||||
|
||||
# To trick the tokengenerator to work with us, because we don't really
|
||||
# have the expected user Class since we are reading the user from a form
|
||||
# We store the tokens and don't have to use the check function,
|
||||
# some one time data works fine.
|
||||
|
||||
class LastLogin():
|
||||
def replace(self, microsecond=0, tzinfo=None):
|
||||
return randint(1,100000)
|
||||
|
||||
class PseudoUser():
|
||||
# easiest way to handle the check for lastlogin
|
||||
last_login = LastLogin()
|
||||
# random alphanumeric strings for primary key and password, just used for token generation
|
||||
pk = ''.join(choice(string.ascii_letters + string.digits) for _ in range(20))
|
||||
password = ''.join(choice(string.ascii_letters + string.digits) for _ in range(30))
|
||||
|
||||
|
||||
class ActivateAccount(View):
|
||||
|
||||
def get(self, request, user=None, pwd=None, firstname=None, lastname=None, email=None, token=None):
|
||||
def get(self, request, token=None):
|
||||
clean_db()
|
||||
if token is None:
|
||||
return HttpResponse('Invalid URL', status=404)
|
||||
elem_list = [user, pwd, firstname, lastname, email]
|
||||
clean_list = []
|
||||
for value in elem_list:
|
||||
try:
|
||||
value_temp = bytes(value, 'utf-8')
|
||||
value_decode = b64decode(value_temp)
|
||||
value_clean = value_decode.decode('utf-8')
|
||||
clean_list.append(value_clean)
|
||||
except Exception as e:
|
||||
return HttpResponse('Invalid URL', status=404)
|
||||
checks_out = False
|
||||
dbentries = ResetToken.objects.all().filter(user=clean_list[0])
|
||||
for entry in dbentries:
|
||||
if entry.token == token:
|
||||
# found the token, now delete it since it's used
|
||||
checks_out = True
|
||||
entry.delete()
|
||||
# No token was found
|
||||
if not checks_out:
|
||||
pending = PendingRegistration.objects.filter(token=token).first()
|
||||
if pending is None:
|
||||
return HttpResponse('Invalid URL.', status=404)
|
||||
# Token was found, create user
|
||||
# single use: consumed whether or not the creation below succeeds
|
||||
pending.delete()
|
||||
try:
|
||||
ldap_manager = LdapManager()
|
||||
ldap_manager.create_user(
|
||||
clean_list[0], clean_list[1], clean_list[2], clean_list[3], clean_list[4]
|
||||
pending.username, pending.password_hash,
|
||||
pending.firstname, pending.lastname, pending.email
|
||||
)
|
||||
req = requests.post(otp_url, data=json.dumps(
|
||||
{
|
||||
'auth_token': TOTP(admin_seed).now(),
|
||||
'auth_name': admin_name,
|
||||
'auth_realm': admin_realm,
|
||||
'name': clean_list[0],
|
||||
'name': pending.username,
|
||||
'realm': user_realm
|
||||
}), headers={'Content-Type': 'application/json'})
|
||||
if req.status_code != 201:
|
||||
logger.error("User {} failed to create its otp seed".format(clean_list[0]))
|
||||
logger.error("User {} failed to create its otp seed".format(pending.username))
|
||||
|
||||
#Send welcome email
|
||||
except Exception as e:
|
||||
return render(request, 'error.html', {'urlname': 'register',
|
||||
'service': 'register an user',
|
||||
'error': e})
|
||||
return render(request, 'usercreated.html', { 'user': clean_list[0] } )
|
||||
return render(request, 'usercreated.html', { 'user': pending.username } )
|
||||
|
||||
|
||||
class UserCreateAPI(APIView):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue