#!/usr/bin/python

# vim:expandtab ts=4
# in order to use the embedded vim commands "set modeline" is required in your .vimrc file

import cgi
import cgitb
import os
import sqlite3
import crypt
import time
import base64
#cgitb.enable(display=0, logdir="/tmp")
import subprocess
import commands

try:
    import ticketing_cfg
    CFG_HOUR_BORDER=ticketing_cfg.cfg_hour_border
except:
    CFG_HOUR_BORDER=24975

"""
################
# page templates
################
"""

title = 'Barracuda CloudGen Firewall Ticketing'

loginpageerrorhtml="""
                <div id="errormessage">
                    <h1>Error</h1>
                    <p>%s</p>
                </div>

"""

loginpagehtml="""
<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        
        <title>%%TITLE%%</title>
        
        <meta name="description" content="%%TITLE%%" />
        <meta name="viewport" content="width=device-width" />
        
        <link rel="icon" href="/favicon.png" type="image/x-icon" />
        
        <link rel="stylesheet" href="/lp/lib/wifi.css?fwauthdlocal=yes"/>
        
        <script src="/lp/lib/modernizr-custom.js?fwauthdlocal=yes"></script>
    </head>
    <body>
        <!--[if lt IE 9]>
    <div class="browser-warning">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</div>
        <![endif]-->
    
        <div id="wrapper">
            <div id="login">
    
                <div id="header">
                    <img src="/lp/lib/barracuda-logo-header.png?fwauthdlocal=yes" alt="%%TITLE%%"/>
                </div>
    
                <form action="/lp/cgi-bin/ticketing" method="POST" >
    
                <div id="message">
                    <h1>%%TITLE%%</h1>
                    <p>Please login to manage Internet access tickets</p>
                </div>
    
                %s
                
                <div id="form">
    
                    <input 
                        type="text" 
                        name="user" 
                        size="20" 
                        placeholder="Username"
                        class="formfield"
                        autofocus required
                        accesskey="u"/>
                    <input 
                        type="password" 
                        name="password" 
                        size="20" 
                        placeholder="Password"
                        class="formfield"
                        required
                        autocomplete="off"
                        accesskey="p"/>
    
                    <input 
                        type="submit"
                        value="Login"/>
                </div>
    
                </form>
            </div>
        </div>
    
        <div id="branding"></div>
    </body>
</html>    
"""

ticketingpageheaderhtml="""
<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        
        <title>%%TITLE%%</title>
        
        <meta name="description" content="%%TITLE%%" />
        <meta name="viewport" content="width=device-width" />
        
        <link rel="icon" href="/favicon.png" type="image/x-icon" />
        
        <link rel="stylesheet" href="/lp/lib/wifi.css?fwauthdlocal=yes"/>
        <link rel="stylesheet" href="/lp/lib/ticketing.css?fwauthdlocal=yes"/>
        
        <script src="/lp/lib/modernizr-custom.js?fwauthdlocal=yes"></script>
    </head>
    <body>
        <!--[if lt IE 9]>
    <div class="browser-warning">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</div>
        <![endif]-->

        <div id="wrapper">
            <div id="ticketing">
                <noscript>
                <div class="warning">You need to enable JavaScript to use the ticketing manager</div>
                </noscript>

                <div id="header">
                    <a href="#top" title="Add ticket" class="add"><span>Add</span></a>
                    <img src="/lp/lib/barracuda-logo-header.png?fwauthdlocal=yes" alt="%%TITLE%%"/>
                    <div>%%TITLE%%</div>
                    <a href="/lp/cgi-bin/ticketing?logout&amp;commitid=%%COMMITID%%" title="Logout" class="logout"><span>Logout</span></a>
                </div>
    
                <form action="/lp/cgi-bin/ticketing" method="POST" >
                <input type="hidden" name="commitid" id="commitid" value="%%COMMITID%%" />
                <input type="hidden" name="type" id="type" value="save" />

                <div id="tickettable">
                    <table >
                        <thead>
                            <tr>
                                <th style="width:25%%">Username</th>
                                <th style="width:25%%">Ticket/Password</th>
                                <th style="width:10%%">Days</th>
                                <th style="width:10%%">Hours</th>
                                <th style="width:30%%">&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody>
"""

ticketingpageformbottomhtml="""
                        </tbody>
                    </table>
                </div>
    
                <div id="form">
                    <input 
                        type="submit"
                        value="Save Changes"/>
                </div>
    
                </form>
            </div>
        </div>
    
        <div id="branding"></div>
    
        <script src="/lp/lib/jquery-1.9.1.min.js?fwauthdlocal=yes"></script>
        <script type='text/javascript' >
        	window.hourBorder = %%CFG_HOUR_BORDER%%;
        </script>
        <script src="/lp/lib/ticketing.js?fwauthdlocal=yes"></script>
    
        <div id="printticket">
            <h1>Ticketing information</h1>
            <table>
                <tbody>
                    <tr>
                        <td>Username</td>
                        <td id="ticket-user"></td>
                    </tr>
                    <tr>
                        <td>Ticket</td>
                        <td id="ticket-ticket"></td>
                    </tr>
                    <tr>
                        <td>Validity</td>
                        <td id="ticket-validity"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>
"""

"""
##################
# required classes
##################
"""
class Tuple:
    def __init__(self):
        self.user=''
        self.ticket=''
        self.maxage=0

class RequestAnalysis:
    def __init__(self):
        self.user=''
        self.pwd=''
        self.peerip=''
        self.cookies={'TicketingAuth':''}
        self.isCommit=False
        self.commitIdSent=''
        self.isLogout=False

    def analyze(self, form, env):
        if form.has_key("user"): self.user=form["user"].value    
        if form.has_key("password"): self.pwd=form["password"].value    
        if form.has_key("type") and form["type"].value=="save":
            self.isCommit=True
        if form.has_key("commitid"):
            self.commitIdSent=form["commitid"].value

        if env.has_key('HTTP_COOKIE'):
            for cookie in env['HTTP_COOKIE'].split(';'):
                if cookie.find('=')<0: continue
                self.cookies[cookie[0:cookie.find('=')].strip()]=cookie[cookie.find('=')+1:].strip()
        if env.has_key('PEERIP'):
            self.peerip=env['PEERIP']

        if env.has_key('QUERY_STRING'):
            for n in env['QUERY_STRING'].split('&'):
                if n=='logout':
                    self.isLogout=True
                elif n[0:8]=='commitid' and len(n)>9:
                    self.commitIdSent=n[9:]

class Request:
    def __init__(self):
        self.cookie=''
        self.authtimeout=600
        self.form=None
        self.database='/var/phion/preserve/fwauthd/ticketing.db'
        self.isCommit=False
        self.commitId=''
        self.commitIdSent=''
        self.peerip=''
        self.msg=''
        self.isLogout=False

    def responseHeader(self, contentLength):
        #result='HTTP 1.1 200 OK\r\nContent-Type: text/html; charset=ISO-8859-1\r\nConnection: Close\r\nX-Frame-Options: SAMEORIGIN\r\n'
        #do not use status line. this is added in fwauthd automatically
        result='Content-Type: text/html; charset=ISO-8859-1\r\nConnection: Close\r\nContent-Length: %d\r\nX-Frame-Options: SAMEORIGIN\r\n' % contentLength
        if len(self.cookie)>0:
            result+='Set-Cookie: TicketingAuth=%s; HttpOnly\r\n' % self.cookie
        result+='\r'
        return result

    def createCookie(self):
        f=open('/dev/urandom')
        res=base64.b64encode(f.read(10))
        f.close()
        return res

    def checkDBVersion(self, db):
        cursor = db.cursor
        cursor = db.execute('PRAGMA user_version;')
        result=cursor.fetchone()
        if len(result)<1:
            db.execute('PRAGMA user_version=1;')
            db.commit()
            return
        if result[0]<2:
            db.execute('alter table cookies add column commitid varchar(256);')
            db.execute('PRAGMA user_version=2;')
            db.commit()

    def checkAuth(self, user, pwd, peerip, cookiesent):
        try:
            db=sqlite3.Connection(self.database)    
            # special character handling: db.text_factory = str
            db.text_factory = str
            cursor = db.cursor()

            self.checkDBVersion(db)

            authOK=False
            if len(cookiesent):
                cursor=db.execute('Select cookie, maxage, commitid from cookies where peerip=?;', (peerip,))
                for row in cursor:
                    if cookiesent==row[0] and int(time.time())<int(row[1]):
                        cursor.execute('update cookies set maxage=? where cookie=?;', (int(time.time()+self.authtimeout), cookiesent))
                        db.commit()
                        authOK=True
                        self.cookie=row[0]
                        self.commitId=row[2]
                        break;
            if not authOK and len(user)>0:
                user=user.replace('%', '')
                user=user.replace('\'', '')
                user=user.replace('*', '')
                cursor=db.execute('Select hash from auth where user=?;', (user,))
                for row in cursor:
                    if crypt.crypt(pwd, row[0])==row[0]:
                        self.cookie=self.createCookie()
                        self.commitId=self.createCookie() # commitId will be created as different cookie
                        cursor.execute('delete from cookies where maxage<?;', (int(time.time()),))
                        cursor.execute('insert or replace into cookies (peerip, cookie, commitid, maxage) values (?, ?, ?, ?);', (peerip, self.cookie, self.commitId, int(time.time())+self.authtimeout,))
                        db.commit()
                        db.close()
                        return True
                if len(user) and not authOK: self.msg='Login failed. Please try again'
            db.close()
            return authOK
                
        except sqlite3.OperationalError, e:
            self.msg=e.__str__()
            return False

    def loginPage(self, msg=''):
        if len(msg):
                content=loginpagehtml.replace('%%TITLE%%', title) % loginpageerrorhtml % msg
        else:
                content=loginpagehtml.replace('%%TITLE%%', title) % msg
        print self.responseHeader(len(content))
        print content


    def auth(self):
        self.form = cgi.FieldStorage()
        tr=RequestAnalysis()
        tr.analyze(self.form, os.environ)
        self.isCommit=tr.isCommit
        self.peerip=tr.peerip
        self.commitIdSent=tr.commitIdSent
        self.isLogout=tr.isLogout

        return self.checkAuth(tr.user, tr.pwd, tr.peerip, tr.cookies['TicketingAuth'])
    
    def showTickets(self):
        try:
            tickets=[]
            i=0
            db=sqlite3.Connection(self.database)    
            # special character handling: db.text_factory = str
            db.text_factory = str
            cursor = db.cursor()
            cursor=db.execute("select user, ticket, maxage from tickets where maxage>%d order by created;" % int(time.time()))
            for row in cursor:
                tickets.append((i,row[0], row[1], row[2]));
                i=i+1
            db.close()
        except sqlite3.OperationalError, e:
            return (False, '')
       
        content=''
        content+=ticketingpageheaderhtml.replace('%%TITLE%%', title).replace('%%COMMITID%%', self.commitId)+'\n'
        for ticket in tickets:
            content+='<TR data-ticket="%s">\n' % ticket[0]
            content+='    <TD>%s</TD>\n' % (htmlEncode(ticket[1]))
            content+='    <TD>%s</TD>\n' % (htmlEncode(ticket[2]))
            rest=int(ticket[3])-int(time.time())
            days = int(rest/86400)
            hours = int(int(rest%86400)/3600)
            if days > 999:
                hours += (days - 999) * 24
                days = 999
            content+='    <TD>%d</TD>\n' % (int(days))
            content+='    <TD>%d</TD>\n' % (int(hours))
            content+='</TR>\n'

        content+=ticketingpageformbottomhtml.replace('%%CFG_HOUR_BORDER%%', str(CFG_HOUR_BORDER))
        print self.responseHeader(len(content))
        print content

    def commitTickets(self):
        # check commit ID
        if self.commitId != self.commitIdSent:
            self.msg="Invalid (unauthorized) commit!"
            return False

        try:
            db=sqlite3.Connection(self.database)    
            # special character handling: db.text_factory = str
            db.text_factory = str
            tmp={}
            for n in sorted(self.form):
                if n[0:3]!='tkt': continue

                k=n[:-5]
                sb=n[-4:]
                if not tmp.has_key(k):
                    tmp[k]=Tuple()
                if sb=='0frm':
                    tmp[k].user=self.form[n].value
                elif sb=='1frm':
                    tmp[k].ticket=self.form[n].value
                elif sb=='2frm':
                    try:
                        tmp[k].maxage=int(time.time())+86400*int(self.form[n].value)
                    except ValueError,e:
                         tmp[k].maxage=int(time.time())+86400
                elif sb=='3frm':
                    try:
                        # add half an hour due to rounding
                        tmp[k].maxage+=3600*int(self.form[n].value)+1800
                    except ValueError,e:
                        pass
            
            cursor = db.cursor()
            cursor = db.execute("select user, created from tickets;")
            createdmap={}
            for row in cursor:
                createdmap[row[0]]=row[1]
            cursor.execute("delete from tickets;");
            for n in tmp:
                if createdmap.has_key(tmp[n].user):
                    cursor.execute("insert or replace into tickets (user, ticket, maxage, created) values (?, ?, ?, ?);", (tmp[n].user, tmp[n].ticket, tmp[n].maxage, createdmap[tmp[n].user],))
                else:
                    cursor.execute("insert or replace into tickets (user, ticket, maxage, created) values (?, ?, ?, ?);", (tmp[n].user, tmp[n].ticket, tmp[n].maxage, int(time.time()),))
            db.commit()
            db.close()
        except sqlite3.OperationalError, e:
            self.msg=e.__str__()
            return False

    def doLogout(self):
        # check commit ID
        if self.commitId != self.commitIdSent:
            self.msg="Invalid (unauthorized) logout: %s vs %s!" % (self.commitId, self.commitIdSent)
            return False

        try:
            db=sqlite3.Connection(self.database)    
            # special character handling: db.text_factory = str
            db.text_factory = str
            db.execute('delete from cookies where peerip=? and cookie=?;', (self.peerip, self.cookie,))
            db.commit()
            db.close()
            self.cookie=''
            self.commitId=''
            self.commitIdSent=''
        except sqlite3.OperationalError, e:
            pass

html_escape_table = {    
    ">": "&gt;",
    "<": "&lt;",
    }
            
def htmlEncode(text):
    return "".join(html_escape_table.get(c,c) for c in text)        

"""
#############
# the program
#############
"""
if __name__=="__main__":
    request=Request()
    result=request.auth()
    if not result:
        request.loginPage(request.msg)
    elif request.isLogout:
        request.doLogout()
        request.loginPage(request.msg)
    else:
        if request.isCommit:
            request.commitTickets()
            # search server for firewall module
            (ret1,out1)=commands.getstatusoutput('/opt/phion/bin/phionctrl module show firewall')
            if ((ret1 == 0) and (len(out1) > 0)):
                for n in out1.split('\n'):
                   haServer = n.split(' ')
                   if (haServer[0] == "server"):
                       subprocess.Popen(['/opt/phion/modules/box/boxsrv/dist/bin/dist2client', '-r', haServer[1], '-p', 'put', '-f', '/var/phion/preserve/fwauthd/ticketing.db'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
            # search server for cfirewall module
            (ret2,out2)=commands.getstatusoutput('/opt/phion/bin/phionctrl module show cfirewall')
            if ((ret2 == 0) and (len(out2) > 0)):
                for n in out2.split('\n'):
                   haServer = n.split(' ')
                   if (haServer[0] == "server"):
                       subprocess.Popen(['/opt/phion/modules/box/boxsrv/dist/bin/dist2client', '-r', haServer[1], '-p', 'put', '-f', '/var/phion/preserve/fwauthd/ticketing.db'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        request.showTickets()
        
