Skip to content

Instantly share code, notes, and snippets.

@pacmac
Last active December 18, 2019 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pacmac/b3ca5d6b92fb8b6387d43d157b4e97c2 to your computer and use it in GitHub Desktop.
Save pacmac/b3ca5d6b92fb8b6387d43d157b4e97c2 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import SimpleHTTPServer
import SocketServer
from os import curdir, sep
import urllib
import subprocess
import time
import logging
logging.basicConfig(
filename='/var/log/dovecotpwd.log',
filemode='w',
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
PORT = 8000
PASSKEY = "12345"
FILEPATH = '/etc/dovecot/passwd'
PUBLIC = 'public'
## Read existing & parse new password
def dofile(email,passwd):
FDATA=[]
with open(FILEPATH) as fp:
line = fp.readline()
while line:
if len(line) > 20:
_email,_pwd = line.strip().split(':')
if _email != email:
FDATA.append(line.strip())
else:
FDATA.append('{}:{}'.format(email,passwd))
line = fp.readline()
return ("\n".join(FDATA))
def wrfile(data):
f = open(FILEPATH, "w")
f.write(data)
f.close()
return
def bash(cmd):
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
res, err = process.communicate()
if err: return err
else: return res
#Handler for the GET requests
class myHandler(BaseHTTPRequestHandler):
## html page
def page(self,path='index.html'):
mimetype = 'text/html'
f = open(curdir + sep + PUBLIC + sep + path)
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
def inline(self,code):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(code);
def do_GET(self):
self.path = urllib.unquote(self.path)
logging.info('path:{}'.format(self.path))
if '?' in self.path:
try:
bits = self.path.split('?')
if len(bits) == 2:
params = bits[1].split('&')
data = {
'email' : None,
'passwd' : None,
'passkey' : None
}
for i in params:
key,val = i.split('=')
if key in data: data[key] = val
## Dont Proceed if Wrong
if data['passkey'] != PASSKEY:
self.send_response(500)
return self.end_headers()
else:
cram = bash('/usr/bin/doveadm pw -s cram-md5 -u {} -p {}'.format(data['email'],data['passwd'])).strip()
res = dofile(data['email'],cram)
wrfile(res);
bash("service dovecot reload")
return self.page('/result.html')
except:
self.send_response(500)
return self.end_headers()
else:
try:
return self.page(self.path)
except:
self.send_response(404)
return self.end_headers()
return
while True:
try:
httpd = SocketServer.TCPServer(("", PORT), myHandler)
logging.info("Serving at port {}".format(PORT))
httpd.serve_forever()
except:
logging.info('Waiting for startup ...')
time.sleep(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment