def __call__(self, value, *args, **kwargs): if os.name == 'posix' and hasattr(self.mod.dotransform, 'privileged') and os.geteuid(): print highlight("Need to be root to run this transform... sudo'ing...", 'green', True) os.execvp('sudo', self.sudoargs) return local_transform_runner(self.mod, value, kwargs, list(args), config, message_writer=console_message)
def list_transforms(args): # TODO: project_tree may raise an exception if either project_root can't be # determined or if we can't find the package as an installed package. # Atleast the create-transform command calls this function without handling # the possible exception. What is the best sollution? # TODO: create-transform takes an argument --transform-dir which can be used # to control where to place the transform template. This breaks the new # assumption of the 'transforms' folder always being inside the 'pkg' # folder. However this is an assumption all over the place, so this # parameter doesn't really make much sense? # TODO: There are most likely many commands with similar problems # (above). and perhaps they should be updated to use the below template and # have their argument updated to -d/--dir instead with CWD as the default # value. # TODO: Perhaps we should introduce a 'create' command that will just make # an empty canari root dir (project). Inside this we can then call # create-package a number of times to generate all the desired # packages. This could even be automated for N-times during the call to # 'create'. 'create-package' can even still default to call 'create' if not # inside a canari root directory, to preserve backwards compatability. # TODO: Handle hyphening of package names. When creating them and when # trying to access them. This goes for project_tree, it should change '-' # with '_' in the package name. try: with pushd(args.dir): opts = parse_args(args) with pushd(args.ptree['src']): transform_package = TransformDistribution(opts.package) for t in transform_package.transforms: print('`- %s: %s' % (highlight( t.__name__, 'green', True), t.dotransform.description)) print(highlight(' `- Maltego identifiers:', 'black', True)) for uuid, (input_set, input_type) in zip(t.dotransform.uuids, t.dotransform.inputs): print ' `- %s applies to %s in set %s' % ( highlight(uuid, 'red', False), highlight(input_type._type_, 'red', False), highlight(input_set, 'red', False)) print '' except ValueError, e: print str(e) exit(-1)
def list_transforms(args): # TODO: project_tree may raise an exception if either project_root can't be # determined or if we can't find the package as an installed package. # Atleast the create-transform command calls this function without handling # the possible exception. What is the best sollution? # TODO: create-transform takes an argument --transform-dir which can be used # to control where to place the transform template. This breaks the new # assumption of the 'transforms' folder always being inside the 'pkg' # folder. However this is an assumption all over the place, so this # parameter doesn't really make much sense? # TODO: There are most likely many commands with similar problems # (above). and perhaps they should be updated to use the below template and # have their argument updated to -d/--dir instead with CWD as the default # value. # TODO: Perhaps we should introduce a 'create' command that will just make # an empty canari root dir (project). Inside this we can then call # create-package a number of times to generate all the desired # packages. This could even be automated for N-times during the call to # 'create'. 'create-package' can even still default to call 'create' if not # inside a canari root directory, to preserve backwards compatability. # TODO: Handle hyphening of package names. When creating them and when # trying to access them. This goes for project_tree, it should change '-' # with '_' in the package name. try: with pushd(args.dir): opts = parse_args(args) with pushd(args.ptree['src']): transform_package = TransformDistribution(opts.package) for t in transform_package.transforms: print ('`- %s: %s' % (highlight(t.__name__, 'green', True), t.dotransform.description)) print (highlight(' `- Maltego identifiers:', 'black', True)) for uuid, (input_set, input_type) in zip(t.dotransform.uuids, t.dotransform.inputs): print ' `- %s applies to %s in set %s' % ( highlight(uuid, 'red', False), highlight(input_type._type_, 'red', False), highlight(input_set, 'red', False) ) print '' except ValueError, e: print str(e) exit(-1)
def __call__(self, value, *args, **kwargs): if os.name == 'posix' and hasattr(self.mod.dotransform, 'privileged') and os.geteuid(): print highlight( "Need to be root to run this transform... sudo'ing...", 'green', True) os.execvp('sudo', self.sudoargs) return local_transform_runner(self.mod, value, kwargs, list(args), config, message_writer=console_message)
def console_message(msg, tab=-1): """ Internal API: Returns a prettified tree-based output of an XML message for debugging purposes. This helper function is used by the debug-transform command. """ tab += 1 if isinstance(msg, Model): msg = fromstring(msg.render(fragment=True)) print('%s`- %s: %s %s' % ( ' ' * tab, highlight(msg.tag, None, True), highlight(msg.text, 'red', False) if msg.text is not None else '', highlight(msg.attrib, 'green', True) if msg.attrib.keys() else '' )) for c in msg.getchildren(): print(' %s`- %s: %s %s' % ( ' ' * tab, highlight(c.tag, None, True), highlight(c.text, 'red', False) if c.text is not None else '', highlight(c.attrib, 'green', True) if c.attrib.keys() else '' )) for sc in c.getchildren(): tab += 1 console_message(sc, tab) tab -= 1
def shell(opts): fix_binpath(config['default/path']) fix_pypath() if not opts.package.endswith('transforms'): opts.package = '%s.transforms' % opts.package try: t = TransformDistribution(opts.package) with pushd(opts.working_dir or t.default_prefix): mtg_console = MtgConsole(opts.package) mtg_console.interact(highlight('Welcome to Canari %s.' % canari.__version__, 'green', True)) except ValueError, e: print str(e) exit(-1)
def shell(opts): fix_binpath(config['default/path']) fix_pypath() if not opts.package.endswith('transforms'): opts.package = '%s.transforms' % opts.package try: t = TransformDistribution(opts.package) with pushd(opts.working_dir or t.default_prefix): mtg_console = MtgConsole(opts.package) mtg_console.interact( highlight('Welcome to Canari %s.' % canari.__version__, 'green', True)) except ValueError, e: print str(e) exit(-1)
def console_message(msg, tab=-1): """ Internal API: Returns a prettified tree-based output of an XML message for debugging purposes. This helper function is used by the debug-transform command. """ tab += 1 if isinstance(msg, Model): msg = fromstring(msg.render(fragment=True)) print('%s`- %s: %s %s' % (' ' * tab, highlight(msg.tag, None, True), highlight(msg.text, 'red', False) if msg.text is not None else '', highlight(msg.attrib, 'green', True) if msg.attrib.keys() else '')) for c in msg.getchildren(): print(' %s`- %s: %s %s' % (' ' * tab, highlight(c.tag, None, True), highlight(c.text, 'red', False) if c.text is not None else '', highlight(c.attrib, 'green', True) if c.attrib.keys() else '')) for sc in c.getchildren(): tab += 1 console_message(sc, tab) tab -= 1
def project_tree(package=None): """Returns a dict of the project tree. Will try and look for local/source packages first, and if it fails to find a valid project root, it will look for system installed packages instead. Returns a dictionary with the following fields: - root: Path of the canari root folder or None if not applicable. - src: Path of the folder containing the package. - pkg: Path of the actual package. - pkg_name: Name of the package, which details are returned about. - resources: Path of the resources folder inside the package. - transforms: Path of the transforms folder inside the package. """ # Default values for the returned fields. tree = dict( root=None, src=None, pkg=None, pkg_name=None, resources=None, transforms=None, ) try: root = project_root() # TODO: The 'src' folder is currently harcoded inside setup.py. People # may change this and thus we should probably read this value from # '.canari', so the user may change this freely. # Using find_packages we don't risk having to deal with the *.egg-info # folder and trying to make a best guess at what folder is a actual # source code, tests, or something else. packages = filter(lambda pkg: pkg.find('.') < 0, find_packages('src')) if package is None and len(packages) == 1: # No package was specified by the user and there is only one # possibility, so silently choose that one. package = packages[0] elif package not in packages: # The supplied package was not found or not specified (None). List # the found packages and make the user choose the correct one. if package is not None: print "{warning} You specified a specific transform package, but " \ "it does {_not_} exist inside this canari source directory. " \ "\nPerhaps you ment to refer to an already installed package?\n" \ .format(warning = highlight('[warning]', 'red', False), _not_= highlight('not', None, True)) print "The possible transform packages inside this canari root directory are:" print 'Root dir: %s' % root n = parse_int('Choose a package', packages, default=0) package = packages[n] #else: the user supplied package name is already a valid one, and the #one the user picked.. so all is good. assert package is not None, 'Fatal error: No package has been found or choosen!' # Update the tree dict with all relevant information for this source package tree['root'] = root # Again 'src' is hardcooded in setup.py tree['src'] = os.path.join(tree['root'], 'src') tree['pkg'] = os.path.join(tree['src'], package) except ValueError as ve: # If we can't locate the project root, then we are not within a (source) # canari project folder and thus we will try and look for installed # packages instead. for module_importer, name, ispkg in iter_modules(): # module_importer is most likely a pkgutils.ImpImporter instance (or # the like) that has been initialised with a path that matches the # (egg) install directory of the current module being iterated. # Thus any calls to functions (e.g., find_module) on this instance # will be limited to that path (i.e., you can't load arbitrary # packages from it). if name == package: # Installed packages, don't have a (canari) 'root' folder. # However it seems that (atleast) installed eggs have a form of # 'src' folder named #pkg_name#-#pkg_version#-#py_version#.egg. # This folder (generally) contains two folders: #pkg_name# and # EGG-INFO tree['src'] = module_importer.path tree['pkg'] = module_importer.find_module(package).filename break # No need to keep searching. if tree['src'] is None: # We didn't find the user supplied package name in the list of # installed packages. raise ValueError("You are not inside a canari root directory ('%s'), " "and it was not possible to locate " "the given package " "'%s' among the list of installed packages." % (os.getcwd(), package)) tree['pkg_name'] = package # A transform packages structure is expected to have a 'pkg_name.resources' # and 'pkg_name.transforms', thus we won't dynamically look for these as # everything else will break, if they can't be imported as such. # TODO: Here be dragons. Does python3 module madness break this assumption # with its new fancy features of ways to have modules not nessesarily # stricly tied to the file system? tree['resources'] = os.path.join(tree['pkg'], 'resources') tree['transforms'] = os.path.join(tree['pkg'], 'transforms') return tree
def list_commands(opts): cmds = canari_main.subparsers.choices k = cmds.keys() k.sort() for i in k: print('%s - %s' % (highlight(i, 'green', True), cmds[i].description))
def list_commands(opts): cmds = canari_main.subparsers.choices k = cmds.keys() k.sort() for i in k: print ('%s - %s' % (highlight(i, 'green', True), cmds[i].description))