External authentication script for ejabberd to validate Mastodon accounts directly from the database. https://social.chinwag.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

168 lines
5.2 KiB

  1. #!/usr/bin/env python3
  2. import os, sys, logging, struct, psycopg2, bcrypt, random, atexit, time
  3. # Database connection details. The credentials here need access to the Mastodon database, which "ejabberd" is unlikely
  4. # to have on your system by default. You shoud grant SELECT privileges to ejabberd on the "accounts" and "users" tables,
  5. # to play it safe, or include the Mastodon DB user credentials here (don't).
  6. db_host="localhost"
  7. db_port=5432
  8. db_user="ejabberd"
  9. db_pass=""
  10. db_name="mastodon"
  11. # This is the query that pulls the password hash for the given user. Mastodon doesn't store the domain for local accounts in
  12. # the database, so we ignore the host component and try to match username where the domain is NULL.
  13. 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"
  14. ########################################################################
  15. #Setup
  16. ########################################################################
  17. sys.stderr = open('/var/log/ejabberd/extauth_err.log', 'a')
  18. logging.basicConfig(level=logging.INFO,
  19. format='%(asctime)s %(levelname)s %(message)s',
  20. filename='/var/log/ejabberd/extauth.log',
  21. filemode='a')
  22. try:
  23. # Connect to the DB, set autocommit and readonly otherwise postgresql seems to have a
  24. # tendency to keep things "idle in transaction" and table locks eventually grind
  25. # Mastodon to a halt. We don't make any changes anyway.
  26. database=psycopg2.connect(host = db_host, user = db_user, password = db_pass, database = db_name, port = db_port)
  27. database.set_session(readonly=True, autocommit=True)
  28. logging.debug(database.get_dsn_parameters())
  29. except:
  30. logging.error("Unable to initialize database, check settings!")
  31. time.sleep(10)
  32. sys.exit(1)
  33. @atexit.register
  34. def close_db():
  35. cursor.close()
  36. database.close()
  37. logging.info('auth-mastodon script started, waiting for ejabberd requests')
  38. class EjabberdInputError(Exception):
  39. def __init__(self, value):
  40. self.value = value
  41. def __str__(self):
  42. return repr(self.value)
  43. ########################################################################
  44. #Declarations
  45. ########################################################################
  46. def ejabberd_in():
  47. logging.debug("trying to read 2 bytes from ejabberd:")
  48. input_length = sys.stdin.buffer.read(2)
  49. if len(input_length) is not 2:
  50. logging.debug("ejabberd sent us wrong things!")
  51. raise EjabberdInputError('Wrong input from ejabberd!')
  52. logging.debug('got 2 bytes via stdin: %s'%input_length)
  53. (size,) = struct.unpack('>h', input_length)
  54. logging.debug('size of data: %i'%size)
  55. income=sys.stdin.read(size)
  56. logging.debug("incoming data: %s"%income)
  57. return income
  58. def ejabberd_out(bool):
  59. logging.debug("Ejabberd gets: %s" % bool)
  60. token = genanswer(bool)
  61. logging.debug("sent bytes: %#x %#x %#x %#x" % (token[0], token[1], token[2], token[3]))
  62. sys.stdout.buffer.write(token)
  63. sys.stdout.buffer.flush()
  64. def genanswer(bool):
  65. answer = 0
  66. if bool:
  67. answer = 1
  68. token = struct.pack('>hh', 2, answer)
  69. return token
  70. def get_password(user, host):
  71. # Right now we ignore the host component, as Mastodon doesn't store it for local accounts.
  72. # It may be required one day, so the code to handle passing it to the query is left in for now.
  73. cursor = database.cursor()
  74. cursor.execute(db_query_getpass, {"user": user.lower(), "host": host})
  75. data = cursor.fetchone()
  76. cursor.close()
  77. return data[0] if data != None else None
  78. def isuser(user, host):
  79. return get_password(user, host) != None
  80. def auth(user, host, password):
  81. db_password = get_password(user, host)
  82. if db_password == None:
  83. logging.debug("Wrong username: %s@%s" % (user, host))
  84. return False
  85. else:
  86. if bcrypt.checkpw(password.encode('utf8'), db_password.encode('utf8')):
  87. logging.debug("Validated %s against hash %s" % (user, db_password))
  88. return True
  89. else:
  90. logging.debug("Wrong password for user: %s@%s" % (user, host))
  91. return False
  92. ########################################################################
  93. #Main Loop
  94. ########################################################################
  95. exitcode=0
  96. while True:
  97. logging.debug("start of infinite loop")
  98. try:
  99. ejab_request = ejabberd_in().split(':', 3)
  100. except EOFError:
  101. break
  102. except Exception as e:
  103. logging.exception("Exception occured while reading stdin")
  104. raise
  105. op_result = False
  106. try:
  107. # Only 'auth' and 'isuser' implemented, placeholders left to maybe
  108. # expose other functions later but for now let's not even think about
  109. # modifying the Mastodon DB
  110. if ejab_request[0] == "auth":
  111. op_result = auth(ejab_request[1], ejab_request[2], ejab_request[3])
  112. elif ejab_request[0] == "isuser":
  113. op_result = isuser(ejab_request[1], ejab_request[2])
  114. elif ejab_request[0] == "setpass":
  115. op_result = False
  116. elif ejab_request[0] == "tryregister":
  117. op_result = False
  118. elif ejab_request[0] == "removeuser":
  119. op_result = False
  120. elif ejab_request[0] == "removeuser3":
  121. op_result = False
  122. except Exception:
  123. logging.exception("Exception occured")
  124. ejabberd_out(op_result)
  125. logging.info("successful" if op_result else "unsuccessful")
  126. logging.debug("end of infinite loop")
  127. logging.info('extauth script terminating')
  128. database.close()
  129. sys.exit(exitcode)