Example #1
0
def SendDataToYast(data):
    debug_logger.info('SendDataToYast: Waiting for YCP command')
    for line in sys.stdin:
        ycommand, ypath, yargument = ParseCommand(line)
        if ycommand and ycommand == 'Read':
            debug_logger.info('SendDataToYast: Sending--%s' % data)
            ycp.Return(data)
            return True
        else:
            debug_logger.info('SendDataToYast: Expected \'Read\' but got-- %s' % line)
    error('SendDataToYast: didn\'t receive YCP command before connection died')
Example #2
0
def GetDataFromYast():
    debug_logger.inf('GetDataFromYast: Waiting for YCP command')
    for line in sys.stdin:
        debug_logger.info('GetDataFromYast: YCP: %s' % line)
        ycommand, ypath, yarg = ParseCommand(line)
        debug_logger.info('GetDataFromYast: Recieved--\n%s' % yarg)
        if ycommand and ycommand == 'Write':
            ycp.Return('true')
            return ypath, yarg
        else:
            debug_logger.info('GetDataFromYast: Expected Write but got-- %s' % line)
    error('GetDataFromYast: didn\'t receive YCP command before connection died')
Example #3
0
def SendDataToYast(data):
    debug_logger.info('SendDataToYast: Waiting for YCP command')
    for line in sys.stdin:
        ycommand, ypath, yargument = ParseCommand(line)
        if ycommand and ycommand == 'Read':
            debug_logger.info('SendDataToYast: Sending--%s' % data)
            ycp.Return(data)
            return True
        else:
            debug_logger.info(
                'SendDataToYast: Expected \'Read\' but got-- %s' % line)
    error('SendDataToYast: didn\'t receive YCP command before connection died')
Example #4
0
def run_xsandbox(command, opt):
    '''Run X application in a sandbox'''
    old_cwd = os.getcwd()

    # first, start X
    if opt.xserver.lower() == "xephyr":
        x = SandboxXephyr(command[0],
                          geometry=opt.xephyr_geometry,
                          xauth=opt.xauthority)
    elif opt.xserver.lower() == "xpra3d":
        x = SandboxXpra(command[0],
                        geometry=None,
                        driver="xdummy",
                        xauth=opt.xauthority,
                        clipboard=opt.with_clipboard)
    else:
        x = SandboxXpra(command[0],
                        geometry=None,
                        xauth=opt.xauthority,
                        clipboard=opt.with_clipboard)

    x.verify_host_setup()

    # Debug: show old environment
    keys = x.old_environ.keys()
    keys.sort()
    for k in keys:
        debug("Old: %s=%s" % (k, x.old_environ[k]))

    try:
        x.start()
    except Exception as e:
        error(e)
    os.chdir(old_cwd)

    if not opt.read_path:
        opt.read_path = []
    opt.read_path.append(x.xauth)

    # Only used with dynamic profiles
    required_rules = ['audit deny @{HOME}/.Xauthority mrwlk,']

    # aa-exec
    try:
        rc, report = aa_exec(command, opt, x.new_environ, required_rules)
    except Exception:
        x.cleanup()
        raise
    x.cleanup()

    return rc, report
Example #5
0
def GetDataFromYast():
    debug_logger.inf('GetDataFromYast: Waiting for YCP command')
    for line in sys.stdin:
        debug_logger.info('GetDataFromYast: YCP: %s' % line)
        ycommand, ypath, yarg = ParseCommand(line)
        debug_logger.info('GetDataFromYast: Recieved--\n%s' % yarg)
        if ycommand and ycommand == 'Write':
            ycp.Return('true')
            return ypath, yarg
        else:
            debug_logger.info('GetDataFromYast: Expected Write but got-- %s' %
                              line)
    error(
        'GetDataFromYast: didn\'t receive YCP command before connection died')
Example #6
0
def run_xsandbox(command, opt):
    '''Run X application in a sandbox'''
    old_cwd = os.getcwd()

    # first, start X
    if opt.xserver.lower() == "xephyr":
        x = SandboxXephyr(command[0], geometry=opt.xephyr_geometry,
                                      xauth=opt.xauthority)
    elif opt.xserver.lower() == "xpra3d":
        x = SandboxXpra(command[0], geometry=None,
                                    driver="xdummy",
                                    xauth=opt.xauthority,
                                    clipboard=opt.with_clipboard)
    else:
        x = SandboxXpra(command[0], geometry=None,
                                    xauth=opt.xauthority,
                                    clipboard=opt.with_clipboard)

    x.verify_host_setup()

    # Debug: show old environment
    keys = x.old_environ.keys()
    keys.sort()
    for k in keys:
        debug ("Old: %s=%s" % (k, x.old_environ[k]))

    try:
        x.start()
    except Exception as e:
        error(e)
    os.chdir(old_cwd)

    if not opt.read_path:
        opt.read_path = []
    opt.read_path.append(x.xauth)

    # Only used with dynamic profiles
    required_rules = ['audit deny @{HOME}/.Xauthority mrwlk,']

    # aa-exec
    try:
        rc, report = aa_exec(command, opt, x.new_environ, required_rules)
    except Exception as e:
        x.cleanup()
        raise
    x.cleanup()

    return rc, report
Example #7
0
def check_requirements(binary):
    '''Verify necessary software is installed'''
    exes = ['xset',        # for detecting free X display
            'aa-easyprof', # for templates
            'aa-exec',     # for changing profile
            'sudo',        # eventually get rid of this
            'pkexec',      # eventually get rid of this
            binary]

    for e in exes:
        debug("Searching for '%s'" % e)
        rc, report = cmd(['which', e])
        if rc != 0:
            error("Could not find '%s'" % e, do_exit=False)
            return False

    return True
Example #8
0
def check_requirements(binary):
    '''Verify necessary software is installed'''
    exes = ['xset',        # for detecting free X display
            'aa-easyprof', # for templates
            'aa-exec',     # for changing profile
            'sudo',        # eventually get rid of this
            'pkexec',      # eventually get rid of this
            binary]

    for e in exes:
        debug("Searching for '%s'" % e)
        rc, report = cmd(['which', e])
        if rc != 0:
            error("Could not find '%s'" % e, do_exit=False)
            return False

    return True
Example #9
0
def parse_args(args=None, parser=None):
    '''Parse arguments'''
    if parser == None:
        parser = optparse.OptionParser()

    parser.add_option('-X', '--with-x',
                      dest='withx',
                      default=False,
                      help='Run in isolated X server',
                      action='store_true')
    parser.add_option('--with-xserver',
                      dest='xserver',
                      default='xpra',
                      help='Nested X server to use: xpra (default), xpra3d, xephyr')
    parser.add_option('--with-clipboard',
                      dest='with_clipboard',
                      default=False,
                      help='Allow clipboard access',
                      action='store_true')
    parser.add_option('--with-xauthority',
                      dest='xauthority',
                      default=None,
                      help='Specify Xauthority file to use')
    parser.add_option('-d', '--debug',
                      dest='debug',
                      default=False,
                      help='Show debug messages',
                      action='store_true')
    parser.add_option('--with-xephyr-geometry',
                      dest='xephyr_geometry',
                      default=None,
                      help='Geometry for Xephyr window')
    parser.add_option('--profile',
                      dest='profile',
                      default=None,
                      help='Specify an existing profile (see aa-status)')

    (my_opt, my_args) = parser.parse_args()
    if my_opt.debug:
        apparmor.common.DEBUGGING = True

    valid_xservers = ['xpra', 'xpra3d', 'xephyr']
    if my_opt.withx and my_opt.xserver.lower() not in valid_xservers:
            error("Invalid server '%s'. Use one of: %s" % (my_opt.xserver, \
                                                           ", ".join(valid_xservers)))

    if my_opt.withx:
        if my_opt.xephyr_geometry and my_opt.xserver.lower() != "xephyr":
            error("Invalid option --with-xephyr-geometry with '%s'" % my_opt.xserver)
        elif my_opt.with_clipboard and my_opt.xserver.lower() == "xephyr":
            error("Clipboard not supported with '%s'" % my_opt.xserver)

    if my_opt.template == "default":
        if my_opt.withx:
            my_opt.template = "sandbox-x"
        else:
            my_opt.template = "sandbox"

    return (my_opt, my_args)
Example #10
0
def parse_args(args=None, parser=None):
    '''Parse arguments'''
    if parser == None:
        parser = optparse.OptionParser()

    parser.add_option('-X', '--with-x',
                      dest='withx',
                      default=False,
                      help='Run in isolated X server',
                      action='store_true')
    parser.add_option('--with-xserver',
                      dest='xserver',
                      default='xpra',
                      help='Nested X server to use: xpra (default), xpra3d, xephyr')
    parser.add_option('--with-clipboard',
                      dest='with_clipboard',
                      default=False,
                      help='Allow clipboard access',
                      action='store_true')
    parser.add_option('--with-xauthority',
                      dest='xauthority',
                      default=None,
                      help='Specify Xauthority file to use')
    parser.add_option('-d', '--debug',
                      dest='debug',
                      default=False,
                      help='Show debug messages',
                      action='store_true')
    parser.add_option('--with-xephyr-geometry',
                      dest='xephyr_geometry',
                      default=None,
                      help='Geometry for Xephyr window')
    parser.add_option('--profile',
                      dest='profile',
                      default=None,
                      help='Specify an existing profile (see aa-status)')

    (my_opt, my_args) = parser.parse_args()
    if my_opt.debug:
        apparmor.common.DEBUGGING = True

    valid_xservers = ['xpra', 'xpra3d', 'xephyr']
    if my_opt.withx and my_opt.xserver.lower() not in valid_xservers:
            error("Invalid server '%s'. Use one of: %s" % (my_opt.xserver, \
                                                           ", ".join(valid_xservers)))

    if my_opt.withx:
        if my_opt.xephyr_geometry and my_opt.xserver.lower() != "xephyr":
            error("Invalid option --with-xephyr-geometry with '%s'" % my_opt.xserver)
        elif my_opt.with_clipboard and my_opt.xserver.lower() == "xephyr":
            error("Clipboard not supported with '%s'" % my_opt.xserver)

    if my_opt.template == "default":
        if my_opt.withx:
            my_opt.template = "sandbox-x"
        else:
            my_opt.template = "sandbox"

    return (my_opt, my_args)
Example #11
0
def handle_exception(*exc_info):
    '''Used as exception handler in the aa-* tools.
       For AppArmorException (used for profile syntax errors etc.), print only the exceptions
       value because a backtrace is superfluous and would confuse users.
       For other exceptions, print backtrace and save detailed information in a file in /tmp/
       (including variable content etc.) to make debugging easier.
    '''
    (ex_cls, ex, tb) = exc_info

    if ex_cls.__name__ == 'AppArmorException':  # I didn't find a way to get this working with isinstance() :-/
        print('', file=sys.stderr)
        error(ex.value)
    else:
        (fd, path) = tempfile.mkstemp(prefix='apparmor-bugreport-',
                                      suffix='.txt')
        file = os.fdopen(fd, 'w')
        #file = open_file_write(path)  # writes everything converted to utf8 - not sure if we want this...

        cgitb_hook = cgitb.Hook(display=1,
                                file=file,
                                format='text',
                                context=10)
        cgitb_hook.handle(exc_info)

        file.write(
            'Please consider reporting a bug at https://bugs.launchpad.net/apparmor/\n'
        )
        file.write('and attach this file.\n')

        print(''.join(traceback.format_exception(*exc_info)), file=sys.stderr)
        print('', file=sys.stderr)
        print('An unexpected error occoured!', file=sys.stderr)
        print('', file=sys.stderr)
        print('For details, see %s' % path, file=sys.stderr)
        print(
            'Please consider reporting a bug at https://bugs.launchpad.net/apparmor/',
            file=sys.stderr)
        print('and attach this file.', file=sys.stderr)
Example #12
0
    def start(self):
        debug("Searching for '%s'" % 'xpra')
        rc, report = cmd(['which', 'xpra'])
        if rc != 0:
            raise AppArmorException("Could not find '%s'" % 'xpra')

        if self.driver == "xdummy":
            # FIXME: is there a better way we can detect this?
            drv = "/usr/lib/xorg/modules/drivers/dummy_drv.so"
            debug("Searching for '%s'" % drv)
            if not os.path.exists(drv):
                raise AppArmorException("Could not find '%s'" % drv)
        '''Run any setup code'''
        SandboxXserver.start(self)

        xvfb_args = self._get_xvfb_args()
        listener_x = os.fork()
        if listener_x == 0:
            os.environ['XAUTHORITY'] = self.xauth

            # This will clean out any dead sessions
            cmd(['xpra', 'list'])

            x_args = [
                '--no-daemon',
                #'--no-mmap', # for security?
                '--no-pulseaudio'
            ]
            if not self.clipboard:
                x_args.append('--no-clipboard')

            if xvfb_args != '':
                x_args.append(" ".join(xvfb_args))

            args = ['/usr/bin/xpra', 'start', self.display] + x_args
            debug(" ".join(args))
            sys.stderr.flush()
            os.execv(args[0], args)
            sys.exit(0)
        self.pids.append(listener_x)

        started = False

        # We need to wait for the xpra socket to exist before attaching
        fn = os.path.join(os.environ['HOME'], '.xpra', '%s-%s' % \
                          (socket.gethostname(), self.display.split(':')[1]))
        for i in range(self.timeout *
                       2):  # up to self.timeout seconds to start
            if os.path.exists(fn):
                debug("Found '%s'! Proceeding to attach" % fn)
                break
            debug("'%s' doesn't exist yet, waiting" % fn)
            time.sleep(0.5)

        if not os.path.exists(fn):
            sys.stdout.flush()
            self.cleanup()
            raise AppArmorException("Could not start xpra (try again with -d)")

        for i in range(self.timeout):  # Up to self.timeout seconds to start
            rc, out = cmd(['xpra', 'list'])

            if 'DEAD session at %s' % self.display in out:
                error("xpra session at '%s' died" % self.display,
                      do_exit=False)
                break

            search = 'LIVE session at %s' % self.display
            if search in out:
                started = True
                break
            time.sleep(0.5)
            debug("Could not find '%s' in:\n" % search)
            debug(out)

        if not started:
            sys.stdout.flush()
            self.cleanup()
            raise AppArmorException("Could not start xpra (try again with -d)")

        # Next, attach to xpra
        sys.stdout.flush()
        os.chdir(os.environ["HOME"])
        listener_attach = os.fork()
        if listener_attach == 0:
            args = [
                '/usr/bin/xpra',
                'attach',
                self.display,
                '--title=%s' % self.generate_title(),
                #'--no-mmap', # for security?
                '--no-tray',
                '--no-pulseaudio'
            ]
            if not self.clipboard:
                args.append('--no-clipboard')

            debug(" ".join(args))
            sys.stderr.flush()
            os.execv(args[0], args)
            sys.exit(0)

        self.pids.append(listener_attach)

        # Make sure that a client has attached
        for i in range(self.timeout):  # up to self.timeout seconds to attach
            time.sleep(1)
            rc, out = cmd(['xpra', 'info', self.display])
            search = 'clients=1'
            if search in out:
                debug("Client successfully attached!")
                break
            debug("Could not find '%s' in:\n" % search)
            debug(out)

        msg("TODO: filter '~/.xpra/run-xpra'")
Example #13
0
    def start(self):
        debug("Searching for '%s'" % 'xpra')
        rc, report = cmd(['which', 'xpra'])
        if rc != 0:
            raise AppArmorException("Could not find '%s'" % 'xpra')

        if self.driver == "xdummy":
            # FIXME: is there a better way we can detect this?
            drv = "/usr/lib/xorg/modules/drivers/dummy_drv.so"
            debug("Searching for '%s'" % drv)
            if not os.path.exists(drv):
                raise AppArmorException("Could not find '%s'" % drv)

        '''Run any setup code'''
        SandboxXserver.start(self)

        xvfb_args = self._get_xvfb_args()
        listener_x = os.fork()
        if listener_x == 0:
            os.environ['XAUTHORITY'] = self.xauth

            # This will clean out any dead sessions
            cmd(['xpra', 'list'])

            x_args = ['--no-daemon',
                      #'--no-mmap', # for security?
                      '--no-pulseaudio']
            if not self.clipboard:
                x_args.append('--no-clipboard')

            if xvfb_args != '':
                x_args.append(" ".join(xvfb_args))

            args = ['/usr/bin/xpra', 'start', self.display] + x_args
            debug(" ".join(args))
            sys.stderr.flush()
            os.execv(args[0], args)
            sys.exit(0)
        self.pids.append(listener_x)

        started = False

        # We need to wait for the xpra socket to exist before attaching
        fn = os.path.join(os.environ['HOME'], '.xpra', '%s-%s' % \
                          (socket.gethostname(), self.display.split(':')[1]))
        for i in range(self.timeout * 2): # up to self.timeout seconds to start
            if os.path.exists(fn):
                debug("Found '%s'! Proceeding to attach" % fn)
                break
            debug("'%s' doesn't exist yet, waiting" % fn)
            time.sleep(0.5)

        if not os.path.exists(fn):
            sys.stdout.flush()
            self.cleanup()
            raise AppArmorException("Could not start xpra (try again with -d)")

        for i in range(self.timeout): # Up to self.timeout seconds to start
            rc, out = cmd(['xpra', 'list'])

            if 'DEAD session at %s' % self.display in out:
                error("xpra session at '%s' died" % self.display, do_exit=False)
                break

            search = 'LIVE session at %s' % self.display
            if search in out:
                started = True
                break
            time.sleep(0.5)
            debug("Could not find '%s' in:\n" % search)
            debug(out)

        if not started:
            sys.stdout.flush()
            self.cleanup()
            raise AppArmorException("Could not start xpra (try again with -d)")

        # Next, attach to xpra
        sys.stdout.flush()
        os.chdir(os.environ["HOME"])
        listener_attach = os.fork()
        if listener_attach == 0:
            args = ['/usr/bin/xpra', 'attach', self.display,
                                     '--title=%s' % self.generate_title(),
                                     #'--no-mmap', # for security?
                                     '--no-tray',
                                     '--no-pulseaudio']
            if not self.clipboard:
                args.append('--no-clipboard')

            debug(" ".join(args))
            sys.stderr.flush()
            os.execv(args[0], args)
            sys.exit(0)

        self.pids.append(listener_attach)

        # Make sure that a client has attached
        for i in range(self.timeout): # up to self.timeout seconds to attach
            time.sleep(1)
            rc, out = cmd (['xpra', 'info', self.display])
            search = 'clients=1'
            if search in out:
                debug("Client successfully attached!")
                break
            debug("Could not find '%s' in:\n" % search)
            debug(out)

        msg("TODO: filter '~/.xpra/run-xpra'")