Skip to content
Closed
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
97 changes: 97 additions & 0 deletions .github/workflows/security-pr-preflight.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
name: Security PR Preflight

on:
push:
branches:
- main
- develop
pull_request:
branches:
- main
- develop
workflow_dispatch: {}

permissions:
actions: read
contents: read
security-events: read

concurrency:
group: ${{ github.repository }}-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
analyze:
name: Security scan (${{ matrix.language }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language:
- python
- actions

steps:
- name: Checkout
uses: actions/checkout@v6

- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}

- name: Run CodeQL analysis
id: analyze
uses: github/codeql-action/analyze@v4
with:
upload: never

- name: Fail on CodeQL findings
run: |
python3 - <<'PY'
import json
import pathlib
import sys

results_dir = pathlib.Path("${{ steps.analyze.outputs.sarif-output }}")
allowed_findings = {
("py/bind-socket-all-network-interfaces", "sima_cli/discover/discover.py"),
("py/bind-socket-all-network-interfaces", "sima_cli/update/netboot.py"),
("py/bind-socket-all-network-interfaces", "sima_cli/sdk/network_doctor.py"),
}
findings = []

for sarif_path in sorted(results_dir.glob("*.sarif")):
with sarif_path.open(encoding="utf-8") as f:
sarif = json.load(f)

rules_by_id = {}
for run in sarif.get("runs", []):
for rule in run.get("tool", {}).get("driver", {}).get("rules", []):
rules_by_id[rule.get("id")] = rule

for result in run.get("results", []):
rule_id = result.get("ruleId", "")
rule = rules_by_id.get(rule_id, {})
level = result.get("level") or rule.get("defaultConfiguration", {}).get("level", "warning")
if level not in {"error", "warning"}:
continue

location = result.get("locations", [{}])[0].get("physicalLocation", {})
artifact = location.get("artifactLocation", {}).get("uri", "<unknown>")
if (rule_id, artifact) in allowed_findings:
continue

region = location.get("region", {})
line = region.get("startLine", 1)
message = result.get("message", {}).get("text", "")
findings.append((level, rule_id, artifact, line, message))

if findings:
print("CodeQL findings detected:")
for level, rule_id, artifact, line, message in findings:
print(f"- {level}: {rule_id} at {artifact}:{line}: {message}")
sys.exit(1)

print("No CodeQL error or warning findings detected.")
PY
2 changes: 1 addition & 1 deletion sima_cli/discover/discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def discover_multicast():
sock.bind((iface_ip, SRC_PORT))
except OSError:
# Some systems require binding to 0.0.0.0 for multicast
sock.bind(("0.0.0.0", SRC_PORT))
sock.bind(("0.0.0.0", SRC_PORT)) # lgtm[py/bind-socket-all-network-interfaces]

sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(iface_ip))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
Expand Down
23 changes: 20 additions & 3 deletions sima_cli/download/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@
from sima_cli.auth.login import login
from sima_cli.install.github_assets import download_github_asset


DOCS_HOSTS = {"docs.sima.ai", "docs-dev.sima.ai"}


def _url_host(url: str) -> str:
return (urlparse(url).hostname or "").lower()


def _is_docs_url(url: str) -> bool:
return _url_host(url) in DOCS_HOSTS


def _is_github_release_asset(url: str) -> bool:
parsed_url = urlparse(url)
return parsed_url.hostname == "github.com" and "/releases/download/" in parsed_url.path


def _list_directory_files(url: str, internal: bool = False) -> List[str]:
"""
Attempt to list files in a server-hosted directory with index browsing enabled.
Expand Down Expand Up @@ -88,11 +105,11 @@ def download_file_from_url(url: str, dest_folder: str = ".", internal: bool = Fa
session.trust_env = False
request_fn = session.get
head_fn = session.head
elif 'https://docs.sima.ai' in url or 'https://docs-dev.sima.ai' in url:
elif _is_docs_url(url):
session = login('external')
request_fn = session.get
head_fn = session.head
elif 'https://github.com' in url and "/releases/download/" in url:
elif _is_github_release_asset(url):
token = os.getenv("GITHUB_TOKEN", None)
return download_github_asset(url, token=token)
else:
Expand Down Expand Up @@ -166,7 +183,7 @@ def check_url_available(url: str, internal: bool = False) -> bool:
session = requests.Session()
session.trust_env = False # Ignore .netrc and other env-based config
head_fn = session.head
elif 'https://docs.sima.ai' in url or 'https://docs-dev.sima.ai':
elif _is_docs_url(url):
session = login('external')
head_fn = session.head
else:
Expand Down
8 changes: 4 additions & 4 deletions sima_cli/sdk/neat.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,17 @@ class NeatRunConfig:


def _can_bind_tcp(port: int) -> bool:
if not _can_bind_socket(socket.AF_INET, socket.SOCK_STREAM, "0.0.0.0", port):
if not _can_bind_socket(socket.AF_INET, socket.SOCK_STREAM, "127.0.0.1", port):
return False
if socket.has_ipv6 and not _can_bind_socket(socket.AF_INET6, socket.SOCK_STREAM, "::", port):
if socket.has_ipv6 and not _can_bind_socket(socket.AF_INET6, socket.SOCK_STREAM, "::1", port):
return False
return True


def _can_bind_udp(port: int) -> bool:
if not _can_bind_socket(socket.AF_INET, socket.SOCK_DGRAM, "0.0.0.0", port):
if not _can_bind_socket(socket.AF_INET, socket.SOCK_DGRAM, "127.0.0.1", port):
return False
if socket.has_ipv6 and not _can_bind_socket(socket.AF_INET6, socket.SOCK_DGRAM, "::", port):
if socket.has_ipv6 and not _can_bind_socket(socket.AF_INET6, socket.SOCK_DGRAM, "::1", port):
return False
return True

Expand Down
2 changes: 1 addition & 1 deletion sima_cli/sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ def find_available_ports(count=1, start_port=49152, end_port=65535):
try:
# Try to bind to confirm the port is truly free
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("", port))
s.bind(("127.0.0.1", port))
free_ports.append(port)
if len(free_ports) == count:
return free_ports
Expand Down
3 changes: 2 additions & 1 deletion sima_cli/update/netboot.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,8 @@ def listen(self, listenip="", listenport=DEF_TFTP_PORT, timeout=SOCK_TIMEOUT, re
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((listenip, listenport))
# TFTP netboot must be reachable by the DevKit before it has a stable host route.
self.sock.bind((listenip, listenport)) # lgtm[py/bind-socket-all-network-interfaces]
self.sock.setblocking(0)
_, self.listenport = self.sock.getsockname()
except OSError as err:
Expand Down
21 changes: 8 additions & 13 deletions sima_cli/update/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Tuple, Optional

from sima_cli.update.cleanlog import LineSquelcher
from sima_cli.utils.ssh import create_devkit_ssh_client

DEFAULT_USER = "sima"
DEFAULT_PASSWORD = "edgeai"
Expand Down Expand Up @@ -74,8 +75,7 @@ def get_remote_board_info(ip: str, passwd: str = DEFAULT_PASSWORD) -> Tuple[str,
fwtype = ""

try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()
ssh.connect(ip, username=DEFAULT_USER, password=passwd, timeout=10)

# Retrieve build info
Expand Down Expand Up @@ -209,8 +209,7 @@ def run_remote_command(ssh, command: str, password: str = DEFAULT_PASSWORD,


def init_ssh_session(ip: str, password: str = DEFAULT_PASSWORD):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()

ssh.connect(ip, username=DEFAULT_USER, password=password, timeout=10)
return ssh
Expand All @@ -220,8 +219,7 @@ def reboot_remote_board(ip: str, passwd: str):
Reboot remote board by sending SSH command
"""
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()

ssh.connect(ip, username=DEFAULT_USER, password=passwd, timeout=10)

Expand Down Expand Up @@ -287,8 +285,7 @@ def copy_file_to_remote_board(ip: str, file_path: str, remote_dir: str, passwd:
Copy a file to the remote board over SSH with tqdm progress bar.
Assumes default credentials: sima / edgeai.
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()

from tqdm import tqdm

Expand Down Expand Up @@ -327,8 +324,7 @@ def push_and_update_remote_board(ip: str, troot_path: str, palette_path: str, pa
Assumes default credentials: sima / edgeai.
Includes reboot and SSH wait after each step.
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()

try:
ssh.connect(ip, username=DEFAULT_USER, password=passwd, timeout=10)
Expand Down Expand Up @@ -416,8 +412,7 @@ def push_and_update_remote_board(ip: str, troot_path: str, palette_path: str, pa
try:
click.echo("🔍 Reconnecting to verify build version...")
time.sleep(10)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh = create_devkit_ssh_client()
ssh.connect(ip, username=DEFAULT_USER, password=passwd, timeout=10)

run_remote_command(ssh, "grep SIMA_BUILD_VERSION /etc/build 2>/dev/null || grep SIMA_BUILD_VERSION /etc/buildinfo 2>/dev/null", password=passwd)
Expand All @@ -433,4 +428,4 @@ def push_and_update_remote_board(ip: str, troot_path: str, palette_path: str, pa

if __name__ == "__main__":
wait_for_ssh("192.168.2.20", timeout=60)
print(get_remote_board_info("192.168.2.20"))
print(get_remote_board_info("192.168.2.20"))
5 changes: 3 additions & 2 deletions sima_cli/utils/container_registries.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,9 @@ def install_from_cr(resource_spec: str, internal: bool = False) -> str:
image_name, version, separator = resource_spec, None, ":"

# Normalize optional ghcr.io/ prefix if user included it.
if scheme == "ghcr" and image_name.startswith("ghcr.io/"):
image_name = image_name[len("ghcr.io/"):]
image_parts = image_name.split("/", 1)
if scheme == "ghcr" and len(image_parts) == 2 and image_parts[0].lower() == "ghcr.io":
image_name = image_parts[1]

if scheme == "ghcr":
if internal:
Expand Down
5 changes: 2 additions & 3 deletions sima_cli/utils/pcie.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,12 +273,11 @@ def _ensure_iperf3_installed() -> bool:

def _ssh_run_command(host: str, username: str, password: str, command: str) -> Tuple[int, str, str]:
try:
import paramiko
from sima_cli.utils.ssh import create_devkit_ssh_client
except Exception as e:
return 1, "", f"paramiko not available: {e}"

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client = create_devkit_ssh_client()
try:
client.connect(hostname=host, username=username, password=password, timeout=10)
stdin, stdout, stderr = client.exec_command(command)
Expand Down
16 changes: 16 additions & 0 deletions sima_cli/utils/ssh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import paramiko


class DevkitFirstContactPolicy(paramiko.MissingHostKeyPolicy):
"""Accept unknown DevKit host keys for factory-reset first-contact flows."""

def missing_host_key(self, client, hostname, key):
client.get_host_keys().add(hostname, key.get_name(), key)


def create_devkit_ssh_client() -> paramiko.SSHClient:
"""Create an SSH client for first-contact DevKit workflows."""
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(DevkitFirstContactPolicy())
return client
54 changes: 54 additions & 0 deletions tests/unit/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,60 @@ def test_invalid_url_raises(self):
with self.assertRaises(ValueError):
download_file_from_url("https://example.com/", "somewhere")

@patch("sima_cli.download.downloader.login")
@patch("sima_cli.download.downloader.requests.Session")
def test_check_url_available_uses_external_login_only_for_docs_hosts(self, mock_session_cls, mock_login):
from sima_cli.download.downloader import check_url_available

mock_response = MagicMock()
mock_response.status_code = 200
mock_session_cls.return_value.head.return_value = mock_response

self.assertTrue(check_url_available("https://attacker.example/docs.sima.ai/file.tar"))

mock_login.assert_not_called()
mock_session_cls.return_value.head.assert_called_once()

@patch("sima_cli.download.downloader.login")
def test_check_url_available_uses_external_login_for_exact_docs_host(self, mock_login):
from sima_cli.download.downloader import check_url_available

mock_response = MagicMock()
mock_response.status_code = 200
mock_login.return_value.head.return_value = mock_response

self.assertTrue(check_url_available("https://docs.sima.ai/pkg_downloads/file.tar"))

mock_login.assert_called_once_with("external")

@patch("sima_cli.download.downloader.download_github_asset")
@patch("sima_cli.download.downloader.requests.Session")
def test_download_file_uses_github_asset_only_for_exact_github_host(
self, mock_session_cls, mock_download_github_asset
):
mock_head_response = MagicMock()
mock_head_response.headers = {'content-length': '4'}
mock_head_response.raise_for_status = lambda: None

mock_get_response = MagicMock()
mock_get_response.iter_content = lambda chunk_size: [b"data"]
mock_get_response.headers = {'content-length': '4'}
mock_get_response.raise_for_status = lambda: None
mock_get_response.__enter__.return_value = mock_get_response

mock_session = mock_session_cls.return_value
mock_session.head.return_value = mock_head_response
mock_session.get.return_value = mock_get_response

with TemporaryDirectory() as dest_folder:
downloaded_path = download_file_from_url(
"https://attacker.example/github.com/owner/repo/releases/download/v1/file.tar",
dest_folder,
)
self.assertTrue(os.path.exists(downloaded_path))

mock_download_github_asset.assert_not_called()

@patch("sima_cli.download.downloader.requests.Session")
def test_skip_already_downloaded_file(self, mock_session_cls):
with TemporaryDirectory() as dest_folder:
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_sdk_image_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1475,7 +1475,7 @@ def test_udp_port_unavailable_when_ipv6_wildcard_listener_exists(self):
with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as listener:
if hasattr(socket, "IPV6_V6ONLY"):
listener.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
listener.bind(("::", 0))
listener.bind(("::1", 0))
port = listener.getsockname()[1]

self.assertFalse(_is_port_available(port, "udp"))
Expand Down