예제 #1
0
파일: virtualbox.py 프로젝트: Gigia/cuckoo
    def __init__(self, vm_id = None):
        log = logging.getLogger("VirtualMachine")

        vbm = vboxapi.VirtualBoxManager(None, None)
        self.vbox = vbm.vbox
        self.mgr = vbm.mgr

        self.mach       = None
        self.name       = None
        self.username   = None
        self.password   = None
        self.mac        = None

        # If a virtual machine name is specified than open handle.
        if vm_id is not None:
            self.name = CuckooConfig().get_vm_name(vm_id)
            self.username = CuckooConfig().get_vm_username(vm_id)
            self.password = CuckooConfig().get_vm_password(vm_id)
        
            try:
                self.mach = self.vbox.findMachine(self.name)
                log.debug("Acquired virtual machine with name \"%s\"."
                          % self.name)
                
                # Acquire virtual machines' MAC address.
                mac_raw = self.mach.getNetworkAdapter(0).MACAddress
                mac_blocks = [mac_raw[x:x+2] for x in xrange(0, len(mac_raw), 2)]
                self.mac = ':'.join(mac_blocks)
            except Exception, why:
                log.error("Virtual machine \"%s\" not found: %s"
                          % (self.name, why))
예제 #2
0
def _get_object_session():
    ''' get new session to vm '''
    vbox, session = None, None
    try:
        vbox = vboxapi.VirtualBoxManager(None, None)
        session = vbox.mgr.getSessionObject(vbox.vbox)
    except Exception, err:
        pretty.print_error(__name__, 'virtualbox: get session error ', err)
예제 #3
0
 def __init__(self, mtype=None, mparams=None):
     pid = current_process().ident
     if _managers is None:
         raise RuntimeError(
             "Can not create a new manager following a system exit.")
     if pid not in _managers:
         with import_vboxapi() as vboxapi:
             self.manager = vboxapi.VirtualBoxManager(mtype, mparams)
예제 #4
0
def _get_existing_session(vm_uuid):
    ''' get existing session by machine uuid '''
    vbox, session = None, None
    try:
        vbox = vboxapi.VirtualBoxManager(None, None)
        session = vbox.mgr.getSessionObject(vbox.vbox)
    except Exception, err:
        pretty.print_error(__name__, 'virtualbox: get session error', vm_uuid,
                           err)
예제 #5
0
def _get_object_session():
    ''' get new session to vm '''
    pretty.print_debug(__name__, '_get_object_session start')
    vbox, session = None, None
    try:
        vbox = vboxapi.VirtualBoxManager(None, None)
        session = vbox.mgr.getSessionObject(vbox.vbox)
    except Exception as err:
        pretty.print_error(__name__, 'virtualbox: get session error ', err)
    pretty.print_debug(__name__, '_get_object_session finished', vbox, session)
    return vbox, session
예제 #6
0
def vb_get_manager():
    """
    Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
    @return:
    @rtype: VirtualBoxManager
    """
    global _virtualboxManager
    if _virtualboxManager is None and HAS_LIBS:
        salt.utils.compat.reload(vboxapi)
        _virtualboxManager = vboxapi.VirtualBoxManager(None, None)

    return _virtualboxManager
예제 #7
0
def vb_get_manager():
    '''
    Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
    @return:
    @rtype: VirtualBoxManager
    '''
    global _virtualboxManager
    if _virtualboxManager is None and HAS_LIBS:
        # Reloading the API extends sys.paths for subprocesses of multiprocessing, since they seem to share contexts
        reload(vboxapi)
        _virtualboxManager = vboxapi.VirtualBoxManager(None, None)

    return _virtualboxManager
예제 #8
0
def _get_existing_session(vm_uuid):
    ''' get existing session by machine uuid '''
    pretty.print_debug(__name__, '_get_existing_session start')
    vbox, session = None, None
    try:
        vbox = vboxapi.VirtualBoxManager(None, None)
        session = vbox.mgr.getSessionObject(vbox.vbox)
        vbox.vbox.openExistingSession(session, vm_uuid)
    except Exception as err:
        pretty.print_error(__name__, 'virtualbox: get session error', vm_uuid,
                           err)
    pretty.print_debug(__name__, '_get_existing_session finished', vbox,
                       session)
    return vbox, session
예제 #9
0
파일: __init__.py 프로젝트: maxfragg/pyvbox
    def manager(self):
        """Create a default Manager object
        
        Builds a singleton VirtualBoxManager object.

        Note: It is not necessary to build this object when defining a
        Session or VirtualBox object as both of these classes will default
        to this object's global singleton during construction. 
        """
        global _manager
        pid = current_process().ident
        if pid not in _manager:
            with _sys_path_scope():
                vboxapi = import_vboxapi()
                _manager[pid] = vboxapi.VirtualBoxManager(None, None)
        return _manager[pid]
예제 #10
0
	def init(self):
		vbm = vboxapi.VirtualBoxManager('XPCOM', None)
		
		self.ctx = {'global': vbm,
					'vb'	: vbm.vbox,
					'mgr'	: vbm.mgr,
					'const'	: vbm.constants,
					'guest'	: None} # console.guest unavailable until VM started
		try:
			self.mach = self.ctx['vb'].findMachine(self.vmname)
			self.uuid = self.mach.id
			logger.info('Using %s (uuid: %s)', self.vmname, self.uuid)
			return True
		except Exception as e:
			logger.exception('Cannot find registered machine: %s. Error: %s', self.vmname, e)
			return False
예제 #11
0
def select_vm(signal):
    window = gtk.Window()
    window.connect('destroy', lambda w: select_vm)
    window.set_title("SELECT VIRTUAL MACHINE")
    combobox = gtk.combo_box_new_text()
    window.add(combobox)
    virtualBoxManager = vboxapi.VirtualBoxManager(None, None)
    vbox = virtualBoxManager.vbox
    vboxVMList = virtualBoxManager.getArray(vbox, 'machines')
    vboxNameList = [mach.name for mach in vboxVMList]
    for i in vboxNameList:
        combobox.append_text(str(i))
    combobox.connect('changed', changed_cb)
    combobox.set_active(0)
    window.show_all()
    return
예제 #12
0
파일: __init__.py 프로젝트: maxfragg/pyvbox
    def __init__(self, url='http://localhost/', user='', password=''):
        """Create a VirtualBoxManager WEBSERVICE manager for IVirtualBox
        
        Options:
            url - url to connect with the VirtualBox server 
            user - username used to auth to the VirtualBox server service
            password - password used to auth to the VirtualBox server service

        Example:
            manager = WebServiceManager(user="******", password="******")
            vbox = VirtualBox(manager=manager)
            ...
        """
        with _sys_path_scope():
            vboxapi = import_vboxapi()
            params = (url, user, password)
            self.manager = vboxapi.VirtualBoxManager("WEBSERVICE", params)
예제 #13
0
def vb_get_manager():
    '''
    Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
    @return:
    @rtype: VirtualBoxManager
    '''
    global _virtualboxManager
    if _virtualboxManager is None and HAS_LIBS:
        try:
            from importlib import reload
        except ImportError:
            # If we get here, we are in py2 and reload is a built-in.
            pass

        # Reloading the API extends sys.paths for subprocesses of multiprocessing, since they seem to share contexts
        reload(vboxapi)
        _virtualboxManager = vboxapi.VirtualBoxManager(None, None)

    return _virtualboxManager
예제 #14
0
def vboxmerge(machine_name):
    '''
    Merge snapshots using global OPTIONS.
    '''
    vbm = vboxapi.VirtualBoxManager(None, None)
    vbox = vbm.vbox
    try:
        mach = vbox.findMachine(machine_name)
    except pywintypes.com_error:
        die('machine not found: %s' % machine_name)
    out('\nmachine: %s: %s\n', mach.name, mach.id)
    if mach.state != VBOX.MachineState_PoweredOff:
        die('machine must be powered off')
    session = vbm.mgr.getSessionObject(vbox)
    print dir(vbox)
    print 'session'
    print dir(session)
    vbox.openSession(session, mach.id)
    try:
        snap = mach.currentSnapshot
        if snap:

            if OPTIONS.discard_currentstate:
                out('\ndiscarding current machine state\n')
                runcmd(session.console.restoreSnapshot, snap)

            skip = int(OPTIONS.skip)
            count = int(OPTIONS.count)
            while snap:
                parent = snap.parent
                if skip <= 0 and count > 0:
                    out('\nmerging: %s: %s\n', snap.name, snap.id)
                    runcmd(session.console.deleteSnapshot, snap.id)

                    # The deleteSnapshot API sometimes silently skips snapshots
                    # so test to make sure the snapshot is no longer valid.
                    try:
                        snap.id
                    except pywintypes.com_error:
                        pass
                    else:
                        if not OPTIONS.dryrun:
                            die('%s: %s: more than one child VDI' %
                                (snap.name, snap.id))

                    count -= 1
                snap = parent
                skip -= 1
        else:
            out('no snapshots\n')

        if OPTIONS.snapshot:
            # Create a base snapshot.
            out('\ncreating base snapshot\n')
            runcmd(session.console.takeSnapshot, 'Base',
                   'Created by vboxmerge')

        if OPTIONS.compact:
            # Compact the base VDI.
            for attachment in mach.mediumAttachments:
                if attachment.type == VBOX.DeviceType_HardDisk:
                    base = attachment.medium.base
                    if base.type == VBOX.MediumType_Normal:
                        out('\ncompacting base VDI: %s\n', base.name)
                        runcmd(base.compact)
    finally:
        session.close()
예제 #15
0
def main():
    virtualBoxManager = vboxapi.VirtualBoxManager(None, None)
    machines = virtualBoxManager.getArray(virtualBoxManager.vbox, 'machines')
    for launcher in load():
        config = generate(launcher[0], machines)
        write(config, launcher)
예제 #16
0
파일: kylin.py 프로젝트: xmcp/kylinOJ
class Kylin:
    mgr = vboxapi.VirtualBoxManager()
    vbox = mgr.vbox

    def __init__(self, vm_name, log):
        self.log = log
        self.vm_name = vm_name
        self.log('=== initializing')
        self.vm = self.vbox.findMachine(vm_name)
        self.session = self.mgr.getSessionObject(self.vbox)
        self.running = False

    def __del__(self):
        if self.session.state != 1:
            wait(self.session.console.powerDown())

    def _boot(self):
        self.vm = self.vbox.findMachine(self.vm_name)
        self.session = self.mgr.getSessionObject(self.vbox)
        self.log('  === launching')
        while True:
            try:
                wait(
                    self.vm.launchVMProcess(
                        self.session, 'gui' if const.DEBUG else 'headless',
                        ''))
            except pywintypes.com_error:  #still unlocking machine
                time.sleep(.1)
            else:
                break
        self.log('  === waiting for gs')
        while True:
            try:
                result = self._execute('judge', const.VM_JUDGE_PSW,
                                       '/bin/echo', ['hello', 'world'], 2)
                assert result[0] == 0 and result[1].startswith(
                    'hello world') and not result[2]
            except (AssertionError, pywintypes.com_error):
                time.sleep(.1)
            else:
                break

    def _execute(self, user, passwd, program, args, timeout=15, stdin=None):
        def read_out():
            process.waitFor(7, 0)
            o = process.read(1, 65000, 0).tobytes().decode('utf-8', 'ignore')
            stdout.append(o)
            process.waitFor(8, 0)
            e = process.read(2, 65000, 0).tobytes().decode('utf-8', 'ignore')
            stderr.append(e)

        timeout *= 1000
        if self.session.state == 1:
            self.session = self.mgr.openMachineSession(self.vm)

        self.log('  === creating process')
        with closing(
                self.session.console.guest.createSession(
                    user, passwd, "", "kylinOJ execute session")) as gs:
            while gs.status != 100:
                time.sleep(.02)
            process = gs.processCreate(program, [program] + args, [], [16, 32],
                                       timeout)
            process.waitFor(1, 0)

            if stdin:
                self.log('  === writing stdin')
                process.waitFor(4, 0)
                index = 0
                while index < len(stdin):
                    array = list(map(lambda a: str(ord(a)), stdin[index:]))
                    wrote = process.writeArray(0, [0], array, 0)
                    if not wrote:
                        if process.status <= 100:
                            raise RuntimeError(
                                'Failed to write ANY bytes to STDIN')
                        else:  #terminated
                            break
                    index += wrote
                process.writeArray(0, [1], [], 0)

            self.log('  === executing')
            stdout, stderr = [], []
            while process.status <= 100:
                read_out()
                time.sleep(0.02)
            self.log('  === stopped')
            read_out()

            return process.exitCode, ''.join(stdout), ''.join(stderr)

    def _writefile(self, user, passwd, filename, content):
        if self.session.state == 1:
            self.session = self.mgr.openMachineSession(self.vm)

        self.log('  === initializing gs')
        with closing(
                self.session.console.guest.createSession(
                    user, passwd, "", "kylinOJ writefile session")) as gs:
            while gs.status != 100:
                time.sleep(.02)
            self.log('  === writing')
            with closing(gs.fileOpen(filename, 2, 4, 0x755)) as handler:
                handler.write(content.encode('utf-8', 'ignore'), 1000)

    def _readfile(self, user, passwd, filename):
        if self.session.state == 1:
            self.session = self.mgr.openMachineSession(self.vm)

        self.log('  === initializing gs')
        with closing(
                self.session.console.guest.createSession(
                    user, passwd, "", "kylinOJ writefile session")) as gs:
            while gs.status != 100:
                time.sleep(.02)
            self.log('  === reading')
            with closing(gs.fileOpen(filename, 1, 1, 0x755)) as handler:
                return handler.read(1024 * 1024, 1000).tobytes()

    def restore(self):
        def _pwn():
            self.log('  === writing judger')
            with open('vm_files/judger.cpp', 'r') as f:
                self._writefile(
                    'root', const.VM_ROOT_PSW, '/root/judger.cpp',
                    f.read().replace('/*JUDGE_UID*/', const.VM_JUDGE_UID))

            self.log('  === compiling judger')
            code, out, err = self._execute(
                'root', const.VM_ROOT_PSW, '/usr/bin/g++',
                ['-o', '/root/judger', '/root/judger.cpp'])
            if code:
                self.log('!!! errcode = %d' % code)
                self.log('[STDOUT]\n%s\n[STDERR]\n%s' % (out, err))

        if self.session.state != 1:
            self.log('=== powering down')
            wait(self.session.console.powerDown())
        while self.session.state != 1:
            time.sleep(.1)

        self.log('=== opening session')
        self.session = self.mgr.openMachineSession(self.vm)
        self.vm = self.session.machine
        self.log('=== restoring')
        wait(
            self.vm.restoreSnapshot(
                self.vm.findSnapshot(const.VM_BASE_SNAPSHOT)))
        wait(self.session.unlockMachine())

        self.log('=== powering up')
        while self.session.state != 1:
            time.sleep(.1)
        self._boot()
        _pwn()

    def _real_judge(self, source, memlimit, timelimit, datas,
                    callback):  #mem in mb
        results = []
        callback({'progress': 'init'})
        self.restore()
        try:
            self.log('=== copying user program')
            self._writefile('judge', const.VM_JUDGE_PSW,
                            '/home/judge/program.cpp', source)

            callback({'progress': 'compiling'})
            self.log('=== compiling')
            code, out, err = self._execute(
                'judge', const.VM_JUDGE_PSW, '/usr/bin/g++', [
                    '-static', '-o', '/home/judge/program',
                    '/home/judge/program.cpp'
                ])
            if code:
                self.log('!!! errcode = %d' % code)
                self.log('[STDOUT]\n%s\n[STDERR]\n%s' % (out, err))
                return callback({'progress': 'done', 'result': [Result.CE]})
        except Exception as e:
            self.log('!!! Uncaught Error: %r' % e)
            return callback({
                'progress': 'done',
                'result': results + [Result.SB]
            })

        len_datas = len(datas)
        for pos, io in enumerate(datas):
            try:
                callback({'progress': 'judging', 'result': results})
                self.log('=== judging data %d/%d' % (pos + 1, len_datas))

                code, out, err = self._execute(
                    'root', const.VM_ROOT_PSW, '/root/judger',
                    [(memlimit + 1) * 1024 * 1024, timelimit + 1],
                    timelimit + 2, io[0])
                if const.DEBUG:
                    self.log('[ERRCODE] %d\n[STDOUT]\n%s\n[STDERR]\n%s' %
                             (code, out, err))
                lim = self._readfile(
                    'root', const.VM_ROOT_PSW,
                    '/root/result.txt').decode(errors='ignore')
                _, runtime, *_ = lim.splitlines()
                self.log('=== user program completed in %sus' % runtime)

                if int(runtime) / 1000000 > timelimit:
                    results.append(Result.LE)
                elif code and err.startswith('[JUDGER ERROR] '):
                    results.append(Result.SB)
                elif code:
                    results.append(Result.RE)
                elif not out:
                    results.append(Result.WA)
                elif [x.rstrip() for x in out.rstrip().splitlines()
                      ] == [x.rstrip() for x in io[1].rstrip().splitlines()]:
                    results.append(Result.AC)
                elif out.replace(' ', '').replace('\n', '') == io[1].replace(
                        ' ', '').replace('\n', ''):
                    results.append(Result.PE)
                else:
                    results.append(Result.WA)
            except Exception as e:
                self.log('!!! Uncaught Error: %r' % e)
                return callback({
                    'progress': 'done',
                    'result': results + [Result.SB]
                })
        return callback({'progress': 'done', 'result': results})

    def judge(self, *args):
        def wrapper():
            self._real_judge(*args)
            self.running = False

        self.running = True
        threading.Thread(target=wrapper).start()
    except Exception as err:
        logging.exception(str(err))
    finally:
        debugger = session.console.debugger
        debugger.dumpGuestCore(
            normpath(join(dirname(__file__), 'gen/coredump')), '')
        if RESET_STATE:
            pdwn = session.machine.saveState()
            pdwn.waitForCompletion(-1)
            try:
                session.unlockMachine()
                call(['VBoxManage', 'snapshot', 'AMA', 'restore', 'Clean'])
            except Exception as err:
                pass
        else:
            session.unlockMachine()


if __name__ == "__main__":
    logging.basicConfig(format='%(levelname)s:\t%(message)s',
                        level=logging.DEBUG)
    virtualBoxManager = vboxapi.VirtualBoxManager(None, None)
    try:
        vbox = virtualBoxManager.getVirtualBox()
        todo = vbox.findMachine(MACH_NAME)
        proc(todo, virtualBoxManager, vbox)
    except Exception as err:
        logging.exception(str(err))

        # virtualBoxManager.closeMachineSession(session)
예제 #18
0
 def __init__(self, mtype=None, mparams=None):
     pid = current_process().ident
     if pid not in _manager:
         with import_vboxapi() as vboxapi:
             self.manager = vboxapi.VirtualBoxManager(mtype, mparams)
예제 #19
0
    def __getattr__(self, name):
        return self.labels[name]

    def __getitem__(self, value):
        return self.values[value]

    def __str__(self):
        return "Enum(labels: %r)" % self.labels

    __repr__ = __str__


try:
    import vboxapi
    VBM = vboxapi.VirtualBoxManager()
    VB = VBM.getVirtualBox()
    MachineState = Enum(VBM.constants.all_values('MachineState'))
    AutostopType = Enum(VBM.constants.all_values('AutostopType'))
    LockType = Enum(VBM.constants.all_values('LockType'))
    OffMachineStates = (
        MachineState.PoweredOff,
        MachineState.Saved,
        MachineState.Teleported,
        MachineState.Aborted,
    )
except ImportError:
    vboxapi = None

    class VB:
        class Machine: