From 05b80be5d3ac943cc020c32ef4320393a5cb8ad6 Mon Sep 17 00:00:00 2001
From: Kenneth Johansson <kenneth@southpole.se>
Date: Fri, 11 Dec 2015 00:18:40 +0100
Subject: [PATCH] Sign the firmware image.
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

To use this the opkg package needs to be deselected.
opkg-smime package needs to be selected

CONFIG_PACKAGE_opkg-smime=y
-----------
A certificate needs to be created. Start by creating a file containing
the password.

echo "testing" >passkey.txt

Then create the cert with

openssl req -utf8 \
-newkey rsa:2048 \
-keyout privkey.pem \
-out req.pem  \
-passout file:passkey.txt \
-subj "/C=SE/ST=Stockholm/L=Skärholmen/O=Inteno/OU=broadband/CN=inteno.se"

openssl x509 -req -in req.pem \
-signkey privkey.pem \
-out cert.pem \
-passin file:passkey.txt \
-nameopt oneline,-esc_msb

you now have
  passkey.txt
  req.pem
  cert.pem
  privkey.pem

Then CONFIG_OPKGSMIME_CERT CONFIG_OPKGSMIME_KEY & CONFIG_OPKGSMIME_PASSFILE
needs to be set in openwrt .config

ex:
CONFIG_OPKGSMIME_CERT="/home/kenjo/proj/inteno/ssl/cert.pem"
CONFIG_OPKGSMIME_KEY="/home/kenjo/proj/inteno/ssl/privkey.pem"
CONFIG_OPKGSMIME_PASSFILE="/home/kenjo/proj/inteno/ssl/passkey.txt"

then rebuild.

If the cert is changed one have to clean and recompile opkg since
that package is putting the cert.pem file into the root filesystem and
it has no idea that we changed the config after it was compiled.
(that sucker cost me a lot of time as I was using the wrong cert on target)
---
 brcm63xx_ref_nand/image/Makefile | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/brcm63xx_ref_nand/image/Makefile b/brcm63xx_ref_nand/image/Makefile
index aa9346961..1d86533e8 100644
--- a/brcm63xx_ref_nand/image/Makefile
+++ b/brcm63xx_ref_nand/image/Makefile
@@ -177,6 +177,9 @@ define Image/Build/Header
 	echo "cfe $$$$(ls -l $(KDIR)/$(2) | awk '{print $$$$5}')" >> $(KDIR)/hdr
 	echo "vmlinux $$$$(ls -l $(KDIR)/$(3) | awk '{print $$$$5}')" >> $(KDIR)/hdr
 	echo "ubifs $$$$(ls -l $(KDIR)/$(4) | awk '{print $$$$5}')" >> $(KDIR)/hdr
+    ifeq ($(CONFIG_SMIMEOPT),y)
+	echo "sig 256" >> $(KDIR)/hdr
+    endif
 	cat $(KDIR)/hdr /dev/zero | head --bytes=1024 > $(KDIR)/$(1)
 endef
 
@@ -281,6 +284,16 @@ define Image/Build/ubi
 	    $(KDIR)/vmlinux.jffs2 \
 	    $(KDIR)/root.ubifs > $(BIN_DIR)/$(IHGSP_BUILD_VERSION).y
 
+# If build is signed also sign the cfe,kernel,fs part of the image.
+    ifeq ($(CONFIG_SMIMEOPT),y)
+	cat $(KDIR)/cfe$(CONFIG_BCM_CHIP_ID)_nand.v \
+	    $(KDIR)/vmlinux.jffs2 \
+	    $(KDIR)/root.ubifs | \
+	openssl dgst -sha256 -sign $(CONFIG_OPKGSMIME_KEY) \
+	-passin file:$(call qstrip,$(CONFIG_OPKGSMIME_PASSFILE)) \
+		>> $(BIN_DIR)/$(IHGSP_BUILD_VERSION).y
+    endif
+
 	# Attach checksum to combined image (.y)
 	md5sum $(BIN_DIR)/$(IHGSP_BUILD_VERSION).y |awk '{printf "%s",$$$$1}' \
 		>> $(BIN_DIR)/$(IHGSP_BUILD_VERSION).y
-- 
GitLab