# Path: beeswarm/drones/honeypot/capabilities/http.py
# class Http(HandlerBase):
#     HandlerClass = BeeHTTPHandler
# 
#     def __init__(self, options, workdir):
#         super(Http, self).__init__(options, workdir)
#         self._options = options
# 
#     def handle_session(self, gsocket, address):
#         session = self.create_session(address)
#         try:
#             # The third argument ensures that the BeeHTTPHandler will access
#             # only the data in vfs/var/www
#             self.HandlerClass(gsocket, address, self.vfsystem.opendir('/var/www'), None, httpsession=session,
#                               options=self._options, users=self.users)
#         except socket.error as err:
#             logger.debug('Unexpected end of http session: {0}, errno: {1}. ({2})'.format(err, err.errno, session.id))
#         finally:
#             self.close_session(session)
# 
# class BeeHTTPHandler(BaseHTTPRequestHandler):
#     def __init__(self, request, client_address, vfs, server, httpsession, options, users):
# 
#         self.vfs = vfs
#         self.users = users
#         self.current_user = None  # This is set if a login attempt is successful
# 
#         # Had to call parent initializer later, because the methods used
#         # in BaseHTTPRequestHandler.__init__() call handle_one_request()
#         # which calls the do_* methods here. If _banner, _session and _options
#         # are not set, we get a bunch of errors (Undefined reference blah blah)
# 
#         self._options = options
#         if 'banner' in self._options:
#             self._banner = self._options['banner']
#         else:
#             self._banner = 'Microsoft-IIS/5.0'
#         self._session = httpsession
#         BaseHTTPRequestHandler.__init__(self, request, client_address, server)
#         self._session.end_session()
# 
#     def do_HEAD(self):
#         self.send_response(200)
#         self.send_header('Content-type', 'text/html')
#         self.end_headers()
# 
#     def do_AUTHHEAD(self):
#         self.send_response(401)
#         self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
#         self.send_header('Content-type', 'text/html')
#         self.end_headers()
# 
#     def do_GET(self):
#         if self.headers.getheader('Authorization') is None:
#             self.do_AUTHHEAD()
#             self.send_html('please_auth.html')
#         else:
#             hdr = self.headers.getheader('Authorization')
#             _, enc_uname_pwd = hdr.split(' ')
#             dec_uname_pwd = base64.b64decode(enc_uname_pwd)
#             uname, pwd = dec_uname_pwd.split(':')
#             if not self._session.try_auth('plaintext', username=uname, password=pwd):
#                 self.do_AUTHHEAD()
#                 self.send_html('please_auth.html')
#             else:
#                 self.do_HEAD()
#                 self.send_html('index.html')
#         self.request.close()
# 
#     def send_html(self, filename):
# 
#         file_ = self.vfs.open(filename)
#         send_whole_file(self.request.fileno(), file_.fileno())
#         file_.close()
# 
#     def version_string(self):
#         return self._banner
# 
#     # Disable logging provided by BaseHTTPServer
#     def log_message(self, format_, *args):
#         pass
# 
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
#     def __init__(self, options, workdir):
#         """
#         Base class that all capabilities must inherit from.
# 
#         :param sessions: a dictionary of Session objects.
#         :param options: a dictionary of configuration options.
#         :param workdir: the directory which contains files for this
#                         particular instance of Beeswarm
#         """
#         self.options = options
#         self.sessions = {}
#         if 'users' in options:
#             self.users = options['users']
#         else:
#             self.users = {}
#         # virtual file system shared by all capabilities
#         self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
#         # service port
#         self.port = int(options['port'])
# 
#     def create_session(self, address):
#         protocol = self.__class__.__name__.lower()
#         session = Session(address[0], address[1], protocol, self.users)
#         self.sessions[session.id] = session
#         session.destination_port = self.port
#         logger.debug(
#             'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
#                                                                           address[1], str(session.id)))
#         logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
#         return session
# 
#     def close_session(self, session):
#         logger.debug('Closing sessions')
#         session.end_session()
#         if session.id in self.sessions:
#             del self.sessions[session.id]
#         else:
#             assert False
# 
#     def handle_session(self, socket, address):
#         raise Exception('Do no call base class!')


import logging
from beeswarm.drones.honeypot.capabilities.http import Http, BeeHTTPHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.





logger = logging.getLogger(__name__)


class BeeHTTPSHandler(BeeHTTPHandler):
    """
        This class doesn't do anything about HTTPS, the difference is in the way the
        HTML body is sent. We need smaller chunks for HTTPS apparently.
    """

    def send_html(self, filename):
        with self.vfs.open(filename) as f:
            while True:
                chunk = f.read(1024)
                if not chunk:
                    break
                self.request.send(chunk)


class https(Http, HandlerBase):
    """
    This class will get wrapped in SSL. This is possible because we by convention wrap
    all capabilities that ends with the letter 's' in SSL."""


# Path: beeswarm/drones/honeypot/capabilities/http.py
# class Http(HandlerBase):
#     HandlerClass = BeeHTTPHandler
# 
#     def __init__(self, options, workdir):
#         super(Http, self).__init__(options, workdir)
#         self._options = options
# 
#     def handle_session(self, gsocket, address):
#         session = self.create_session(address)
#         try:
#             # The third argument ensures that the BeeHTTPHandler will access
#             # only the data in vfs/var/www
#             self.HandlerClass(gsocket, address, self.vfsystem.opendir('/var/www'), None, httpsession=session,
#                               options=self._options, users=self.users)
#         except socket.error as err:
#             logger.debug('Unexpected end of http session: {0}, errno: {1}. ({2})'.format(err, err.errno, session.id))
#         finally:
#             self.close_session(session)
# 
# class BeeHTTPHandler(BaseHTTPRequestHandler):
#     def __init__(self, request, client_address, vfs, server, httpsession, options, users):
# 
#         self.vfs = vfs
#         self.users = users
#         self.current_user = None  # This is set if a login attempt is successful
# 
#         # Had to call parent initializer later, because the methods used
#         # in BaseHTTPRequestHandler.__init__() call handle_one_request()
#         # which calls the do_* methods here. If _banner, _session and _options
#         # are not set, we get a bunch of errors (Undefined reference blah blah)
# 
#         self._options = options
#         if 'banner' in self._options:
#             self._banner = self._options['banner']
#         else:
#             self._banner = 'Microsoft-IIS/5.0'
#         self._session = httpsession
#         BaseHTTPRequestHandler.__init__(self, request, client_address, server)
#         self._session.end_session()
# 
#     def do_HEAD(self):
#         self.send_response(200)
#         self.send_header('Content-type', 'text/html')
#         self.end_headers()
# 
#     def do_AUTHHEAD(self):
#         self.send_response(401)
#         self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
#         self.send_header('Content-type', 'text/html')
#         self.end_headers()
# 
#     def do_GET(self):
#         if self.headers.getheader('Authorization') is None:
#             self.do_AUTHHEAD()
#             self.send_html('please_auth.html')
#         else:
#             hdr = self.headers.getheader('Authorization')
#             _, enc_uname_pwd = hdr.split(' ')
#             dec_uname_pwd = base64.b64decode(enc_uname_pwd)
#             uname, pwd = dec_uname_pwd.split(':')
#             if not self._session.try_auth('plaintext', username=uname, password=pwd):
#                 self.do_AUTHHEAD()
#                 self.send_html('please_auth.html')
#             else:
#                 self.do_HEAD()
#                 self.send_html('index.html')
#         self.request.close()
# 
#     def send_html(self, filename):
# 
#         file_ = self.vfs.open(filename)
#         send_whole_file(self.request.fileno(), file_.fileno())
#         file_.close()
# 
#     def version_string(self):
#         return self._banner
# 
#     # Disable logging provided by BaseHTTPServer
#     def log_message(self, format_, *args):
#         pass
# 
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
#     def __init__(self, options, workdir):
#         """
#         Base class that all capabilities must inherit from.
# 
#         :param sessions: a dictionary of Session objects.
#         :param options: a dictionary of configuration options.
#         :param workdir: the directory which contains files for this
#                         particular instance of Beeswarm
#         """
#         self.options = options
#         self.sessions = {}
#         if 'users' in options:
#             self.users = options['users']
#         else:
#             self.users = {}
#         # virtual file system shared by all capabilities
#         self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
#         # service port
#         self.port = int(options['port'])
# 
#     def create_session(self, address):
#         protocol = self.__class__.__name__.lower()
#         session = Session(address[0], address[1], protocol, self.users)
#         self.sessions[session.id] = session
#         session.destination_port = self.port
#         logger.debug(
#             'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
#                                                                           address[1], str(session.id)))
#         logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
#         return session
# 
#     def close_session(self, session):
#         logger.debug('Closing sessions')
#         session.end_session()
#         if session.id in self.sessions:
#             del self.sessions[session.id]
#         else:
#             assert False
# 
#     def handle_session(self, socket, address):
#         raise Exception('Do no call base class!')


# Path: beeswarm/drones/honeypot/capabilities/https.py
import logging
from beeswarm.drones.honeypot.capabilities.http import Http, BeeHTTPHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.





logger = logging.getLogger(__name__)


class BeeHTTPSHandler(BeeHTTPHandler):
    """
        This class doesn't do anything about HTTPS, the difference is in the way the
        HTML body is sent. We need smaller chunks for HTTPS apparently.
    """

    def send_html(self, filename):
        with self.vfs.open(filename) as f:
            while True:
                chunk = f.read(1024)
                if not chunk:
                    break
                self.request.send(chunk)


class https(Http, HandlerBase):
    """
    This class will get wrapped in SSL. This is possible because we by convention wrap
    all capabilities that ends with the letter 's' in SSL."""


    HandlerClass = BeeHTTPSHandler