# Automatically generate key pairs in UBOOT_SIGN_KEYDIR if they do not exist.
# The key pair is generated by the kernel-signing-keys-native recipe and is not
# stored in the sstate cache. This can be beneficial from a security standpoint,
# as it avoids unintentionally caching and distributing private keys.
# However, this behavior can lead to non-reproducible builds. For example, if
# the keys are deleted, they must be manually restored, or you must run:
#   bitbake -c cleanall kernel-signing-keys-native
# before new key pairs are generated.
#
# However, this approach is only suitable for simple or local development use
# cases. For more advanced or production-grade scenarios, a more robust solution
# is usually required—such as external signing or re-signing using e.g a HSM.

SUMMARY = "Signing keys for the kernel FIT image"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/COPYING.MIT;md5=3da9cfbcb788c80a0384361b4de20420"

require conf/image-fitimage.conf

DEPENDS += "openssl-native"

inherit native

do_fetch[noexec] = "1"
do_unpack[noexec] = "1"
do_patch[noexec] = "1"
do_configure[noexec] = "1"
do_install[noexec] = "1"

do_compile() {
	if [ "${UBOOT_SIGN_ENABLE}" = "0" ] && [ "${FIT_GENERATE_KEYS}" = "1" ]; then
		bbwarn "FIT_GENERATE_KEYS is set to 1 even though UBOOT_SIGN_ENABLE is set to 0. The keys will not be generated as they won't be used."
	fi

	if [ "${UBOOT_SIGN_ENABLE}" = "1" ] && [ "${FIT_GENERATE_KEYS}" = "1" ]; then

		# Generate keys to sign configuration nodes, only if they don't already exist
		if [ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key ] || \
			[ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".crt ]; then

			# make directory if it does not already exist
			mkdir -p "${UBOOT_SIGN_KEYDIR}"

			bbnote "Generating RSA private key for signing fitImage"
			openssl genrsa ${FIT_KEY_GENRSA_ARGS} -out \
				"${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key \
			"${FIT_SIGN_NUMBITS}"

			bbnote "Generating certificate for signing fitImage"
			openssl req ${FIT_KEY_REQ_ARGS} "${FIT_KEY_SIGN_PKCS}" \
				-key "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key \
				-out "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".crt
		fi

		# Generate keys to sign image nodes, only if they don't already exist
		if [ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_IMG_KEYNAME}".key ] || \
			[ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_IMG_KEYNAME}".crt ]; then

			# make directory if it does not already exist
			mkdir -p "${UBOOT_SIGN_KEYDIR}"

			bbnote "Generating RSA private key for signing fitImage"
			openssl genrsa ${FIT_KEY_GENRSA_ARGS} -out \
				"${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_IMG_KEYNAME}".key \
			"${FIT_SIGN_NUMBITS}"

			bbnote "Generating certificate for signing fitImage"
			openssl req ${FIT_KEY_REQ_ARGS} "${FIT_KEY_SIGN_PKCS}" \
				-key "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_IMG_KEYNAME}".key \
				-out "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_IMG_KEYNAME}".crt
		fi
	fi
}
