Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[16.0] [MIG] auth_sms #724

Open
wants to merge 17 commits into
base: 16.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
pre-commit:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions/setup-python@v2
with:
python-version: "3.11"
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
name: Detect unreleased dependencies
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- run: |
for reqfile in requirements.txt test-requirements.txt ; do
if [ -f ${reqfile} ] ; then
Expand Down Expand Up @@ -62,7 +62,7 @@ jobs:
INCLUDE: "${{ matrix.include }}"
EXCLUDE: "${{ matrix.exclude }}"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install addons and dependencies
Expand Down
124 changes: 124 additions & 0 deletions auth_sms/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
=================================
Two factor authentication via SMS
=================================

..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:744503b1e32edd0f7f70943a95a2bfff0489985e29584afa7934b48853b943dd
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github
:target: https://github.com/OCA/server-auth/tree/16.0/auth_sms
:alt: OCA/server-auth
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/server-auth-16-0/server-auth-16-0-auth_sms
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/server-auth&target_branch=16.0
:alt: Try me on Runboat

|badge1| |badge2| |badge3| |badge4| |badge5|

This module allows you to use SMS as second factor for user authentication.

While SMS is not the most secure way of delivering a secret, it's still safer
than no multi factor authentication at all.

**Table of contents**

.. contents::
:local:

Configuration
=============

#. Go to Settings/Technical/SMS providers and configure a provider.
While you can configure multiple ones, the addon will always pick the
topmost active provider for authorization.
#. On a user, enable the `Use SMS verification` checkbox

The addon understands the following configuration parameters:

auth_sms.code_chars
The characters used to generate a code. Default is generated from
Python's string.ascii_letters + string.digits.

You can repeat characters here to make some more or less probable to be
used.

auth_sms.code_length
The length of a code to be sent to the user via SMS. Default is 8.

auth_sms.rate_limit_limit, auth_sms.rate_limit_hours
The amount of sms to send for one user within a certain amount of time.
Default is to send at most 10 SMS within 24 hours.

Usage
=====

After a user has filled in the correct credentials, she will be taken to a second form where she's asked for the code that has been sent via SMS.

Known issues / Roadmap
======================

* add a config wizard to configure parameters
* add a button to send another code
* make SMS codes time out (currently they live as long as the session they were
generated for)
* make being able to turn on 2FA depend on some security group
* create some auth_mfa_code module and move a lot of code there to have a
common base for all MFA modules that generate some extra code to fill in

Bug Tracker
===========

Bugs are tracked on `GitHub Issues <https://github.com/OCA/server-auth/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/server-auth/issues/new?body=module:%20auth_sms%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.

Do not contact contributors directly about support or help with technical issues.

Credits
=======

Authors
~~~~~~~

* Therp BV

Contributors
~~~~~~~~~~~~

* Holger Brunn <[email protected]>

Other credits
~~~~~~~~~~~~~

* Odoo Community Association: `Icon <https://github.com/OCA/maintainer-tools/blob/master/template/module/static/description/icon.svg>`_.

Maintainers
~~~~~~~~~~~

This module is maintained by the OCA.

.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org

OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.

This module is part of the `OCA/server-auth <https://github.com/OCA/server-auth/tree/16.0/auth_sms>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
4 changes: 4 additions & 0 deletions auth_sms/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import models
from . import controllers
from . import exceptions
25 changes: 25 additions & 0 deletions auth_sms/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Copyright 2019 Therp BV <https://therp.nl>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Two factor authentication via SMS",
"version": "16.0.1.0.0",
"author": "Therp BV,Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Tools",
"website": "https://github.com/OCA/server-auth",
"summary": "Allow users to turn on two factor authentication via SMS",
"depends": [
"mail",
],
"demo": [
"demo/res_users.xml",
"demo/sms_provider.xml",
],
"data": [
"views/sms_provider.xml",
"views/res_users.xml",
"security/ir_rule.xml",
"templates/template_code.xml",
"security/ir.model.access.csv",
],
}
2 changes: 2 additions & 0 deletions auth_sms/controllers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import auth_sms
117 changes: 117 additions & 0 deletions auth_sms/controllers/auth_sms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Copyright 2019 Therp BV <https://therp.nl>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import base64
import random

from odoo import _, http
from odoo.http import request

from odoo.addons.web.controllers.home import Home

from ..exceptions import (
AccessDeniedNoSmsCode,
AccessDeniedSmsRateLimit,
AccessDeniedWrongSmsCode,
)


class AuthSms(Home):
@http.route()
def web_login(self, redirect=None, **kw):
try:
return super().web_login(redirect=redirect, **kw)
except AccessDeniedNoSmsCode as exception:
try:
request.env["res.users"]._auth_sms_send(exception.user.id)
except AccessDeniedSmsRateLimit:
return self._show_rate_limit(redirect=None, **kw)
return self._show_sms_entry(redirect=None, **kw)

def _show_rate_limit(self, redirect=None, **kw):
"""User has requested to much sms codes in a short period."""
# providers here as elsewhere are included in case auth_oauth is installed.
return request.render(
"web.login",
dict(
request.params.copy(),
providers=[],
error=_("Rate limit for SMS exceeded"),
),
)

def _show_sms_entry(self, redirect=None, **kw):
"""Show copy of login screen for sms entry."""
# password will be stored, encrypted, in the session, while
# the secret will be send (and later retrieved) from the browser.
password_bytes = request.params["password"].encode("utf8")
secret = self._auth_sms_generate_secret()
encrypted_password = self._auth_sms_xor(password_bytes, secret)
request.session["auth_sms.password"] = encrypted_password
encoded_secret_string = base64.b64encode(secret).decode("utf8")
return request.render(
"auth_sms.template_code",
dict(
request.params.copy(),
secret=encoded_secret_string,
redirect=redirect,
providers=[],
message=_("Please fill in the code sent to you by SMS"),
**kw
),
)

@http.route("/auth_sms/code", auth="none")
def code(self, password=None, secret=None, redirect=None, **kw):
# IN this case the password argument really contains the sms code.
request.session["auth_sms.code"] = password
encrypted_password = request.session["auth_sms.password"]
decoded_secret_bytes = base64.b64decode((secret or "").encode("utf8"))
decrypted_password = self._auth_sms_xor(
encrypted_password, decoded_secret_bytes
)
request.params["password"] = decrypted_password.decode("utf8")
request.params["login"] = request.params["user_login"]
try:
return self.web_login(
redirect=redirect, **dict(kw, password=request.params["password"])
)
except AccessDeniedWrongSmsCode:
return self._show_wrong_sms_code(secret, redirect=None, **kw)

def _show_wrong_sms_code(self, secret, redirect=None, **kw):
"""Wrong sms code entered, user can try again."""
del request.session["auth_sms.code"]
return request.render(
"auth_sms.template_code",
dict(
request.params.copy(),
secret=secret,
providers=[],
redirect=redirect,
databases=[],
error=_("Could not verify code"),
**kw
),
)

def _auth_sms_generate_secret(self):
"""Generate an OTP for storing the password in the session."""
otp_size = int(
request.env["ir.config_parameter"]
.sudo()
.get_param(
"auth_sms.otp_size",
128,
)
)
return bytes(bytearray([random.randrange(256) for dummy in range(otp_size)]))

def _auth_sms_xor(self, password, secret):
"""Xor password with secret, to encrypt or decrypt password.

password and secret should both be byte strings.
"""
assert len(secret) >= len(password)
assert isinstance(password, bytes)
assert isinstance(secret, bytes)
return bytes(bytearray(c ^ otp for c, otp in zip(password, secret)))
11 changes: 11 additions & 0 deletions auth_sms/demo/res_users.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="demo_user" model="res.users" context="{'no_reset_password': True}">
<field name="login">auth_sms_demo_user</field>
<field name="password">auth_sms_demo_user</field>
<field name="name">Auth SMS demo user</field>
<field name="mobile">0123456789</field>
<field name="email">[email protected]</field>
<field name="auth_sms_enabled" eval="True" />
</record>
</odoo>
7 changes: 7 additions & 0 deletions auth_sms/demo/sms_provider.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="sms_provider" model="sms.provider">
<field name="provider">messagebird</field>
<field name="api_key">XXXXX</field>
</record>
</odoo>
16 changes: 16 additions & 0 deletions auth_sms/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 20192024 Therp BV <https://therp.nl>.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).


class AccessDeniedNoSmsCode(Exception):
def __init__(self, user, message=None):
self.user = user
super().__init__(message)


class AccessDeniedWrongSmsCode(Exception):
pass


class AccessDeniedSmsRateLimit(Exception):
pass
4 changes: 4 additions & 0 deletions auth_sms/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from . import sms_provider
from . import res_users
from . import auth_sms_code
13 changes: 13 additions & 0 deletions auth_sms/models/auth_sms_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright 2019 Therp BV <https://therp.nl>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models


class AuthSmsCode(models.Model):
_name = "auth_sms.code"
_description = "Hold a code for a session"
_rec_name = "code"

code = fields.Char(required=True, index=True)
user_id = fields.Many2one("res.users", required=True, index=True)
session_id = fields.Char(index=True)
Loading
Loading