-
Notifications
You must be signed in to change notification settings - Fork 47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for targetrc file to execute commands when a target shell is spawned #859
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a434c19
Add loading and executtion of rc file on cli init
twiggler a06173a
Add test to check if .targetrc file is processed
twiggler 386eacb
Refactor to make run commands file path a local variable.
twiggler 607a1a4
Make method for loading rc file private
twiggler d0e3cf2
Support loading of runcommand files in registry shell
twiggler 754b57e
Enhance abstraction by moving targetrc constant to subclass
twiggler afc3150
Rename constants
twiggler 5b96b70
Use union syntax instead of optional
twiggler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -19,7 +19,7 @@ | |||||
import sys | ||||||
from contextlib import contextmanager | ||||||
from datetime import datetime, timedelta, timezone | ||||||
from typing import Any, BinaryIO, Callable, Iterator, TextIO | ||||||
from typing import Any, BinaryIO, Callable, Iterator, Optional, TextIO | ||||||
|
||||||
from dissect.cstruct import hexdump | ||||||
from flow.record import RecordOutput | ||||||
|
@@ -96,6 +96,7 @@ | |||||
|
||||||
CMD_PREFIX = "cmd_" | ||||||
_runtime_aliases = {} | ||||||
DEFAULT_RUNCOMMANDS_FILE = None | ||||||
|
||||||
def __init__(self, cyber: bool = False): | ||||||
cmd.Cmd.__init__(self) | ||||||
|
@@ -121,6 +122,28 @@ | |||||
|
||||||
return object.__getattribute__(self, attr) | ||||||
|
||||||
def _load_targetrc(self, path: pathlib.Path) -> None: | ||||||
"""Load and execute commands from the run commands file.""" | ||||||
try: | ||||||
with path.open() as fh: | ||||||
for line in fh: | ||||||
if (line := line.strip()) and not line.startswith("#"): # Ignore empty lines and comments | ||||||
self.onecmd(line) | ||||||
except FileNotFoundError: | ||||||
# The .targetrc file is optional | ||||||
pass | ||||||
except Exception as e: | ||||||
log.debug("Error processing .targetrc file: %s", e) | ||||||
|
||||||
def _get_targetrc_path(self) -> Optional[pathlib.Path]: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
"""Get the path to the run commands file. Can return ``None`` if ``DEFAULT_RUNCOMMANDS_FILE`` is not set.""" | ||||||
return pathlib.Path(self.DEFAULT_RUNCOMMANDS_FILE).expanduser() if self.DEFAULT_RUNCOMMANDS_FILE else None | ||||||
|
||||||
def preloop(self) -> None: | ||||||
super().preloop() | ||||||
if targetrc_path := self._get_targetrc_path(): | ||||||
self._load_targetrc(targetrc_path) | ||||||
|
||||||
@staticmethod | ||||||
def check_compatible(target: Target) -> bool: | ||||||
return True | ||||||
|
@@ -309,6 +332,8 @@ | |||||
DEFAULT_HISTFILESIZE = 10_000 | ||||||
DEFAULT_HISTDIR = None | ||||||
DEFAULT_HISTDIRFMT = ".dissect_history_{uid}_{target}" | ||||||
DEFAULT_RUNCOMMANDS_FILE = "~/.targetrc" | ||||||
CONFIG_KEY_RUNCOMMANDS_FILE = "TARGETRCFILE" | ||||||
|
||||||
def __init__(self, target: Target): | ||||||
self.target = target | ||||||
|
@@ -338,7 +363,15 @@ | |||||
|
||||||
super().__init__(self.target.props.get("cyber")) | ||||||
|
||||||
def _get_targetrc_path(self) -> pathlib.Path: | ||||||
"""Get the path to the run commands file.""" | ||||||
|
||||||
return pathlib.Path( | ||||||
getattr(self.target._config, self.CONFIG_KEY_RUNCOMMANDS_FILE, self.DEFAULT_RUNCOMMANDS_FILE) | ||||||
).expanduser() | ||||||
|
||||||
def preloop(self) -> None: | ||||||
super().preloop() | ||||||
if readline and self.histfile.exists(): | ||||||
try: | ||||||
readline.read_history_file(self.histfile) | ||||||
|
@@ -507,7 +540,6 @@ | |||||
self.prompt_base = _target_name(target) | ||||||
|
||||||
TargetCmd.__init__(self, target) | ||||||
|
||||||
self._clicache = {} | ||||||
self.cwd = None | ||||||
self.chdir("/") | ||||||
|
@@ -1144,6 +1176,10 @@ | |||||
class RegistryCli(TargetCmd): | ||||||
"""CLI for browsing the registry.""" | ||||||
|
||||||
# Registry shell is incompatible with default shell, so override the default rc file and config key | ||||||
DEFAULT_RUNCOMMANDS_FILE = "~/.targetrc.registry" | ||||||
CONFIG_KEY_RUNCOMMANDS_FILE = "TARGETRCFILE_REGISTRY" | ||||||
|
||||||
def __init__(self, target: Target, registry: regutil.RegfHive | None = None): | ||||||
self.prompt_base = _target_name(target) | ||||||
|
||||||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.