Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions core/database_arango.py
Original file line number Diff line number Diff line change
Expand Up @@ -1761,11 +1761,20 @@ def _get_collection(cls):
return "all_objects_view"


def tagged_observables_export(cls, args):
aql = """
def tagged_observables_export(cls, args, user: "user.User | None" = None):
aql_args = dict(args)
with_clause = ""
acl_clause = ""
if user and RBAC_ENABLED and not user.admin:
with_clause = "WITH acls, users, groups\n"
acl_clause = f"FILTER {_acl_read_subquery('o')}\n"
aql_args["username"] = user.username
aql = f"""
{with_clause}
FOR o in observables
FILTER (o.type IN @acts_on OR @acts_on == [])
FILTER o.tags != []
{acl_clause}
LET freshtags = (
FOR t IN o.tags
FILTER t.name NOT IN @ignore
Expand All @@ -1777,7 +1786,7 @@ def tagged_observables_export(cls, args):
FILTER COUNT(INTERSECTION(freshtags, @exclude)) == 0
RETURN o
"""
documents = db.aql.execute(aql, bind_vars=args, count=True, full_count=True)
documents = db.aql.execute(aql, bind_vars=aql_args, count=True, full_count=True)
results = []
for doc in documents:
doc["__id"] = doc.pop("_key")
Expand Down
2 changes: 1 addition & 1 deletion core/schemas/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def load(cls, object: dict):

@classmethod
def has_permissions(
cls, user, target_id: str, permission: roles.Permission
cls, user, target_id: str, permission: roles.Permission | roles.Role
) -> bool:
acl_acl = """
WITH observables, entities, dfiq, indicators
Expand Down
11 changes: 9 additions & 2 deletions core/schemas/indicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
from core.helpers import now
from core.schemas.model import YetiAclModel, YetiContextModel, YetiTagModel

if TYPE_CHECKING:
from core.schemas import user as user_schema


def future():
return datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
Expand Down Expand Up @@ -100,9 +103,13 @@ def match(self, value: str) -> Any | None:

@classmethod
def search(
cls, observables: list[str]
cls, observables: list[str], user: "user_schema.User | None" = None
) -> Generator[tuple[str, "Indicator"], None, None]:
indicators = list(cls.list())
if user is not None:
query = {"type__in": [cls._type_filter]} if cls._type_filter else {}
indicators, _ = cls.filter(query, wildcard=False, user=user)
else:
indicators = list(cls.list())
for observable in observables:
for indicator in indicators:
try:
Expand Down
34 changes: 28 additions & 6 deletions core/schemas/indicators/yara.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import ClassVar, Literal
from typing import TYPE_CHECKING, ClassVar, Literal

import plyara
import plyara.exceptions
Expand All @@ -8,7 +8,10 @@
from pydantic import BaseModel, PrivateAttr, model_validator

from core import errors
from core.schemas import indicator
from core.schemas import indicator, rbac, roles

if TYPE_CHECKING:
from core.schemas import user as user_schema

ALLOWED_EXTERNALS = {
"filename": "",
Expand Down Expand Up @@ -255,7 +258,10 @@ def import_bulk_rules(cls, bulk_rule_text: str, tags: list[str] | None = None):
yara_object.tag(tags + rule_tags)

def rule_with_dependencies(
self, resolved: set[str] | None = None, seen: set[str] | None = None
self,
resolved: set[str] | None = None,
seen: set[str] | None = None,
user: "user_schema.User | None" = None,
) -> str:
"""
Find dependencies in a Yara rule.
Expand Down Expand Up @@ -284,7 +290,20 @@ def rule_with_dependencies(
dep_rule = Yara.find(name=dependency)
if not dep_rule:
raise ValueError(f"Rule depends on unknown dependency '{dependency}'")
concatenated_rules += dep_rule.rule_with_dependencies(resolved, seen)
if (
user
and rbac.RBAC_ENABLED
and not user.admin
and not user.has_permissions(
dep_rule.extended_id, roles.Permission.READ
)
):
raise PermissionError(
f"Forbidden: missing privileges {roles.Permission.READ} on dependency '{dependency}'"
)
concatenated_rules += dep_rule.rule_with_dependencies(
resolved, seen, user=user
)

if self.name not in resolved:
concatenated_rules += self.pattern + "\n\n"
Expand Down Expand Up @@ -351,17 +370,20 @@ def apply_overlays_plyara(
return self

@classmethod
def generate_yara_bundle(cls, rules: list["Yara"]) -> str:
def generate_yara_bundle(
cls, rules: list["Yara"], user: "user_schema.User | None" = None
) -> str:
"""Export a list of Yara rules to a single string.

Args:
rules: A list of Yara rules to export.
user: Optional user whose READ permissions are checked on dependencies.

Returns:
A string containing the exported rules.
"""
resolved: set[str] = set()
bulk_rules = ""
for rule in rules:
bulk_rules += rule.rule_with_dependencies(resolved)
bulk_rules += rule.rule_with_dependencies(resolved, user=user)
return bulk_rules
2 changes: 1 addition & 1 deletion core/schemas/rbac.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def root_type(self):
# wrapper would drag every decorated route (and its blocking calls) onto the
# loop and serialize the whole server. Nothing in the wrappers awaits.
def require_permission(
user: "user.User", extended_id: str, permission: roles.Permission
user: "user.User", extended_id: str, permission: roles.Permission | roles.Role
) -> None:
if not RBAC_ENABLED or user.admin:
return
Expand Down
30 changes: 22 additions & 8 deletions core/schemas/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ class ExportTask(Task):
acts_on: list[str] = [] # observable type names to export, e.g. ["ipv4"]
template_name: str
sha256: str | None = None
owner: str | None = None

@property
def file_name(self) -> str:
Expand All @@ -408,13 +409,25 @@ def file_name(self) -> str:

def run(self) -> None:
"""Runs the export asynchronously."""
export_data = self.get_tagged_data(
acts_on=self.acts_on,
include_tags=self.include_tags,
exclude_tags=self.exclude_tags,
ignore_tags=self.ignore_tags,
fresh_tags=self.fresh_tags,
)
from core.schemas import rbac
from core.schemas.user import User

owner_user = User.find(username=self.owner) if self.owner else None
if (
rbac.RBAC_ENABLED
and self.owner
and (not owner_user or not owner_user.enabled)
):
export_data = []
else:
export_data = self.get_tagged_data(
acts_on=self.acts_on,
include_tags=self.include_tags,
exclude_tags=self.exclude_tags,
ignore_tags=self.ignore_tags,
fresh_tags=self.fresh_tags,
user=owner_user,
)

template = Template.find(name=self.template_name)
assert template is not None
Expand All @@ -438,6 +451,7 @@ def get_tagged_data(
exclude_tags: list[str],
ignore_tags: list[str],
fresh_tags: bool,
user=None,
):
args = {
"acts_on": acts_on,
Expand All @@ -447,7 +461,7 @@ def get_tagged_data(
"fresh": fresh_tags,
}

results = database_arango.tagged_observables_export(Observable, args)
results = database_arango.tagged_observables_export(Observable, args, user=user)
return results


Expand Down
4 changes: 3 additions & 1 deletion core/schemas/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ def delete_api_key(self, api_key_name) -> None:
self.api_keys = api_keys
self.save()

def has_permissions(self, target: str, permissions: roles.Permission) -> bool:
def has_permissions(
self, target: str, permissions: roles.Permission | roles.Role
) -> bool:
return graph.RoleRelationship.has_permissions(self, target, permissions)

def has_global_role(self, role: roles.Permission) -> bool:
Expand Down
9 changes: 4 additions & 5 deletions core/web/apiv2/audit.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import datetime

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict
from fastapi import APIRouter, Request

from core.schemas import rbac, roles
from core.schemas.audit import TimelineLog

router = APIRouter()


@router.get("/timeline/{id:path}")
def trail(id: str):
def trail(httpreq: Request, id: str):
rbac.require_permission(httpreq.state.user, id, roles.Permission.READ)
# `target_id__in` matches the id exactly (the plain `target_id` key is a
# `LIKE '%id%'` scan that also returns every object whose key starts with
# the same digits) and is served by the (target_id, timestamp) index.
Expand Down
4 changes: 3 additions & 1 deletion core/web/apiv2/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,9 @@ def match(httpreq: Request, request: AnalysisRequest) -> AnalysisResponse:
processed_relationships.add(edge.id)

matches = []
for observable_string, indi in indicator.Regex.search(values):
for observable_string, indi in indicator.Regex.search(
values, user=httpreq.state.user
):
matches.append((observable_string, indi))

return AnalysisResponse(
Expand Down
8 changes: 7 additions & 1 deletion core/web/apiv2/indicators.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ def tag(httpreq: Request, request: IndicatorTagRequest) -> IndicatorTagResponse:


@router.post("/yara/bundle")
@rbac.permission_on_ids(roles.Permission.READ)
def get_yara_bundle(httpreq: Request, request: YaraBundleRequest) -> YaraBundleResponse:
"""Generates a YARA bundle from a list of indicators."""
yaras = []
Expand Down Expand Up @@ -317,7 +318,12 @@ def get_yara_bundle(httpreq: Request, request: YaraBundleRequest) -> YaraBundleR
continue
yaras.append(yara)

bundle = Yara.generate_yara_bundle(rules=cast("list[Yara]", yaras))
try:
bundle = Yara.generate_yara_bundle(
rules=cast("list[Yara]", yaras), user=httpreq.state.user
)
except PermissionError as error:
raise HTTPException(status_code=403, detail=str(error))

if request.overlays:
yara_map = {}
Expand Down
3 changes: 2 additions & 1 deletion core/web/apiv2/rbac.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,9 @@ def update_member(

@router.delete("/{id}")
def delete(httpreq: Request, id: str) -> None:
"""Deletes an Entity."""
"""Deletes an ACL relationship."""
relationship = graph.RoleRelationship.get(id)
if not relationship:
raise HTTPException(status_code=404, detail=f"Relationship ID {id} not found")
rbac.require_permission(httpreq.state.user, relationship.target, roles.Role.OWNER)
relationship.delete()
8 changes: 6 additions & 2 deletions core/web/apiv2/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from core.config.config import yeti_config
from core.schemas import dfiq, entity, indicator, observable
from core.taskscheduler import app
from core.web.apiv2.auth import get_current_active_user
from core.web.apiv2.auth import GetCurrentUserWithPermissions, get_current_active_user

# API endpoints
router = APIRouter()
Expand Down Expand Up @@ -197,7 +197,11 @@ def get_worker_status() -> WorkerStatusResponse:


@router.post(
"/restartworker/{worker_name}", dependencies=[Depends(get_current_active_user)]
"/restartworker/{worker_name}",
dependencies=[
Depends(get_current_active_user),
Depends(GetCurrentUserWithPermissions(admin=True)),
],
)
def restart_worker(worker_name: str) -> WorkerRestartResponse:
"""Restarts a single or all Celery workers."""
Expand Down
Loading
Loading