Skip to content
Open
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
47 changes: 47 additions & 0 deletions core/tools/blueos_startup_update/blueos_startup_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import os
import re
import time
import subprocess
from pathlib import Path
from typing import List, Tuple
import configparser

Expand Down Expand Up @@ -664,6 +666,47 @@ def update_swap_size() -> bool:
return False


def setup_ssh() -> bool:
logger.info("Setting up SSH...")
# store the key in the docker .config volume
key_path = Path("/root/.config/.ssh")
private_key = key_path / "id_rsa"
public_key = private_key.with_suffix(".pub")
user = os.environ.get("SSH_USER", "pi")
gid = int(os.environ.get("USER_GID", 1000))
uid = int(os.environ.get("USER_UID", 1000))
authorized_keys = Path(f"/home/{user}/.ssh/authorized_keys")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Writing to authorized_keys assumes the parent .ssh directory exists, which can cause failures on fresh systems.

On a fresh setup /home/{user}/.ssh may not exist, so this will raise FileNotFoundError despite the missing file handling above. Consider creating the parent directory first with authorized_keys.parent.mkdir(parents=True, exist_ok=True) (and then applying the appropriate chown/chmod) before writing the file.


try:
key_path.mkdir(parents=True, exist_ok=True)
# check if id_rsa.pub exists, creates a new one if it doesnt
if not public_key.is_file():
subprocess.run(["ssh-keygen", "-t", "rsa", "-f", private_key, "-q", "-N", ""], check=True)
logger.info("Generated new SSH key pair")

public_key_text = public_key.read_text("utf-8")
# add id_rsa.pub to authorized_keys if not there already
try:
authorized_keys_text = authorized_keys.read_text("utf-8")
except FileNotFoundError:
logger.info(f"File does not exist: {authorized_keys}")
authorized_keys_text = ""

if public_key_text not in authorized_keys_text:
if not authorized_keys_text.endswith("\n"):
authorized_keys_text += "\n"
authorized_keys_text += public_key_text
authorized_keys.write_text(authorized_keys_text, "utf-8")
logger.info("Added public key to authorized_keys")

os.chown(authorized_keys, uid, gid)
authorized_keys.chmod(0o600)
return True
except Exception as sshError:
logger.error(f"Error setting up ssh: {sshError}")
return False


def main() -> int:
start = time.time()
# check if boot_loop_detector exists
Expand Down Expand Up @@ -747,6 +790,10 @@ def main() -> int:


if __name__ == "__main__":
try:
setup_ssh()
except Exception as error:
logger.error(f"An error occurred while setting up ssh: {error}")
try:
main()
if os.path.exists(BOOT_LOOP_DETECTOR):
Expand Down
Loading