Updated with comments and config file

This commit is contained in:
Tracker-Friendly 2023-11-19 11:30:01 +00:00
parent 8f3ef5a7f0
commit f44cdfa456
3 changed files with 64 additions and 12 deletions

70
app.py
View File

@ -6,37 +6,66 @@ import random
from captcha.image import ImageCaptcha from captcha.image import ImageCaptcha
from waitress import serve from waitress import serve
import base64 import base64
import configparser
import configparser
# Load from config.ini
config = configparser.ConfigParser()
config.read("config.ini")
secretkey = config.get("HectaMail", "secretkey")
captchachars = config.get("HectaMail", "captchachars")
# Status report
print("HectaMail is starting up...")
print("Your secret key is:", secretkey)
print("Your CAPTCHA allowed characters are:", captchachars)
# Define the allowed pattern for the username
allowed_pattern = r'^[a-zA-Z0-9.]+$' allowed_pattern = r'^[a-zA-Z0-9.]+$'
# Function to generate the CAPTCHA Code
def generate_captcha_text(): def generate_captcha_text():
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
captcha_text = ''.join(random.choice(characters) for i in range(6)) captcha_text = ''.join(random.choice(captchachars) for i in range(6))
return captcha_text return captcha_text
# Function to determine if the username is compilent with the regex filter
def is_valid_input(input_string): def is_valid_input(input_string):
return re.match(allowed_pattern, input_string) is not None return re.match(allowed_pattern, input_string) is not None
# Initalise Flask
app = Flask(__name__) app = Flask(__name__)
app.secret_key = "secret_key_here" app.secret_key = secretkey
# Function to create the email account, in this case using doas for security
def create_email_account(username, password): def create_email_account(username, password):
if password and is_valid_input(username): if password and is_valid_input(username):
try: try:
# Create a temporary file to escape the password
with open("tmp/password.tmp", "w") as file: with open("tmp/password.tmp", "w") as file:
file.write(password) file.write(password)
# Use echo to securely pass the password to the command # Pass the file through a shell command
cmd = ["cat", "tmp/password.tmp", "|", "doas", "-u", "maddy", "maddy", "creds", "create", f"{username}@hectabit.org"] cmd = ["cat", "tmp/password.tmp", "|", "doas", "-u", "maddy", "maddy", "creds", "create", f"{username}@hectabit.org"]
# Run and determine the result of the shell command
result = subprocess.run(" ".join(cmd), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = subprocess.run(" ".join(cmd), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cmd2 = ["doas", "-u", "maddy", "maddy", "imap-acct", "create", f"{username}@hectabit.org"] # Delete the temporary file
result2 = subprocess.run(" ".join(cmd2), shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
os.remove("tmp/password.tmp") os.remove("tmp/password.tmp")
if result.returncode == 0 and result2.returncode == 0:
# Check if command executed correctly
if result.returncode == 0:
# Command executed successfully # Command executed successfully
return True return True
else: else:
@ -49,40 +78,59 @@ def create_email_account(username, password):
print(f"Error creating email account: {str(e)}") print(f"Error creating email account: {str(e)}")
return False return False
else: else:
# Something went very wrong if this function triggers
print(f"Injection Bypass! Very bad!") print(f"Injection Bypass! Very bad!")
return False return False
@app.route('/') @app.route('/')
def index(): def index():
# Generate the CAPTCHA for the user
captcha_text = generate_captcha_text() captcha_text = generate_captcha_text()
image = ImageCaptcha().generate(captcha_text) image = ImageCaptcha().generate(captcha_text)
# Store the CAPTCHA in the session
session['captcha_text'] = captcha_text session['captcha_text'] = captcha_text
# Encode the image in base64
image_base64 = base64.b64encode(image.getvalue()).decode('utf-8') image_base64 = base64.b64encode(image.getvalue()).decode('utf-8')
# Report the CAPTCHA
print(captcha_text) print(captcha_text)
# Pass the CAPTCHA through to index.html
return render_template('index.html', captcha_text=captcha_text, captcha_image=image_base64) return render_template('index.html', captcha_text=captcha_text, captcha_image=image_base64)
@app.route('/api', methods=['POST']) @app.route('/api', methods=['POST'])
def register(): def register():
# Get the form data
username = request.form.get('username') username = request.form.get('username')
password = request.form.get('password') password = request.form.get('password')
# Get the CAPTCHA
user_captcha = request.form.get('captcha') user_captcha = request.form.get('captcha')
# Report the user captcha result
print(user_captcha) print(user_captcha)
if not is_valid_input(username) or not is_valid_input(user_captcha): # Check the regex filter
if not is_valid_input(username):
return render_template('num.html'), 400 return render_template('num.html'), 400
# Validate the captcha # Validate the captcha
captcha_text = session.get('captcha_text', '') captcha_text = session.get('captcha_text', '')
print(captcha_text) print(captcha_text)
if user_captcha.lower() != captcha_text.lower(): if user_captcha.lower() != captcha_text.lower():
# CAPTCHA incorrect
return render_template('captcha_err.html'), 400 return render_template('captcha_err.html'), 400
# Attempt to create the email
if create_email_account(username, password): if create_email_account(username, password):
# Email created
return render_template('ok.html') return render_template('ok.html')
else: else:
# Backend error, potentially maddy
return render_template('err.html'), 500 return render_template('err.html'), 500
# Start the web server
if __name__ == '__main__': if __name__ == '__main__':
serve(app, host='0.0.0.0', port=8050) serve(app, host='0.0.0.0', port=8050)

5
config.ini Normal file
View File

@ -0,0 +1,5 @@
[HectaMail]
# Secret Key, please change to something custom
secretkey: 'your_key_here'
# The characters you allow in your CAPTCHA
captchachars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

View File

@ -1 +0,0 @@
test