#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Build Ultra Hardened dropbear-2025.88 from sources.
# Globals:
#   DIR_TMP
#   ERR_PATH_NOT_VALID
#   VAR_SETUP_PATH
# Arguments:
#   None
# Returns:
#   ERR_PATH_NOT_VALID
#   0: on success
#######################################
build_dropbear() {
  declare var_dropbear_version="2025.88"
  declare var_tar="${VAR_SETUP_PATH}/upgrades/dropbear/dropbear-${var_dropbear_version}.tar.bz2"
  declare var_build_dir="${DIR_TMP}/build/dropbear-${var_dropbear_version}"

  mkdir -p "${DIR_TMP}/build"
  cp "${var_tar}" "${DIR_TMP}/build"
  tar xjf "${DIR_TMP}/build/dropbear-${var_dropbear_version}.tar.bz2" -C "${DIR_TMP}/build" || return "${ERR_PATH_NOT_VALID}"
  cp "${VAR_SETUP_PATH}/upgrades/dropbear/localoptions.h" "${var_build_dir}"
  cd "${var_build_dir}" || return "${ERR_PATH_NOT_VALID}"

  # Flag Purpose
  #  -fPIE:               Generate position-independent executable code
  #  -pie:                Link the executable as PIE (so that ASLR works)
  #  -static:             Fully statically linked against musl
  #  -s:                  Strip unnecessary symbols directly during linking
  #  -Wl,-z,relro,-z,now: Enables full RELRO (symbol resolution at program startup)

  CC=musl-gcc \
  CFLAGS="-Os -fPIE -Wno-undef -fstack-protector-strong -D_FORTIFY_SOURCE=2" \
  LDFLAGS="-static -pie -s -Wl,-z,relro,-z,now" \
  ./configure \
    --enable-static \
    --enable-openpty \
    --disable-pam \
    --disable-zlib

  make -j"$(nproc)"

  do_log "info" "true" "Ultra Hardened dropbear-2025.88 build successfully from sources."

  return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
