|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Copyright 2021 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | +"""Executable and reusable sample for archiving a detection rule.""" |
| 18 | + |
| 19 | +import argparse |
| 20 | + |
| 21 | +from google.auth.transport import requests |
| 22 | + |
| 23 | +from common import chronicle_auth |
| 24 | + |
| 25 | +CHRONICLE_API_BASE_URL = "https://backstory.googleapis.com" |
| 26 | + |
| 27 | + |
| 28 | +def archive_rule(http_session: requests.AuthorizedSession, version_id: str): |
| 29 | + """Archives a detection rule. |
| 30 | +
|
| 31 | + Archiving a rule will fail if: |
| 32 | + - The provided version is not the latest rule version |
| 33 | + - The rule is enabled as live |
| 34 | + - The rule has retrohunts in progress |
| 35 | +
|
| 36 | + If alerting is enabled for a rule, archiving the rule will automatically |
| 37 | + disable alerting for the rule. |
| 38 | +
|
| 39 | + Args: |
| 40 | + http_session: Authorized session for HTTP requests. |
| 41 | + version_id: Unique ID of the detection rule to archive ("ru_<UUID>" or |
| 42 | + "ru_<UUID>@v_<seconds>_<nanoseconds>"). If a version suffix isn't |
| 43 | + specified we use the rule's latest version. |
| 44 | +
|
| 45 | + Raises: |
| 46 | + requests.exceptions.HTTPError: HTTP request resulted in an error |
| 47 | + (response.status_code >= 400). |
| 48 | + """ |
| 49 | + url = f"{CHRONICLE_API_BASE_URL}/v2/detect/rules/{version_id}:archive" |
| 50 | + |
| 51 | + response = http_session.request("POST", url) |
| 52 | + # Expected server response: |
| 53 | + # {} |
| 54 | + |
| 55 | + if response.status_code >= 400: |
| 56 | + print(response.text) |
| 57 | + response.raise_for_status() |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + parser = argparse.ArgumentParser() |
| 62 | + chronicle_auth.add_argument_credentials_file(parser) |
| 63 | + parser.add_argument( |
| 64 | + "-vi", |
| 65 | + "--version_id", |
| 66 | + type=str, |
| 67 | + required=True, |
| 68 | + help="version ID ('ru_<UUID>[@v_<seconds>_<nanoseconds>]')") |
| 69 | + |
| 70 | + args = parser.parse_args() |
| 71 | + session = chronicle_auth.init_session( |
| 72 | + chronicle_auth.init_credentials(args.credentials_file)) |
| 73 | + archive_rule(session, args.version_id) |
0 commit comments