summaryrefslogtreecommitdiff
path: root/phonehome.sh
blob: f469d6c47ad86890771eebcb72c5da2dc61cf3ec (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
#!/bin/bash
#
# Alternate Access Tunnel for Remote Hosts
#
# Opens an SSH connection to a central aggregation host and forwards the local
# SSH port over that connection. This allows remote connections to the server
# from the central aggregation host. In the absence of true OOB recovery
# systems this mechanism provides some OOB recovery capability provided the
# entire internet connection is not down.
#

KEY=/root/.ssh/phonehome.id_rsa
CRONTAB=/var/spool/cron/crontabs/root
CRON_ENTRY="*/5 * * * * /root/phonehome.sh"

# Alt host hedges against DNS being down if the default DNS server is on the
# wrong side of a collapsed ssh tunnel
#
# Grab only answers starting with numbers since we're trying to resolve the IP
# itself not the hostname (in the absence of normal DNS). Grab the first numeric
# answer in the case of multiple records
HOST_IP=$(dig +short @8.8.8.8 phonehome.crute.me | awk '/^[0-9]+/ { print $0; exit; }')

function start_autossh {
    autossh -f \
        -gNxCT \
        -l phonehome -p 4321 $1 \
        -i $KEY \
        -R $REMOTE_PORT:localhost:22
}

if [ ! -f /etc/default/phonehome ]; then
    echo "echo 'REMOTE_PORT=1234' > /etc/default/phonehome"
    exit 1
else
    source /etc/default/phonehome
fi

if ! grep 'phonehome.sh' $CRONTAB 2>&1 > /dev/null; then
    echo "Not in crontab, adding"
    echo "$CRON_ENTRY" >> $CRONTAB
else
    if ! grep -F "$CRON_ENTRY" $CRONTAB 2>&1 > /dev/null; then
        echo "In crontab but not correct, fixing"
        sed -i '/phonehome.sh/d' $CRONTAB
        echo "$CRON_ENTRY" >> $CRONTAB
    fi
fi

if ! pgrep autossh > /dev/null; then
    start_autossh $HOST_IP
fi