Skip to content

Commit

Permalink
Add FURB, SLF, RET to Ruff (EmpireProject#857)
Browse files Browse the repository at this point in the history
* update ruff

* fix after updating

* add RUF

* FURB

* SLF

* RET autofixes

* RET

* changelog

* run black

* fix noqa

* update ruff in ci

* check for pyenv 2.*
  • Loading branch information
vinnybod authored Jul 21, 2024
1 parent 872be88 commit 49050d1
Show file tree
Hide file tree
Showing 162 changed files with 925 additions and 1,075 deletions.
2 changes: 1 addition & 1 deletion .github/install_tests/cst-config-install-base.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ commandTests:
- name: "pyenv version"
command: "pyenv"
args: ["--version"]
expectedOutput: ["pyenv 2.3.*"]
expectedOutput: ["pyenv 2.*"]
# poetry
- name: "poetry python"
command: "poetry"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- uses: psf/[email protected]
- name: Run ruff
run: |
pip install ruff==0.5.0
pip install ruff==0.5.3
ruff check .
matrix-prep-config:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ repos:
- id: end-of-file-fixer

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.2.1
rev: v0.5.3
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Changed

- Updated Ruff to 0.5.3 and added additional Ruff rules (@Vinnybod)

### Fixed

- Removed duplicate code for ironpython agent for loading path resetting (@Cx01N)
- Fixed issue of Sharpire taskings not getting assigned correct id (@Cx01N)

Expand Down
6 changes: 3 additions & 3 deletions empire/client/src/utils/print_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,15 @@ def title(version, server, modules, listeners, agents):
"""
)
print(" " + color(str(modules), "green") + " modules currently loaded")
print("")
print()
print(
" "
+ color(str(listeners), "green")
+ " listeners currently active"
)
print("")
print()
print(" " + color(str(agents), "green") + " agents currently active")
print("")
print()
print(color("Starkiller is now the recommended way to use Empire.", "green"))
print(color(f"Try it out at {server}/index.html", "green"))

Expand Down
8 changes: 4 additions & 4 deletions empire/client/src/utils/table_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ def print_table(
table.inner_footing_row_border = False
table.inner_heading_row_border = False

print("")
print()
print(table.table)

if end_space:
print("")
print()


def print_agent_table(
Expand Down Expand Up @@ -86,6 +86,6 @@ def print_agent_table(
table.inner_footing_row_border = False
table.inner_heading_row_border = False

print("")
print()
print(table.table)
print("")
print()
3 changes: 1 addition & 2 deletions empire/server/api/jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None):
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)


async def get_current_user(
Expand Down
6 changes: 3 additions & 3 deletions empire/server/api/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if not scope.get("path", "").startswith("/socket.io"):
await super().__call__(scope, receive, send)
return
else:
await self.app(scope, receive, send)
return

await self.app(scope, receive, send)
return
14 changes: 7 additions & 7 deletions empire/server/api/v2/agent/agent_task_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,11 +560,11 @@ async def create_task_socks(
):
if is_port_in_use(socks.port):
raise HTTPException(status_code=400, detail="Socks port is in use")
else:
resp, err = agent_task_service.create_task_socks(
db, db_agent, socks.port, current_user.id
)
if err:
raise HTTPException(status_code=400, detail=err)

return domain_to_dto_task(resp)
resp, err = agent_task_service.create_task_socks(
db, db_agent, socks.port, current_user.id
)
if err:
raise HTTPException(status_code=400, detail=err)

return domain_to_dto_task(resp)
10 changes: 5 additions & 5 deletions empire/server/api/v2/listener/listener_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ async def update_listener(
raise HTTPException(status_code=400, detail=err)

return domain_to_dto_listener(resp)
elif listener_req.enabled and db_listener.enabled:
if listener_req.enabled and db_listener.enabled:
# err already running / cannot update
raise HTTPException(
status_code=400, detail="Listener must be disabled before modifying"
)
elif not listener_req.enabled and db_listener.enabled:
if not listener_req.enabled and db_listener.enabled:
# disable and update
listener_service.stop_listener(db_listener)
resp, err = listener_service.update_listener(db, db_listener, listener_req)
Expand All @@ -104,16 +104,16 @@ async def update_listener(
raise HTTPException(status_code=400, detail=err)

return domain_to_dto_listener(resp)
elif not listener_req.enabled and not db_listener.enabled:
if not listener_req.enabled and not db_listener.enabled:
# update
resp, err = listener_service.update_listener(db, db_listener, listener_req)

if err:
raise HTTPException(status_code=400, detail=err)

return domain_to_dto_listener(resp)
else:
raise HTTPException(status_code=500, detail="This Shouldn't Happen")

raise HTTPException(status_code=500, detail="This Shouldn't Happen")


@router.delete(
Expand Down
12 changes: 6 additions & 6 deletions empire/server/api/v2/shared_dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,16 @@ def to_value_type(value: Any, type: str = "") -> ValueType:
type = type or ""
if type.lower() == "file":
return ValueType.file
elif type.lower() in ["string", "str"] or isinstance(value, str):
if type.lower() in ["string", "str"] or isinstance(value, str):
return ValueType.string
elif type.lower() in ["boolean", "bool"] or isinstance(value, bool):
if type.lower() in ["boolean", "bool"] or isinstance(value, bool):
return ValueType.boolean
elif type.lower() == "float" or isinstance(value, float):
if type.lower() == "float" or isinstance(value, float):
return ValueType.float
elif type.lower() in ["integer", "int"] or isinstance(value, int):
if type.lower() in ["integer", "int"] or isinstance(value, int):
return ValueType.integer
else:
return ValueType.string

return ValueType.string


def to_string(value):
Expand Down
2 changes: 1 addition & 1 deletion empire/server/api/v2/websocket/socketio.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async def on_connect(sid, environ, auth):
user = await get_user_from_token(sid, auth["token"], db)
if user:
log.info(f"{user.username} connected to socketio")
return
return None
except HTTPException:
# If a server is restarted and clients are still connected, there are
# sometimes token handling errors. We want to reject these since they fail
Expand Down
88 changes: 35 additions & 53 deletions empire/server/common/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,19 +225,14 @@ def is_ip_allowed(self, ip_address):
"""
if self.ipBlackList:
if self.ipWhiteList:
results = (
return (
ip_address in self.ipWhiteList
and ip_address not in self.ipBlackList
)
return results
else:
results = ip_address not in self.ipBlackList
return results
return ip_address not in self.ipBlackList
if self.ipWhiteList:
results = ip_address in self.ipWhiteList
return results
else:
return True
return ip_address in self.ipWhiteList
return True

def save_file( # noqa: PLR0913
self,
Expand Down Expand Up @@ -371,7 +366,7 @@ def save_module_file(self, sessionID, path, data, language: str):
if not str(os.path.normpath(save_file)).startswith(str(safe_path)):
message = f"agent {sessionID} attempted skywalker exploit!\n[!] attempted overwrite of {path} with data {data}"
log.warning(message)
return
return None

# make the recursive directory structure if it doesn't already exist
if not save_path.exists():
Expand Down Expand Up @@ -444,9 +439,7 @@ def get_agents_db(self):
Return all active agents from the database.
"""
with SessionLocal() as db:
results = db.query(models.Agent).all()

return results
return db.query(models.Agent).all()

def get_agent_nonce_db(self, session_id, db: Session):
"""
Expand All @@ -467,8 +460,8 @@ def get_agent_nonce_db(self, session_id, db: Session):
if nonce and nonce is not None:
if isinstance(nonce, str):
return nonce
else:
return nonce[0]
return nonce[0]
return None

def get_language_db(self, session_id):
"""
Expand All @@ -486,14 +479,12 @@ def get_language_db(self, session_id):
if name_id:
session_id = name_id

language = (
return (
db.query(models.Agent.language)
.filter(models.Agent.session_id == session_id)
.scalar()
)

return language

def get_agent_id_db(self, name, db: Session = None):
"""
Get an agent sessionID based on the name.
Expand Down Expand Up @@ -553,9 +544,7 @@ def get_autoruns_db(self):
results = db.query(models.Config.autorun_data).all()
autorun_data = results[0].autorun_data if results[0].autorun_data else ""

autoruns = [autorun_command, autorun_data]

return autoruns
return [autorun_command, autorun_data]

def update_dir_list(self, session_id, response, db: Session):
""" "
Expand Down Expand Up @@ -753,22 +742,22 @@ def get_queued_agent_tasks_db(self, session_id, db: Session):
if session_id not in self.agents:
log.error(f"Agent {session_id} not active.")
return []
else:
try:
tasks, total = self.mainMenu.agenttasksv2.get_tasks(
db=db,
agents=[session_id],
include_full_input=True,
status=AgentTaskStatus.queued,
)

for task in tasks:
task.status = AgentTaskStatus.pulled
try:
tasks, total = self.mainMenu.agenttasksv2.get_tasks(
db=db,
agents=[session_id],
include_full_input=True,
status=AgentTaskStatus.queued,
)

for task in tasks:
task.status = AgentTaskStatus.pulled

return tasks
except AttributeError:
log.warning("Agent checkin during initialization.")
return []
return tasks
except AttributeError:
log.warning("Agent checkin during initialization.")
return []

def get_queued_agent_temporary_tasks(self, session_id):
"""
Expand All @@ -777,15 +766,11 @@ def get_queued_agent_temporary_tasks(self, session_id):
if session_id not in self.agents:
log.error(f"Agent {session_id} not active.")
return []
else:
try:
tasks = self.mainMenu.agenttasksv2.get_temporary_tasks_for_agent(
session_id
)
return tasks
except AttributeError:
log.warning("Agent checkin during initialization.")
return []
try:
return self.mainMenu.agenttasksv2.get_temporary_tasks_for_agent(session_id)
except AttributeError:
log.warning("Agent checkin during initialization.")
return []

###############################################################
#
Expand Down Expand Up @@ -816,7 +801,7 @@ def handle_agent_staging( # noqa: PLR0912 PLR0915 PLR0913 PLR0911
# step 1 of negotiation -> client requests staging code
return "STAGE0"

elif meta == "STAGE1":
if meta == "STAGE1":
# step 3 of negotiation -> client posts public key
message = f"Agent {sessionID} from {clientIP} posted public key"
log.info(message)
Expand Down Expand Up @@ -880,11 +865,9 @@ def handle_agent_staging( # noqa: PLR0912 PLR0915 PLR0913 PLR0911
data = data.encode("ascii", "ignore")

# step 4 of negotiation -> server returns RSA(nonce+AESsession))
encrypted_msg = encryption.rsa_encrypt(rsa_key, data)
return encryption.rsa_encrypt(rsa_key, data)
# TODO: wrap this in a routing packet!

return encrypted_msg

else:
message = f"Agent {sessionID} returned an invalid PowerShell public key!"
log.error(message)
Expand Down Expand Up @@ -942,11 +925,9 @@ def handle_agent_staging( # noqa: PLR0912 PLR0915 PLR0913 PLR0911

# step 4 of negotiation -> server returns HMAC(AESn(nonce+PUBs))
data = f"{nonce}{serverPub.publicKey}"
encrypted_msg = encryption.aes_encrypt_then_hmac(stagingKey, data)
return encryption.aes_encrypt_then_hmac(stagingKey, data)
# TODO: wrap this in a routing packet?

return encrypted_msg

else:
message = f"Agent {sessionID} from {clientIP} using an invalid language specification: {language}"
log.info(message)
Expand Down Expand Up @@ -1078,8 +1059,9 @@ def handle_agent_staging( # noqa: PLR0912 PLR0915 PLR0913 PLR0911
else:
message = f"Invalid staging request packet from {sessionID} at {clientIP} : {meta}"
log.error(message)
return None

def handle_agent_data( # noqa: PLR0913
def handle_agent_data(
self,
stagingKey,
routingPacket,
Expand Down Expand Up @@ -1294,7 +1276,7 @@ def handle_agent_response(self, sessionID, encData, update_lastseen=False):
log.error(message, exc_info=True)
return None

def process_agent_packet( # noqa: PLR0912 PLR0915 PLR0913
def process_agent_packet( # noqa: PLR0912 PLR0915
self, session_id, response_name, task_id, data, db: Session
):
"""
Expand Down
Loading

0 comments on commit 49050d1

Please sign in to comment.