summaryrefslogtreecommitdiff
path: root/archive/bin/smtptun
blob: 4951dcefb05ae510bc921e81b3a99115970558ee (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
#!/bin/sh

# fix $HOME when run from xinetd (which does run it as root...)
if [ "$HOME" = "/" -o "$HOME" = "" ]; then
    HOME="/root"
    export HOME
fi

# set up standard environment
. $HOME/.shenv

# Make a tunnel with SSH to send e-mail via the SDF mail exchanger,
# and then netcat to that tunnel.  Designed to be run by xinetd.

# An alternative approach is to just run `ssh foo@bar nc ..' but doing
# it with a port-forward means that our SSH can be restricted to the
# command rrsync and a particular port-forward, rather than netcat so
# we can use one SSH key for both purposes.

# Interesting notes for doing this on Windows:
# <http://www.greenend.org.uk/rjk/sshfwd/>

SOCKET="$HOME/tmp/smtptun_sock"
ALTSOCKET="/tmp/ssh-swhitton-spw@ma.sdf.org:22"
REMHOST="spw@ma.sdf.org"
FORWARD="-L localhost:8025:mx.sdf.org:25"
ID="-i $HOME/.ssh/id_rsa"

# First see if I'm SSHing to the MetaArray already.  Requires running
# as root in order to be able to command the socket to add the port
# forward.

# if ssh -O check -S $ALTSOCKET $REMHOST 2>/dev/null; then
#     # Check the port isn't already bound ...
#     if ! ssh -O check -S $SOCKET $REMHOST 2>/dev/null; then
#         ssh -O forward $FORWARD -S $ALTSOCKET $REMHOST
#     fi
# else

    # Now see if another invocation of this script has already constructed a tunnel.
    if ! ssh -O check -S $SOCKET $REMHOST 2>/dev/null; then

        # Okay, we'd better set-up a tunnel.  Make it only accessible from
        # localhost and have it time out after two minutes of no e-mails
        # getting sent down it.

        # Due to an OpenSSH bug
        # <https://bugzilla.mindrot.org/show_bug.cgi?id=1988>, we
        # persist the socket for only five seconds.  The following SSH
        # process hangs on to STDERR, which means this script doesn't
        # exit once the netcat command is finished.

        ssh -M -S $SOCKET -o "ControlPersist=5s" \
            -f -N $FORWARD $REMHOST $ID

    fi
# fi

# Now connect to the tunnel we just made.

nc localhost 8025

# Remove forwarding from swhitton's connection if we added it, and no
# other script invocations are using it (to prevent a situation where
# the other script has started and passed the if-statement to not
# construct the tunnel, but hasn't started netcat yet (if it's already
# started netcat, then it's safe from the -O cancel we do here).  A
# crude check.

# if ssh -O check -S $ALTSOCKET $REMHOST 2>/dev/null; then
#     us=$(basename $0)
#     count=$(pgrep $us | wc -l)
#     if ! [ "$count" -gt 3 ]; then
#         ssh -O cancel $FORWARD -S $ALTSOCKET $REMHOST
#     fi
# fi