'''
payloadTransferFactory.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

'''

import core.controllers.outputManager as om
from core.controllers.w3afException import *

from core.controllers.payloadTransfer.echoWin import echoWin
from core.controllers.payloadTransfer.echoLnx import echoLnx
from core.controllers.payloadTransfer.reverseFTP import reverseFTP
from core.controllers.payloadTransfer.clientlessReverseHTTP import clientlessReverseHTTP
from core.controllers.payloadTransfer.clientlessReverseTFTP import clientlessReverseTFTP

from core.controllers.intrusionTools.execMethodHelpers import *
from core.controllers.extrusionScanning.extrusionScanner import extrusionScanner


class payloadTransferFactory:
    '''
    This factory is pretty cool stuff, it uses an exec_method ( generated by os commanding, or some other vuln ) to determine
    what is the fastest method to send something to the compromised host. After determining what method to use, it will return
    the fastest method. 
    
    Transfers methods inherit from transfer factory and can be found in this directory. If you want to add a new method, you should
    create the file and add it to the to_test list that is defined in the first lines of this function.
    '''
    def __init__( self, exec_method ):
        self._exec_method = exec_method
        self._es = extrusionScanner( exec_method )

    def estimateTransferTime( self ):
        if self._es.canScan():
            return self._es.estimateScanTime() + 1
        else:
            return 1
        
    def getTransferHandler( self , inboundPort=None ):
        '''
        Perform an extrusion scan and return a handler that will know how to upload
        files to the remote end. If the caller sends an inboundPort, don't perform
        an extrusion scan, just trust him and use that port.
        
        @param inboundPort: The port that we should use for reverse connections
        @return: An object with a "transfer" method, which can be called by the user
        in order to upload files.
        '''
        os = osDetectionExec( self._exec_method )
        if os == 'windows':
            echoTransfer = echoWin( self._exec_method, os )
        elif os == 'linux':
            echoTransfer = echoLnx( self._exec_method, os )
            
        to_test = []
        to_test.append( echoTransfer )
        try:
            if not inboundPort:
                inboundPort = self._es.getInboundPort()
        except w3afException, w3:
            om.out.error( 'The extrusion test failed, no reverse connect transfer methods can be used. Trying inband echo transfer method.' )
            om.out.error( 'Error: ' + str(w3) )
        except Exception, e:
            om.out.error('Unhandled exception: ' + str(e) )
        else:
            to_test.append( reverseFTP( self._exec_method, os, inboundPort ) )
            if os == 'windows':
                to_test.append( clientlessReverseTFTP( self._exec_method, os, inboundPort ) )
            elif os == 'linux':
                to_test.append( clientlessReverseHTTP( self._exec_method, os, inboundPort ) )
            
            # Test the fastest first and return the fastest one...
            def sortFunction( x ,y ):
                return cmp( y.getSpeed() , x.getSpeed() )
            to_test.sort( sortFunction )
            
        for method in to_test:
            
            om.out.debug('Testing if "' + str(method) + '" is able to transfer a file to the compromised host.')
            if method.canTransfer():
                om.out.debug('The "' + str(method) + '" method is able to transfer a file to the compromised host.')
                return method
            else:
                om.out.debug('The "' + str(method) + '" method *FAILED* to transfer a file to the compromised host.')
        
        raise w3afException('Failed to transfer a file to the remote host! All the transfer methods failed.')
