summaryrefslogtreecommitdiffstats
path: root/snippets/keep_ssh_host_keys
blob: 527c99260db59d1d64f8522d37e0d62a04dc2138 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#raw
# Nifty trick to restore ssh keys without using a nochroot %post

echo "Saving ssh host keys..." > /dev/ttyS0

keys_found=no

insmod /lib/jbd.o
insmod /lib/ext3.o

mkdir -p /tmp/ssh

drives=$(list-harddrives | awk '{print $1}')
for disk in $drives; do
    DISKS="$DISKS $(fdisk -l /dev/$disk | awk '/^\/dev/{print $1}')"
done

# Try to find the keys on ordinary partitions
for disk in $DISKS; do
    name=$(basename $disk)
    mkdir -p /tmp/$name
    mount $disk /tmp/$name
    [ $? -eq 0 ] || continue # Skip to the next partition if the mount fails

    # Copy current ssh host keys out to be reused
    if [ -d /tmp/${name}/etc/ssh ]; then
        cp -a /tmp/${name}/etc/ssh/ssh_host* /tmp/ssh
        keys_found="yes"
        umount /tmp/$name
        break
    fi
    umount /tmp/$name
    rm -r /tmp/$name
done

# Try LVM if that didn't work
if [ "$keys_found" = "no" ]; then
    lvm lvmdiskscan
    vgs=$(lvm vgs | tail -n +2 | awk '{ print $1 }')
    for vg in $vgs; do
        # Activate any VG we found
        lvm vgchange -ay $vg
    done
    
    lvs=$(lvm lvs | tail -n +2 | awk '{ print "/dev/" $2 "/" $1 }')
    for lv in $lvs; do
        tmpdir=$(mktemp -d findkeys.XXXXXX)
        mkdir -p /tmp/${tmpdir}
        mount $lv /tmp/${tmpdir} || continue # Skip to next volume if this fails

        # Let's see if the keys are in there
        if [ -d /tmp/${tmpdir}/etc/ssh ]; then
            cp -a /tmp/${tmpdir}/etc/ssh/ssh_host* /tmp/ssh/
            keys_found="yes"
            umount /tmp/${tmpdir}
            break # We're done!
        fi
        umount /tmp/${tmpdir}
        rm -r /tmp/${tmpdir}
    done
    
    # And clean up..
    for vg in $vgs; do
        lvm vgchange -an $vg
    done
fi

# Loop until the ssh rpm is installed
if [ "$keys_found" = "yes" ]; then
    while : ; do
        sleep 10
        if [ -d /mnt/sysimage/etc/ssh ] ; then
            cp -f /tmp/ssh/ssh_host* /mnt/sysimage/etc/ssh/
            logger "SSH-HOST-KEY copied to newly installed system"
            break
        fi
    done &
fi
#end