backup.pl: Fix restores for ipsec backups before regen was fixed

Message ID 20250429144219.33884-1-adolf.belka@ipfire.org
State Accepted
Commit f0acc9e4a3a446307684dfe9ee9031313407546a
Headers
Series backup.pl: Fix restores for ipsec backups before regen was fixed |

Commit Message

Adolf Belka April 29, 2025, 2:42 p.m. UTC
  - Prior to the ipsec host cert regen fix, the backup did not include the serial or the
   index.txt files.
- After the ipsec regen patch set, if a backup from before the change is retsored then
   the serial and index.attr could end up not matching. This would break the ipsec regen
   again.
- All backups before the change will have hostcerts with serial numbers of 1.
- This patch extracts the serial number from the restored hostcert.pem. If the serial
   number is 1 and if the existing serial number file does not contain 02, then the
   serial file contents are replaced by 02 and the index.txt contents are deleted.
- If the restored hostcert.pem  serial number is greater than 1 then the backup will
   contain the serial anf index.txt files.
- If the restored hostcert.pem serial number is 1 and the serial file contains 02 then
   the ipsec regen will work correctly.

Fixes: bug13737
Tested-by: Adolf Belka <adolf.belka@ipfire.org>
Signed-off-by: Adolf Belka <adolf.belka@ipfire.org>
---
 config/backup/backup.pl | 12 ++++++++++++
 1 file changed, 12 insertions(+)
  

Patch

diff --git a/config/backup/backup.pl b/config/backup/backup.pl
index 0cfbd4fc3..301faa3df 100644
--- a/config/backup/backup.pl
+++ b/config/backup/backup.pl
@@ -307,6 +307,18 @@  restore_backup() {
 	# start collectd after restore
 	/etc/rc.d/init.d/collectd start
 
+	# Check if ipsec hosctcert.pem serial number is 1 and if the serial file does not contain 02
+	# In this case set the serial file to 02 and empty the index.txt file
+	ARR=()
+	while IFS= read -r line; do
+		ARR+=("$line")
+	done <<< "$(openssl x509 -in /var/ipfire/certs/hostcert.pem -noout -text)"
+       if [ $(echo ${ARR[3]} | sed -E 's,^[^0-9]*([0-9]+).*$,\1,') = 1 ] && \
+			[ $(expr $(cat "/var/ipfire/certs/serial") + 0) != 2 ]; then
+		sed -i "s/.*/02/" /var/ipfire/certs/serial
+		sed -i 'd' /var/ipfire/certs/index.txt
+	fi
+
         # Restart ipsec if enabled
         # This will ensure that the restored certs and secrets etc are loaded and used
         if [ $(grep -c "ENABLED=on" /var/ipfire/vpn/settings) -eq 1  ] ; then