2020-05-09 18:00:07 +00:00
|
|
|
from flask import current_app
|
|
|
|
from flask_login import UserMixin
|
|
|
|
from cryptography.hazmat.primitives import hashes
|
|
|
|
from cryptography.hazmat.primitives import serialization
|
2020-05-10 12:34:28 +00:00
|
|
|
from collections.abc import MutableSequence
|
|
|
|
from datetime import datetime
|
2020-05-25 18:23:27 +00:00
|
|
|
from dateutil import tz
|
2020-05-10 12:34:28 +00:00
|
|
|
import pyotp
|
|
|
|
import json
|
2020-05-27 15:56:10 +00:00
|
|
|
import logging
|
|
|
|
import crypt
|
2022-07-15 08:53:06 +00:00
|
|
|
import secrets
|
|
|
|
import string
|
2020-05-27 15:56:10 +00:00
|
|
|
from flask_sqlalchemy import SQLAlchemy, orm
|
2022-02-20 15:54:35 +00:00
|
|
|
from flask_migrate import Migrate
|
2020-05-27 15:56:10 +00:00
|
|
|
from datetime import datetime
|
|
|
|
import uuid
|
|
|
|
import pyotp
|
2022-02-11 15:09:40 +00:00
|
|
|
from typing import Optional, Callable
|
2022-06-17 11:38:49 +00:00
|
|
|
from cryptography.x509 import Certificate as CertificateObj
|
2022-06-18 11:05:18 +00:00
|
|
|
from sqlalchemy.ext.declarative import DeclarativeMeta
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
|
2020-06-01 21:43:10 +00:00
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
db = SQLAlchemy()
|
2022-06-17 11:38:49 +00:00
|
|
|
migrate = Migrate()
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
|
|
|
|
BaseModel: DeclarativeMeta = db.Model
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
class SecurityUser(UserMixin):
|
|
|
|
|
|
|
|
def __init__(self, username):
|
|
|
|
self._username = username
|
|
|
|
|
|
|
|
def get_id(self):
|
|
|
|
return self._username
|
|
|
|
|
|
|
|
|
|
|
|
class Service(object):
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
def __init__(self, name: str):
|
2020-05-09 18:00:07 +00:00
|
|
|
self._name = name
|
2022-07-15 08:53:06 +00:00
|
|
|
self._app_token = False
|
2020-05-09 18:00:07 +00:00
|
|
|
self._client_cert = False
|
|
|
|
self._pki_config = {
|
|
|
|
'cn': '{username}',
|
|
|
|
'email': '{username}@{domain}'
|
|
|
|
}
|
|
|
|
|
|
|
|
@staticmethod
|
2022-06-18 17:35:05 +00:00
|
|
|
def from_config(name, config) -> 'Service':
|
2020-05-09 18:00:07 +00:00
|
|
|
"""
|
|
|
|
"""
|
|
|
|
service = Service(name)
|
2022-07-15 08:53:06 +00:00
|
|
|
if 'app_token' in config:
|
|
|
|
service._app_token = bool(config['app_token'])
|
2020-05-09 18:00:07 +00:00
|
|
|
if 'client_cert' in config:
|
|
|
|
service._client_cert = bool(config['client_cert'])
|
|
|
|
if 'pki_config' in config:
|
2020-05-10 17:37:57 +00:00
|
|
|
service._pki_config.update(config['pki_config'])
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
return service
|
|
|
|
|
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def name(self) -> str:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._name
|
|
|
|
|
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def client_cert(self) -> bool:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._client_cert
|
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
@property
|
|
|
|
def app_token(self) -> bool:
|
|
|
|
return self._app_token
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def pki_config(self) -> dict[str,str]:
|
2020-05-09 18:00:07 +00:00
|
|
|
if not self._client_cert:
|
|
|
|
raise Exception('invalid call')
|
|
|
|
return self._pki_config
|
|
|
|
|
|
|
|
|
|
|
|
class Certificate(object):
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
def __init__(self, cn: str, ca_name: str, cert_data: CertificateObj, revoked=False):
|
2020-05-09 18:00:07 +00:00
|
|
|
self._cn = cn
|
|
|
|
self._ca_name = ca_name
|
|
|
|
self._cert_data = cert_data
|
2020-05-25 18:23:27 +00:00
|
|
|
self._revoked = revoked
|
|
|
|
self._cert_data.not_valid_after.replace(tzinfo=tz.tzutc())
|
|
|
|
self._cert_data.not_valid_before.replace(tzinfo=tz.tzutc())
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def cn(self) -> str:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._cn
|
|
|
|
|
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def ca_name(self) -> str:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._ca_name
|
|
|
|
|
|
|
|
@property
|
2020-05-25 18:23:27 +00:00
|
|
|
def not_valid_before(self) -> datetime:
|
|
|
|
return self._cert_data.not_valid_before.replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal()).replace(tzinfo=None)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
|
|
|
@property
|
2020-05-25 18:23:27 +00:00
|
|
|
def not_valid_after(self) -> datetime:
|
|
|
|
return self._cert_data.not_valid_after.replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal()).replace(tzinfo=None)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2020-05-25 18:23:27 +00:00
|
|
|
@property
|
|
|
|
def serial_number(self) -> int:
|
|
|
|
return self._cert_data.serial_number
|
|
|
|
|
|
|
|
@property
|
|
|
|
def serial_number_hex(self) -> str:
|
|
|
|
return f'{self._cert_data.serial_number:X}'
|
|
|
|
|
|
|
|
def fingerprint(self, algorithm=hashes.SHA256()) -> bytes:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._cert_data.fingerprint(algorithm)
|
|
|
|
|
2020-05-25 18:23:27 +00:00
|
|
|
@property
|
|
|
|
def is_valid(self) -> bool:
|
|
|
|
return self.not_valid_after > datetime.now() and not self._revoked
|
|
|
|
|
|
|
|
def pem(self) -> str:
|
2020-05-09 18:00:07 +00:00
|
|
|
return self._cert_data.public_bytes(encoding=serialization.Encoding.PEM).decode()
|
|
|
|
|
2020-05-25 18:23:27 +00:00
|
|
|
@property
|
|
|
|
def raw(self):
|
|
|
|
return self._cert_data
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
def __str__(self):
|
|
|
|
return f'Certificate(cn={self._cn}, ca_name={self._ca_name}, not_valid_before={self.not_valid_before}, not_valid_after={self.not_valid_after})'
|
|
|
|
|
2020-05-10 12:34:28 +00:00
|
|
|
|
2020-05-27 15:56:10 +00:00
|
|
|
def generate_uuid():
|
|
|
|
return str(uuid.uuid4())
|
2020-05-10 12:34:28 +00:00
|
|
|
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
class User(BaseModel):
|
2020-05-27 15:56:10 +00:00
|
|
|
id = db.Column(
|
|
|
|
db.String(length=36), primary_key=True, default=generate_uuid)
|
|
|
|
username = db.Column(
|
2020-06-01 21:43:10 +00:00
|
|
|
db.String, unique=True, nullable=False)
|
2022-06-17 11:38:49 +00:00
|
|
|
password_hashed = db.Column(
|
|
|
|
db.String, nullable=False)
|
2022-02-06 22:57:01 +00:00
|
|
|
alternative_email = db.Column(
|
|
|
|
db.String, nullable=True)
|
2020-06-01 21:43:10 +00:00
|
|
|
created_at = db.Column(db.DateTime, nullable=False,
|
|
|
|
default=datetime.now)
|
|
|
|
modified_at = db.Column(db.DateTime, nullable=False,
|
|
|
|
default=datetime.now, onupdate=datetime.now)
|
|
|
|
last_login = db.Column(db.DateTime, nullable=True)
|
2020-05-10 12:34:28 +00:00
|
|
|
|
2022-06-17 11:38:49 +00:00
|
|
|
enabled = db.Column(db.Boolean, nullable=False, default=False)
|
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
app_tokens = db.relationship('AppToken', back_populates='user')
|
2020-05-27 15:56:10 +00:00
|
|
|
totps = db.relationship('Totp', back_populates='user')
|
2022-04-08 19:28:22 +00:00
|
|
|
webauthn_credentials = db.relationship('WebauthnCredential', back_populates='user', cascade='delete,delete-orphan', passive_deletes=True)
|
2020-05-10 12:34:28 +00:00
|
|
|
|
2020-06-01 21:43:10 +00:00
|
|
|
def __init__(self, **kwargs):
|
2022-06-18 11:05:18 +00:00
|
|
|
super().__init__(**kwargs)
|
2020-05-10 12:34:28 +00:00
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
@property
|
2022-06-18 11:05:18 +00:00
|
|
|
def is_authenticated(self) -> bool:
|
2020-05-09 18:00:07 +00:00
|
|
|
return True # TODO
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
def get(self, key) -> None:
|
2022-02-06 22:57:01 +00:00
|
|
|
print(f'getitem: {key}') # TODO
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2020-06-01 21:43:10 +00:00
|
|
|
@property
|
2022-07-15 08:53:06 +00:00
|
|
|
def groups(self) -> list['Group']:
|
2020-06-01 21:43:10 +00:00
|
|
|
if self.username == 'tuxcoder':
|
|
|
|
return [Group(name='admin')]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
@property
|
2022-02-06 22:57:01 +00:00
|
|
|
def email(self) -> str:
|
2020-05-30 21:43:55 +00:00
|
|
|
domain = current_app.config['DOMAIN']
|
|
|
|
return f'{self.username}@{domain}'
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
def change_password(self, password_new: str) -> None:
|
|
|
|
self.password_hashed = crypt.crypt(password_new)
|
|
|
|
|
|
|
|
def get_tokens_by_service(self, service: Service) -> list['AppToken']:
|
|
|
|
return [ token for token in self.app_tokens if token.service_name == service.name ]
|
|
|
|
|
|
|
|
def get_token(self, service: Service, name: str) -> Optional['AppToken']:
|
|
|
|
for token in self.app_tokens:
|
|
|
|
if token.service_name == service.name and token.name == name:
|
|
|
|
return token # type: ignore
|
|
|
|
return None
|
|
|
|
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
class AppToken(BaseModel):
|
2022-06-17 11:38:49 +00:00
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
service_name = db.Column(db.String, nullable=False)
|
2022-07-15 08:53:06 +00:00
|
|
|
user_id = db.Column(
|
|
|
|
db.String(length=36),
|
|
|
|
db.ForeignKey(User.id), nullable=False)
|
|
|
|
user = db.relationship(User)
|
2022-06-17 11:38:49 +00:00
|
|
|
token = db.Column(db.String, nullable=False)
|
|
|
|
name = db.Column(db.String, nullable=False)
|
2022-07-15 08:53:06 +00:00
|
|
|
last_used = db.Column(db.DateTime, nullable=True)
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-07-15 08:53:06 +00:00
|
|
|
@staticmethod
|
|
|
|
def new(service: Service):
|
|
|
|
app_token = AppToken()
|
|
|
|
app_token.service_name = service.name
|
|
|
|
alphabet = string.ascii_letters + string.digits
|
|
|
|
app_token.token = ''.join(secrets.choice(alphabet) for i in range(12))
|
|
|
|
return app_token
|
2020-05-09 18:00:07 +00:00
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
class Totp(BaseModel):
|
2020-05-27 15:56:10 +00:00
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
secret = db.Column(db.String, nullable=False)
|
|
|
|
name = db.Column(db.String, nullable=False)
|
|
|
|
created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
|
2022-07-15 08:53:06 +00:00
|
|
|
last_used = db.Column(db.DateTime, nullable=True)
|
2020-05-27 15:56:10 +00:00
|
|
|
|
|
|
|
user_id = db.Column(
|
|
|
|
db.String(length=36),
|
|
|
|
db.ForeignKey(User.id), nullable=False)
|
|
|
|
user = db.relationship(User)
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
def verify(self, token: str) -> bool:
|
2020-05-27 15:56:10 +00:00
|
|
|
totp = pyotp.TOTP(self.secret)
|
|
|
|
return totp.verify(token)
|
|
|
|
|
2022-04-08 19:28:22 +00:00
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
class WebauthnCredential(BaseModel): # pylint: disable=too-few-public-methods
|
2022-04-08 19:28:22 +00:00
|
|
|
"""Webauthn credential model"""
|
|
|
|
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
2022-04-08 19:29:23 +00:00
|
|
|
user_id = db.Column(db.String(length=36), db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
|
2022-04-08 19:28:22 +00:00
|
|
|
user_handle = db.Column(db.String(64), nullable=False)
|
|
|
|
credential_data = db.Column(db.LargeBinary, nullable=False)
|
|
|
|
name = db.Column(db.String(250))
|
|
|
|
registered = db.Column(db.DateTime, default=datetime.utcnow)
|
|
|
|
|
|
|
|
user = db.relationship('User', back_populates='webauthn_credentials')
|
|
|
|
|
|
|
|
|
2022-06-18 11:05:18 +00:00
|
|
|
class Group(BaseModel):
|
2020-05-27 19:16:14 +00:00
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
2020-06-01 21:43:10 +00:00
|
|
|
name = db.Column(db.String(), nullable=False, unique=True)
|
|
|
|
|