Example #1
0
def test_query_device_do_update_policy(monkeypatch):
    _was_called = False

    def _update_policy(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "UPDATE_POLICY",
            "search": {
                "query": "foobar",
                "criteria": {},
                "exclusions": {}
            },
            "options": {
                "policy_id": 8675309
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_update_policy)
    api.select(Device).where("foobar").update_policy(8675309)
    assert _was_called
def test_audit_remediation_history(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/_search"
        assert body == {"query": "xyzzy", "start": 0}
        _was_called = True
        return StubResponse({"org_key": "Z100", "num_found": 3,
                             "results": [{"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"},
                                         {"org_key": "Z100", "name": "Aoxomoxoa", "id": "cdefghi"},
                                         {"org_key": "Z100", "name": "Read_Me", "id": "efghijk"}]})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.audit_remediation_history("xyzzy")
    assert isinstance(query, RunHistoryQuery)
    count = 0
    for item in query.all():
        assert item.org_key == "Z100"
        if item.id == "abcdefg":
            assert item.name == "FoobieBletch"
        elif item.id == "cdefghi":
            assert item.name == "Aoxomoxoa"
        elif item.id == "efghijk":
            assert item.name == "Read_Me"
        else:
            pytest.fail("Unknown item ID: %s" % item.id)
        count = count + 1
    assert _was_called
    assert count == 3
Example #3
0
def test_query_device_do_update_sensor_version(monkeypatch):
    _was_called = False

    def _update_sensor_version(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "UPDATE_SENSOR_VERSION",
            "search": {
                "query": "foobar",
                "criteria": {},
                "exclusions": {}
            },
            "options": {
                "sensor_version": {
                    "RHEL": "2.3.4.5"
                }
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_update_sensor_version)
    api.select(Device).where("foobar").update_sensor_version(
        {"RHEL": "2.3.4.5"})
    assert _was_called
Example #4
0
def test_query_basealert_facets(monkeypatch):
    _was_called = False

    def _run_facet_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/alerts/_facet"
        assert body["query"] == "Blort"
        t = body["criteria"]
        assert t["workflow"] == ["OPEN"]
        t = body["terms"]
        assert t["rows"] == 0
        assert t["fields"] == ["REPUTATION", "STATUS"]
        _was_called = True
        return StubResponse({"results": [{"field": {},
                                          "values": [{"id": "reputation", "name": "reputationX", "total": 4}]},
                                         {"field": {},
                                          "values": [{"id": "status", "name": "statusX", "total": 9}]}]})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_facet_query)
    query = api.select(BaseAlert).where("Blort").set_workflows(["OPEN"])
    f = query.facets(["REPUTATION", "STATUS"])
    assert _was_called
    assert f == [{"field": {}, "values": [{"id": "reputation", "name": "reputationX", "total": 4}]},
                 {"field": {}, "values": [{"id": "status", "name": "statusX", "total": 9}]}]
def test_Device_update_sensor_version(monkeypatch):
    _was_called = False

    def _get_device(url, parms=None, default=None):
        assert url == "/appservices/v6/orgs/Z100/devices/6023"
        return {"id": 6023}

    def _update_sensor_version(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "UPDATE_SENSOR_VERSION",
            "device_id": [6023],
            "options": {
                "sensor_version": {
                    "RHEL": "2.3.4.5"
                }
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_device, POST=_update_sensor_version)
    dev = Device(api, 6023, {"id": 6023})
    dev.update_sensor_version({"RHEL": "2.3.4.5"})
    assert _was_called
def test_Device_bypass(monkeypatch):
    _was_called = False

    def _get_device(url, parms=None, default=None):
        assert url == "/appservices/v6/orgs/Z100/devices/6023"
        return {"id": 6023}

    def _bypass(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "BYPASS",
            "device_id": [6023],
            "options": {
                "toggle": "OFF"
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_device, POST=_bypass)
    dev = Device(api, 6023, {"id": 6023})
    dev.bypass(False)
    assert _was_called
def test_Device_update_policy(monkeypatch):
    _was_called = False

    def _get_device(url, parms=None, default=None):
        assert url == "/appservices/v6/orgs/Z100/devices/6023"
        return {"id": 6023}

    def _update_policy(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "UPDATE_POLICY",
            "device_id": [6023],
            "options": {
                "policy_id": 8675309
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_device, POST=_update_policy)
    dev = Device(api, 6023, {"id": 6023})
    dev.update_policy(8675309)
    assert _was_called
Example #8
0
def test_query_device_download(monkeypatch):
    _was_called = False

    def _run_download(url, query_params, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/devices/_search/download"
        assert query_params == {
            "status": "ALL",
            "ad_group_id": "14,25",
            "policy_id": "8675309",
            "target_priority": "HIGH",
            "query_string": "foobar",
            "sort_field": "name",
            "sort_order": "DESC"
        }
        _was_called = True
        return "123456789,123456789,123456789"

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, RAW_GET=_run_download)
    rc = api.select(Device).where("foobar").set_ad_group_ids([14, 25]).set_policy_ids([8675309]) \
        .set_status(["ALL"]).set_target_priorities(["HIGH"]).sort_by("name", "DESC").download()
    assert _was_called
    assert rc == "123456789,123456789,123456789"
Example #9
0
def test_query_device_do_quarantine(monkeypatch):
    _was_called = False

    def _quarantine(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {
            "action_type": "QUARANTINE",
            "search": {
                "query": "foobar",
                "criteria": {},
                "exclusions": {}
            },
            "options": {
                "toggle": "ON"
            }
        }
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_quarantine)
    api.select(Device).where("foobar").quarantine(True)
    assert _was_called
Example #10
0
def test_run_refresh(monkeypatch):
    _was_called = False

    def _get_run(url, parms=None, default=None):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg"
        _was_called = True
        return {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "COMPLETE"
        }

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_run)
    run = Run(
        api, "abcdefg", {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "ACTIVE"
        })
    rc = run.refresh()
    assert _was_called
    assert rc
    assert run.org_key == "Z100"
    assert run.name == "FoobieBletch"
    assert run.id == "abcdefg"
    assert run.status == "COMPLETE"
Example #11
0
def test_run_stop_failed(monkeypatch):
    _was_called = False

    def _execute_stop(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg/status"
        assert body == {"status": "CANCELLED"}
        _was_called = True
        return StubResponse(
            {"error_message": "The query is not presently running."}, 409)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, PUT=_execute_stop)
    run = Run(
        api, "abcdefg", {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "CANCELLED"
        })
    rc = run.stop()
    assert _was_called
    assert not rc
Example #12
0
def test_run_stop(monkeypatch):
    _was_called = False

    def _execute_stop(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg/status"
        assert body == {"status": "CANCELLED"}
        _was_called = True
        return StubResponse({
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "CANCELLED"
        })

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, PUT=_execute_stop)
    run = Run(
        api, "abcdefg", {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "ACTIVE"
        })
    rc = run.stop()
    assert _was_called
    assert rc
    assert run.org_key == "Z100"
    assert run.name == "FoobieBletch"
    assert run.id == "abcdefg"
    assert run.status == "CANCELLED"
Example #13
0
def test_run_delete_failed(monkeypatch):
    _was_called = False

    def _execute_delete(url):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg"
        _was_called = True
        return StubResponse(None, 403)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, DELETE=_execute_delete)
    run = Run(
        api, "abcdefg", {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "ACTIVE"
        })
    rc = run.delete()
    assert _was_called
    assert not rc
    assert not run._is_deleted
Example #14
0
def test_run_delete(monkeypatch):
    _was_called = False

    def _execute_delete(url):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg"
        if _was_called:
            pytest.fail("_execute_delete should not be called twice!")
        _was_called = True
        return StubResponse(None)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, DELETE=_execute_delete)
    run = Run(
        api, "abcdefg", {
            "org_key": "Z100",
            "name": "FoobieBletch",
            "id": "abcdefg",
            "status": "ACTIVE"
        })
    rc = run.delete()
    assert _was_called
    assert rc
    assert run._is_deleted
    # Now ensure that certain operations that don't make sense on a deleted object raise ApiError
    with pytest.raises(ApiError):
        run.refresh()
    with pytest.raises(ApiError):
        run.stop()
    # And make sure that deleting a deleted object returns True immediately
    rc = run.delete()
    assert rc
def test_WorkflowStatus(monkeypatch):
    _times_called = 0

    def _get_workflow(url, parms=None, default=None):
        nonlocal _times_called
        assert url == "/appservices/v6/orgs/Z100/workflow/status/W00K13"
        if _times_called >= 0 and _times_called <= 3:
            _stat = "QUEUED"
        elif _times_called >= 4 and _times_called <= 6:
            _stat = "IN_PROGRESS"
        elif _times_called >= 7 and _times_called <= 9:
            _stat = "FINISHED"
        else:
            pytest.fail("_get_workflow called too many times")
        _times_called = _times_called + 1
        return {
            "errors": [],
            "failed_ids": [],
            "id": "W00K13",
            "num_hits": 0,
            "num_success": 0,
            "status": _stat,
            "workflow": {
                "state": "DISMISSED",
                "remediation": "Fixed",
                "comment": "Yessir",
                "changed_by": "Robocop",
                "last_update_time": "2019-10-31T16:03:13.951Z"
            }
        }

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_workflow)
    wfstat = WorkflowStatus(api, "W00K13")
    assert wfstat.workflow_.changed_by == "Robocop"
    assert wfstat.workflow_.state == "DISMISSED"
    assert wfstat.workflow_.remediation == "Fixed"
    assert wfstat.workflow_.comment == "Yessir"
    assert wfstat.workflow_.last_update_time == "2019-10-31T16:03:13.951Z"
    assert _times_called == 1
    assert wfstat.queued
    assert not wfstat.in_progress
    assert not wfstat.finished
    assert _times_called == 4
    assert not wfstat.queued
    assert wfstat.in_progress
    assert not wfstat.finished
    assert _times_called == 7
    assert not wfstat.queued
    assert not wfstat.in_progress
    assert wfstat.finished
    assert _times_called == 10
def test_simple_query(monkeypatch):
    """Test SimpleQuery methods using a FeedQuery for API calls"""
    _was_called = False

    def _get_results(url, **kwargs):
        nonlocal _was_called
        assert url == "/threathunter/feedmgr/v2/orgs/WNEX/feeds"
        _was_called = True
        return {
            "results": [{
                "name": "My Feed",
                "owner": "WNEX",
                "provider_url": "https://exampleprovider.com",
                "summary": "this is the summary",
                "category": "this is the category",
                "source_label": None,
                "access": "public",
                "id": "my_feed_id"
            }]
        }

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="WNEX",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_results)
    feed = api.select(Feed).where(include_public=True)

    assert isinstance(feed, SimpleQuery)
    assert isinstance(feed, FeedQuery)

    results = feed.results

    assert isinstance(results, list)
    assert isinstance(results[0], Feed)
    assert results[0].id == "my_feed_id"
    assert results[0].name == "My Feed"
    assert _was_called

    simpleQuery = SimpleQuery(Feed, api)
    assert simpleQuery._doc_class == Feed
    assert str(
        simpleQuery._urlobject) == "/threathunter/feedmgr/v2/orgs/{}/feeds"
    assert isinstance(simpleQuery, SimpleQuery)
    assert simpleQuery._cb == api
    assert simpleQuery._results == []
    assert simpleQuery._query == {}

    clonedSimple = simpleQuery._clone()
    assert clonedSimple._cb == simpleQuery._cb
    assert clonedSimple._results == simpleQuery._results
    assert clonedSimple._query == simpleQuery._query
Example #17
0
def test_alerts_bulk_undismiss_threat(monkeypatch):
    _was_called = False

    def _do_update(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/threat/workflow/_criteria"
        assert body == {"threat_id": ["B0RG", "F3R3NG1"], "state": "OPEN", "remediation_state": "Fixed",
                        "comment": "NoSir"}
        _was_called = True
        return StubResponse({"request_id": "497ABX"})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_do_update)
    reqid = api.bulk_threat_update(["B0RG", "F3R3NG1"], "Fixed", "NoSir")
    assert _was_called
    assert reqid == "497ABX"
def test_simple_get(monkeypatch):
    _was_called = False

    def _get_run(url, parms=None, default=None):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs/abcdefg"
        _was_called = True
        return {"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"}

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_run)
    run = api.select(Run, "abcdefg")
    assert _was_called
    assert run.org_key == "Z100"
    assert run.name == "FoobieBletch"
    assert run.id == "abcdefg"
def test_Device_lr_session(monkeypatch):
    def _get_session(url, parms=None, default=None):
        assert url == "/appservices/v6/orgs/Z100/devices/6023"
        return {"id": 6023}

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    sked = StubScheduler(6023)
    api._lr_scheduler = sked
    patch_cbapi(monkeypatch, api, GET=_get_session)
    dev = Device(api, 6023, {"id": 6023})
    sess = dev.lr_session()
    assert sess["itworks"]
    assert sked.was_called
Example #20
0
def test_device_delete_sensor(monkeypatch):
    _was_called = False

    def _call_delete_sensor(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/device_actions"
        assert body == {"action_type": "DELETE_SENSOR", "device_id": [6023]}
        _was_called = True
        return StubResponse(None, 204)

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_call_delete_sensor)
    api.device_delete_sensor([6023])
    assert _was_called
Example #21
0
def test_alerts_bulk_dismiss_vmware(monkeypatch):
    _was_called = False

    def _do_dismiss(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/alerts/vmware/workflow/_criteria"
        assert body == {"query": "Blort", "state": "DISMISSED", "remediation_state": "Fixed", "comment": "Yessir",
                        "criteria": {"device_name": ["HAL9000"]}}
        _was_called = True
        return StubResponse({"request_id": "497ABX"})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_do_dismiss)
    q = api.select(VMwareAlert).where("Blort").set_device_names(["HAL9000"])
    reqid = q.dismiss("Fixed", "Yessir")
    assert _was_called
    assert reqid == "497ABX"
Example #22
0
def test_load_workflow(monkeypatch):
    _was_called = False

    def _get_workflow(url, parms=None, default=None):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/workflow/status/497ABX"
        _was_called = True
        return {"errors": [], "failed_ids": [], "id": "497ABX", "num_hits": 0, "num_success": 0, "status": "QUEUED",
                "workflow": {"state": "DISMISSED", "remediation": "Fixed", "comment": "Yessir",
                             "changed_by": "Robocop", "last_update_time": "2019-10-31T16:03:13.951Z"}}

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234",
                       org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_workflow)
    workflow = api.select(WorkflowStatus, "497ABX")
    assert _was_called
    assert workflow.id_ == "497ABX"
Example #23
0
def test_query_device_with_all_bells_and_whistles(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/devices/_search"
        assert body == {
            "query": "foobar",
            "criteria": {
                "ad_group_id": [14, 25],
                "os": ["LINUX"],
                "policy_id": [8675309],
                "status": ["ALL"],
                "target_priority": ["HIGH"]
            },
            "exclusions": {
                "sensor_version": ["0.1"]
            },
            "sort": [{
                "field": "name",
                "order": "DESC"
            }]
        }
        _was_called = True
        return StubResponse({
            "results": [{
                "id": 6023,
                "organization_name": "thistestworks"
            }],
            "num_found":
            1
        })

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.select(Device).where("foobar").set_ad_group_ids([14, 25]).set_os(["LINUX"]) \
        .set_policy_ids([8675309]).set_status(["ALL"]).set_target_priorities(["HIGH"]) \
        .set_exclude_sensor_versions(["0.1"]).sort_by("name", "DESC")
    d = query.one()
    assert _was_called
    assert d.id == 6023
    assert d.organization_name == "thistestworks"
def test_audit_remediation(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs"
        assert body == {"sql": "select * from whatever;", "device_filter": {}}
        _was_called = True
        return StubResponse({"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.audit_remediation("select * from whatever;")
    assert isinstance(query, RunQuery)
    run = query.submit()
    assert _was_called
    assert run.org_key == "Z100"
    assert run.name == "FoobieBletch"
    assert run.id == "abcdefg"
Example #25
0
def test_get_device(monkeypatch):
    _was_called = False

    def _get_device(url):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/devices/6023"
        _was_called = True
        return {"device_id": 6023, "organization_name": "thistestworks"}

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, GET=_get_device)
    rc = api.select(Device, 6023)
    assert _was_called
    assert isinstance(rc, Device)
    assert rc.device_id == 6023
    assert rc.organization_name == "thistestworks"
Example #26
0
def test_query_cbanalyticsalert_with_all_bells_and_whistles(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/alerts/cbanalytics/_search"
        assert body == {"query": "Blort",
                        "criteria": {"category": ["SERIOUS", "CRITICAL"], "device_id": [6023], "device_name": ["HAL"],
                                     "device_os": ["LINUX"], "device_os_version": ["0.1.2"],
                                     "device_username": ["JRN"], "group_results": True, "id": ["S0L0"],
                                     "legacy_alert_id": ["S0L0_1"], "minimum_severity": 6, "policy_id": [8675309],
                                     "policy_name": ["Strict"], "process_name": ["IEXPLORE.EXE"],
                                     "process_sha256": ["0123456789ABCDEF0123456789ABCDEF"],
                                     "reputation": ["SUSPECT_MALWARE"], "tag": ["Frood"], "target_value": ["HIGH"],
                                     "threat_id": ["B0RG"], "type": ["WATCHLIST"], "workflow": ["OPEN"],
                                     "blocked_threat_category": ["RISKY_PROGRAM"], "device_location": ["ONSITE"],
                                     "kill_chain_status": ["EXECUTE_GOAL"],
                                     "not_blocked_threat_category": ["NEW_MALWARE"], "policy_applied": ["APPLIED"],
                                     "reason_code": ["ATTACK_VECTOR"], "run_state": ["RAN"], "sensor_action": ["DENY"],
                                     "threat_cause_vector": ["WEB"]}, "sort": [{"field": "name", "order": "DESC"}]}
        _was_called = True
        return StubResponse({"results": [{"id": "S0L0", "org_key": "Z100", "threat_id": "B0RG",
                                          "workflow": {"state": "OPEN"}}], "num_found": 1})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.select(CBAnalyticsAlert).where("Blort").set_categories(["SERIOUS", "CRITICAL"]) \
        .set_device_ids([6023]).set_device_names(["HAL"]).set_device_os(["LINUX"]).set_device_os_versions(["0.1.2"]) \
        .set_device_username(["JRN"]).set_group_results(True).set_alert_ids(["S0L0"]).set_legacy_alert_ids(["S0L0_1"]) \
        .set_minimum_severity(6).set_policy_ids([8675309]).set_policy_names(["Strict"]) \
        .set_process_names(["IEXPLORE.EXE"]).set_process_sha256(["0123456789ABCDEF0123456789ABCDEF"]) \
        .set_reputations(["SUSPECT_MALWARE"]).set_tags(["Frood"]).set_target_priorities(["HIGH"]) \
        .set_threat_ids(["B0RG"]).set_types(["WATCHLIST"]).set_workflows(["OPEN"]) \
        .set_blocked_threat_categories(["RISKY_PROGRAM"]).set_device_locations(["ONSITE"]) \
        .set_kill_chain_statuses(["EXECUTE_GOAL"]).set_not_blocked_threat_categories(["NEW_MALWARE"]) \
        .set_policy_applied(["APPLIED"]).set_reason_code(["ATTACK_VECTOR"]).set_run_states(["RAN"]) \
        .set_sensor_actions(["DENY"]).set_threat_cause_vectors(["WEB"]).sort_by("name", "DESC")
    a = query.one()
    assert _was_called
    assert a.id == "S0L0"
    assert a.org_key == "Z100"
    assert a.threat_id == "B0RG"
    assert a.workflow_.state == "OPEN"
Example #27
0
def test_query_basealert_with_create_time_as_range(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/alerts/_search"
        assert body == {"query": "Blort", "criteria": {"create_time": {"range": "-3w"}}}
        _was_called = True
        return StubResponse({"results": [{"id": "S0L0", "org_key": "Z100", "threat_id": "B0RG",
                                          "workflow": {"state": "OPEN"}}], "num_found": 1})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.select(BaseAlert).where("Blort").set_create_time(range="-3w")
    a = query.one()
    assert _was_called
    assert a.id == "S0L0"
    assert a.org_key == "Z100"
    assert a.threat_id == "B0RG"
    assert a.workflow_.state == "OPEN"
def test_paginated_query(monkeypatch):
    """Test PaginatedQuery methods"""
    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="WNEX",
                     ssl_verify=True)
    paginatedQuery = PaginatedQuery(Process,
                                    api,
                                    query="process_name='malicious.exe'")
    assert isinstance(paginatedQuery, PaginatedQuery)
    assert isinstance(paginatedQuery, BaseQuery)
    assert paginatedQuery._doc_class == Process
    assert paginatedQuery._query == "process_name='malicious.exe'"

    clonedPaginated = paginatedQuery._clone()
    assert clonedPaginated._doc_class == paginatedQuery._doc_class
    assert clonedPaginated._cb == paginatedQuery._cb
    assert clonedPaginated._total_results == paginatedQuery._total_results
    assert clonedPaginated._count_valid == paginatedQuery._count_valid
    assert clonedPaginated._batch_size == paginatedQuery._batch_size

    _devices_was_called = False

    def _get_devices(url, **kwargs):
        nonlocal _devices_was_called
        assert url == "/integrationServices/v3/device"
        _devices_was_called = True
        return {"results": [{"deviceId": "my_device_id"}]}

    deviceQuery = Query(Device, api)
    deviceQuery = deviceQuery.where("deviceId:'my_device_id'")

    assert isinstance(deviceQuery, PaginatedQuery)
    assert isinstance(deviceQuery, Query)

    patch_cbapi(monkeypatch, api, GET=_get_devices)

    x = deviceQuery.__getitem__(1)
    # assert x is not None
    assert _devices_was_called
def test_audit_remediation_with_everything(monkeypatch):
    _was_called = False

    def _run_query(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/livequery/v1/orgs/Z100/runs"
        assert body == {"sql": "select * from whatever;", "name": "AmyWasHere", "notify_on_finish": True,
                        "device_filter": {"device_id": [1, 2, 3], "os": ["Alpha", "Bravo", "Charlie"],
                                          "policy_id": [16]}}
        _was_called = True
        return StubResponse({"org_key": "Z100", "name": "FoobieBletch", "id": "abcdefg"})

    api = CBCloudAPI(url="https://example.com", token="ABCD/1234", org_key="Z100", ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_run_query)
    query = api.audit_remediation("select * from whatever;").device_ids([1, 2, 3]).device_types(["Alpha", "Bravo", "Charlie"]) \
        .policy_id(16).name("AmyWasHere").notify_on_finish()
    assert isinstance(query, RunQuery)
    run = query.submit()
    assert _was_called
    assert run.org_key == "Z100"
    assert run.name == "FoobieBletch"
    assert run.id == "abcdefg"
def test_BaseAlert_undismiss_threat(monkeypatch):
    _was_called = False

    def _do_update(url, body, **kwargs):
        nonlocal _was_called
        assert url == "/appservices/v6/orgs/Z100/threat/B0RG/workflow"
        assert body == {
            "state": "OPEN",
            "remediation_state": "Fixed",
            "comment": "NoSir"
        }
        _was_called = True
        return StubResponse({
            "state": "OPEN",
            "remediation": "Fixed",
            "comment": "NoSir",
            "changed_by": "Robocop",
            "last_update_time": "2019-10-31T16:03:13.951Z"
        })

    api = CBCloudAPI(url="https://example.com",
                     token="ABCD/1234",
                     org_key="Z100",
                     ssl_verify=True)
    patch_cbapi(monkeypatch, api, POST=_do_update)
    alert = BaseAlert(api, "ESD14U2C", {
        "id": "ESD14U2C",
        "threat_id": "B0RG",
        "workflow": {
            "state": "OPEN"
        }
    })
    wf = alert.update_threat("Fixed", "NoSir")
    assert _was_called
    assert wf.changed_by == "Robocop"
    assert wf.state == "OPEN"
    assert wf.remediation == "Fixed"
    assert wf.comment == "NoSir"
    assert wf.last_update_time == "2019-10-31T16:03:13.951Z"