Compare commits
20 commits
Author | SHA1 | Date | |
---|---|---|---|
ce4891af79 | |||
413a6cad83 | |||
c44e457fd0 | |||
|
2a7e4fcd6e | ||
|
1ad357ba4a | ||
|
6a4de62467 | ||
|
7118641d78 | ||
|
4bed400c7d | ||
|
a88f298e98 | ||
|
9325300e39 | ||
|
34ab6489ba | ||
|
237abe539a | ||
|
9a2d05e51f | ||
|
512114517c | ||
|
3ef1d5daae | ||
|
e30ab77cf4 | ||
|
dc09a6be92 | ||
|
c6c19a1bcf | ||
|
ebd066b170 | ||
|
de4e2027a1 |
5 changed files with 213 additions and 115 deletions
34
.editorconfig
Normal file
34
.editorconfig
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
# .editorconfig
|
||||||
|
# EditorConfig settings for this code base.
|
||||||
|
# See documentation at <URL:http://editorconfig.org/>.
|
||||||
|
|
||||||
|
# Is this the top-most EditorConfig config file in the code base?
|
||||||
|
root = true
|
||||||
|
|
||||||
|
# Match all file names, unless more specific match later.
|
||||||
|
[*]
|
||||||
|
|
||||||
|
# Text encoding name.
|
||||||
|
charset = utf-8
|
||||||
|
|
||||||
|
# Remove trailing whitespace on lines?
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
# End-of-line style (“lf”, “cr”, “crlf”).
|
||||||
|
end_of_line = lf
|
||||||
|
|
||||||
|
# Ensure file ends with a line break?
|
||||||
|
insert_final_newline = true
|
||||||
|
|
||||||
|
# Character to use for indentation (“tab“ for U+0009, “space“ for U+0020).
|
||||||
|
indent_style = space
|
||||||
|
|
||||||
|
# Number of columns for each indentation level.
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
|
||||||
|
# Local variables:
|
||||||
|
# coding: utf-8
|
||||||
|
# mode: conf
|
||||||
|
# End:
|
||||||
|
# vim: fileencoding=utf-8 filetype=dosini :
|
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -1 +1,4 @@
|
||||||
.vscode/*
|
.vscode/*
|
||||||
|
.venv
|
||||||
|
log/*
|
||||||
|
auth-mastodon.ini
|
||||||
|
|
20
README.md
20
README.md
|
@ -5,14 +5,17 @@ The code is derived from [ejabberd-auth-mysql](https://github.com/rankenstein/ej
|
||||||
|
|
||||||
It is used on [Chinwag Social](https://social.chinwag.org) to provide XMPP messaging functionality to every account.
|
It is used on [Chinwag Social](https://social.chinwag.org) to provide XMPP messaging functionality to every account.
|
||||||
|
|
||||||
Discussion, questions and/or just saying hi in the [Chinwag Social Beergarden](xmpp:beergarden@rooms.chinwag.org?join) MUC (beergarden@rooms.chinwag.org) is welcomed!
|
Discussion, questions and/or just saying hi in the [Chinwag Social Beergarden](xmpp:beergarden@rooms.chinwag.org?join) MUC is welcomed!
|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
Edit the `auth-mastodon.py` file and add database connection credentials at the top. Moving this to a config file is next on the TODO list, as this makes updates an awful process. Sorry.
|
Edit the `auth-mastodon.ini.default` file and add database connection credentials, and a location for the log files if desired. Rename it and place it somewhere the ejabberd user can read it.
|
||||||
|
|
||||||
I recommend not using your main Mastodon database user account for this, and instead granting SELECT privileges on the Mastodon *accounts* and *users* tables to your ejabberd user instead.
|
I recommend not using your main Mastodon database user account for this, and instead granting SELECT privileges on the Mastodon *accounts* and *users* tables to your ejabberd user instead. The code here does not attempt any modification to the Mastodon tables at any point, so there's no reason to give it more than read-only rights.
|
||||||
|
|
||||||
The code here does not attempt any modification to the Mastodon tables at any point, so there's no reason to give it more than read-only rights.
|
The default locaction for the ini file is `/etc/ejabberd/auth-mastodon.ini` and can be changed with a command line option if desired:
|
||||||
|
```bash
|
||||||
|
$ auth-mastodon.py -c /usr/local/etc/auth-mastodon.ini
|
||||||
|
```
|
||||||
|
|
||||||
Then configure ejabberd to use `auth-mastodon.py` as an external authentication provider, as described in the [ejabberd docs](https://docs.ejabberd.im/admin/configuration/#external-script):
|
Then configure ejabberd to use `auth-mastodon.py` as an external authentication provider, as described in the [ejabberd docs](https://docs.ejabberd.im/admin/configuration/#external-script):
|
||||||
|
|
||||||
|
@ -20,9 +23,10 @@ Then configure ejabberd to use `auth-mastodon.py` as an external authentication
|
||||||
auth_method: external
|
auth_method: external
|
||||||
extauth_program: "/path/to/auth-mastodon.py"
|
extauth_program: "/path/to/auth-mastodon.py"
|
||||||
```
|
```
|
||||||
|
Startup and shutdown is handled by the ejabberd process, there's no need to handle this separately via systemd or similar. If the process is killed, ejabberd will restart it.
|
||||||
|
|
||||||
## To Do
|
## To Do
|
||||||
1. Move all database and config elements to a simple file to be stored in /etc/ejabberd or similar
|
1. Verify domain part of request somehow. Maybe define a canonical domain to be used in config? Does this gain us anything at all?
|
||||||
2. Verify domain part of request somehow. Maybe define a canonical domain to be used in config? Does this gain us anything at all?
|
2. Better error handling. Would be good to be more descriptive in the logs, perhaps.
|
||||||
3. Better error handling. Would be good to be more descriptive in the logs, perhaps.
|
3. Setup documentation is very brief, maybe include how to grant minimal permissions via pgsql.
|
||||||
4. Setup documentation is very brief, maybe include how to grant minimal permissions via pgsql.
|
4. Reconnection handling, exiting if a query fails would be a simple way to reload if a DB upgrade occurs but we should check if we're in a restart loop or something.
|
9
auth-mastodon.ini.default
Normal file
9
auth-mastodon.ini.default
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
[database]
|
||||||
|
db_host = localhost
|
||||||
|
db_port = 5432
|
||||||
|
db_user = ejabberd
|
||||||
|
db_pass =
|
||||||
|
db_name = mastodon
|
||||||
|
|
||||||
|
[log]
|
||||||
|
log_dir = /var/log/ejabberd/
|
116
auth-mastodon.py
116
auth-mastodon.py
|
@ -1,51 +1,96 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
import os, sys, logging, struct, psycopg2, bcrypt, random, atexit, time
|
|
||||||
|
|
||||||
# Database connection details. The credentials here need access to the Mastodon database, which "ejabberd" is unlikely
|
import atexit
|
||||||
# to have on your system by default. You shoud grant SELECT privileges to ejabberd on the "accounts" and "users" tables,
|
import logging
|
||||||
# to play it safe, or include the Mastodon DB user credentials here (don't).
|
import struct
|
||||||
db_host="localhost"
|
import sys
|
||||||
db_port=5432
|
import time
|
||||||
db_user="ejabberd"
|
|
||||||
db_pass=""
|
|
||||||
db_name="mastodon"
|
|
||||||
|
|
||||||
# This is the query that pulls the password hash for the given user. Mastodon doesn't store the domain for local accounts in
|
import argparse
|
||||||
# the database, so we ignore the host component and try to match username where the domain is NULL.
|
import configparser
|
||||||
db_query_getpass="select users.encrypted_password as password from accounts inner join users on accounts.id=users.account_id where lower(accounts.username) = %(user)s and accounts.domain is null"
|
import bcrypt
|
||||||
|
import psycopg2
|
||||||
|
|
||||||
|
# Get config file location from command line, or default to /etc/ejabberd
|
||||||
|
config_args = argparse.ArgumentParser()
|
||||||
|
config_args.add_argument("-c", "--config_file", help="Config file location", type=str, default="/etc/ejabberd/auth-mastodon.ini")
|
||||||
|
args = config_args.parse_args()
|
||||||
|
|
||||||
|
# Load database config from file, this is currently the only configurable item
|
||||||
|
config_ini = configparser.ConfigParser()
|
||||||
|
config_ini.read(args.config_file)
|
||||||
|
|
||||||
|
# Database connection details. The credentials here need access to the
|
||||||
|
# Mastodon database, which "ejabberd" is unlikely to have on your system
|
||||||
|
# by default. You shoud grant SELECT privileges to ejabberd on the
|
||||||
|
# "accounts" and "users" tables, to play it safe, or include the
|
||||||
|
# Mastodon DB user credentials here (don't).
|
||||||
|
db_host = config_ini.get('database', 'db_host', fallback='localhost')
|
||||||
|
db_port = config_ini.get('database', 'db_port', fallback=5432)
|
||||||
|
db_user = config_ini.get('database', 'db_user', fallback='ejabberd')
|
||||||
|
db_pass = config_ini.get('database', 'db_pass', fallback='')
|
||||||
|
db_name = config_ini.get('database', 'db_name', fallback='mastodon_production')
|
||||||
|
|
||||||
|
# This is the query that pulls the password hash for the given user.
|
||||||
|
# Mastodon doesn't store the domain for local accounts in the database,
|
||||||
|
# so we ignore the host component and try to match username where the
|
||||||
|
# domain is NULL.
|
||||||
|
db_query_getpass = """
|
||||||
|
SELECT users.encrypted_password AS password
|
||||||
|
FROM accounts
|
||||||
|
INNER JOIN users
|
||||||
|
ON accounts.id = users.account_id
|
||||||
|
WHERE
|
||||||
|
lower(accounts.username) = %(user)s
|
||||||
|
AND accounts.domain IS NULL
|
||||||
|
"""
|
||||||
|
|
||||||
########################################################################
|
########################################################################
|
||||||
# Setup
|
# Setup
|
||||||
########################################################################
|
########################################################################
|
||||||
|
|
||||||
sys.stderr = open('/var/log/ejabberd/extauth_err.log', 'a')
|
log_dir = config_ini.get('log', 'log_dir', fallback='/var/log/ejabberd')
|
||||||
logging.basicConfig(level=logging.INFO,
|
sys.stderr = open('%s/extauth_err.log' % log_dir, 'a')
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
format='%(asctime)s %(levelname)s %(message)s',
|
format='%(asctime)s %(levelname)s %(message)s',
|
||||||
filename='/var/log/ejabberd/extauth.log',
|
filename='%s/extauth.log' % log_dir,
|
||||||
filemode='a')
|
filemode='a',
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Connect to the DB, set autocommit and readonly otherwise postgresql seems to have a
|
# Connect to the DB, set autocommit and readonly otherwise
|
||||||
# tendency to keep things "idle in transaction" and table locks eventually grind
|
# postgresql seems to have a tendency to keep things "idle in
|
||||||
# Mastodon to a halt. We don't make any changes anyway.
|
# transaction" and table locks eventually grind Mastodon to a halt.
|
||||||
database=psycopg2.connect(host = db_host, user = db_user, password = db_pass, database = db_name, port = db_port)
|
# We don't make any changes anyway.
|
||||||
|
database = psycopg2.connect(
|
||||||
|
host=db_host,
|
||||||
|
user=db_user,
|
||||||
|
password=db_pass,
|
||||||
|
database=db_name,
|
||||||
|
port=db_port,
|
||||||
|
)
|
||||||
database.set_session(readonly=True, autocommit=True)
|
database.set_session(readonly=True, autocommit=True)
|
||||||
logging.debug(database.get_dsn_parameters())
|
logging.debug(database.get_dsn_parameters())
|
||||||
except:
|
except Exception:
|
||||||
logging.error("Unable to initialize database, check settings!")
|
logging.error("Unable to connect to %s as %s, check configuration" % (db_name, db_user))
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
@atexit.register
|
@atexit.register
|
||||||
def close_db():
|
def close_db():
|
||||||
cursor.close()
|
|
||||||
database.close()
|
database.close()
|
||||||
|
|
||||||
|
|
||||||
logging.info('auth-mastodon script started, waiting for ejabberd requests')
|
logging.info('auth-mastodon script started, waiting for ejabberd requests')
|
||||||
|
|
||||||
|
|
||||||
class EjabberdInputError(Exception):
|
class EjabberdInputError(Exception):
|
||||||
|
|
||||||
def __init__(self, value):
|
def __init__(self, value):
|
||||||
self.value = value
|
self.value = value
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return repr(self.value)
|
return repr(self.value)
|
||||||
|
|
||||||
|
@ -59,7 +104,7 @@ def ejabberd_in():
|
||||||
|
|
||||||
input_length = sys.stdin.buffer.read(2)
|
input_length = sys.stdin.buffer.read(2)
|
||||||
|
|
||||||
if len(input_length) is not 2:
|
if len(input_length) != 2:
|
||||||
logging.debug("ejabberd sent us wrong things!")
|
logging.debug("ejabberd sent us wrong things!")
|
||||||
raise EjabberdInputError('Wrong input from ejabberd!')
|
raise EjabberdInputError('Wrong input from ejabberd!')
|
||||||
|
|
||||||
|
@ -79,7 +124,9 @@ def ejabberd_out(bool):
|
||||||
|
|
||||||
token = genanswer(bool)
|
token = genanswer(bool)
|
||||||
|
|
||||||
logging.debug("sent bytes: %#x %#x %#x %#x" % (token[0], token[1], token[2], token[3]))
|
logging.debug(
|
||||||
|
"sent bytes: %#x %#x %#x %#x"
|
||||||
|
% (token[0], token[1], token[2], token[3]))
|
||||||
|
|
||||||
sys.stdout.buffer.write(token)
|
sys.stdout.buffer.write(token)
|
||||||
sys.stdout.buffer.flush()
|
sys.stdout.buffer.flush()
|
||||||
|
@ -94,22 +141,23 @@ def genanswer(bool):
|
||||||
|
|
||||||
|
|
||||||
def get_password(user, host):
|
def get_password(user, host):
|
||||||
# Right now we ignore the host component, as Mastodon doesn't store it for local accounts.
|
# Right now we ignore the host component, as Mastodon doesn't store
|
||||||
# It may be required one day, so the code to handle passing it to the query is left in for now.
|
# it for local accounts. It may be required one day, so the code to
|
||||||
|
# handle passing it to the query is left in for now.
|
||||||
cursor = database.cursor()
|
cursor = database.cursor()
|
||||||
cursor.execute(db_query_getpass, {"user": user.lower(), "host": host})
|
cursor.execute(db_query_getpass, {"user": user.lower(), "host": host})
|
||||||
data = cursor.fetchone()
|
data = cursor.fetchone()
|
||||||
cursor.close()
|
cursor.close()
|
||||||
return data[0] if data != None else None
|
return data[0] if data is not None else None
|
||||||
|
|
||||||
|
|
||||||
def isuser(user, host):
|
def isuser(user, host):
|
||||||
return get_password(user, host) != None
|
return get_password(user, host) is not None
|
||||||
|
|
||||||
|
|
||||||
def auth(user, host, password):
|
def auth(user, host, password):
|
||||||
db_password = get_password(user, host)
|
db_password = get_password(user, host)
|
||||||
if db_password == None:
|
if db_password is None:
|
||||||
logging.debug("Wrong username: %s@%s" % (user, host))
|
logging.debug("Wrong username: %s@%s" % (user, host))
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
|
@ -134,15 +182,15 @@ while True:
|
||||||
ejab_request = ejabberd_in().split(':', 3)
|
ejab_request = ejabberd_in().split(':', 3)
|
||||||
except EOFError:
|
except EOFError:
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception:
|
||||||
logging.exception("Exception occured while reading stdin")
|
logging.exception("Exception occured while reading stdin")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
op_result = False
|
op_result = False
|
||||||
try:
|
try:
|
||||||
# Only 'auth' and 'isuser' implemented, placeholders left to maybe
|
# Only 'auth' and 'isuser' implemented, placeholders left to
|
||||||
# expose other functions later but for now let's not even think about
|
# maybe expose other functions later but for now let's not even
|
||||||
# modifying the Mastodon DB
|
# think about modifying the Mastodon DB
|
||||||
if ejab_request[0] == "auth":
|
if ejab_request[0] == "auth":
|
||||||
op_result = auth(ejab_request[1], ejab_request[2], ejab_request[3])
|
op_result = auth(ejab_request[1], ejab_request[2], ejab_request[3])
|
||||||
elif ejab_request[0] == "isuser":
|
elif ejab_request[0] == "isuser":
|
||||||
|
|
Loading…
Add table
Reference in a new issue