host info updates
[distro-setup] / dynamic-ip-update
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to switch
7 # its license to GPL.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23
24 set -e; . /usr/local/lib/bash-bear; set +e
25 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
26
27 this_file="$(readlink -f -- "${BASH_SOURCE[0]}")"
28 readonly this_file
29 this_dir="${this_file%/*}"
30 readonly this_dir
31 cd "$this_dir"
32
33 usage() {
34 cat <<EOF
35 Usage: ${0##*/} [-f]
36 Update ip in remote nameserver.
37
38 -f Force update even if ip hasn't changed.
39 -h|--help Print help and exit.
40
41 Note: Uses util-linux getopt option parsing: spaces between args and
42 options, short options can be combined, options before args.
43 EOF
44 exit $1
45 }
46
47 ##### begin command line parsing ########
48
49 # ensure we can handle args with spaces or empty.
50 ret=0; getopt -T || ret=$?
51 [[ $ret == 4 ]] || { echo "Install util-linux for enhanced getopt" >&2; exit 1; }
52
53 force=false # default
54 temp=$(getopt -l help hf "$@") || usage 1
55 eval set -- "$temp"
56 while true; do
57 case $1 in
58 -f) force=true ;;
59 --) shift; break ;;
60 *) echo "$0: unexpected args: $*" >&2 ; usage 1 ;;
61 esac
62 shift
63 done
64
65 ##### end command line parsing ########
66
67 main() {
68
69 fqdn=$(hostname -f)
70 domaintmp=${fqdn#*.}
71 hostnametmp=${fqdn%%.*}
72 # i for internet
73 fqdn=${hostnametmp}i.${domaintmp}
74
75 up4=false
76
77 if ! tmp=$(ip -4 route get 85.119.83.50 2>/dev/null); then
78 # our internet is down
79 if [[ $INVOCATION_ID ]]; then
80 return 0
81 else
82 echo $0: failed to get route, giving up
83 exit 0
84 fi
85 fi
86 read -r _ _ gateway _ ifdev _ <<<"$tmp"
87
88 case $gateway in
89 10.2.0.1)
90 dyndomain=b8.nz
91 ;;
92 *)
93 return 0
94 ;;
95 esac
96
97 # We check if we are at home by testing gateway ssh
98 # fingerprint. However, if we found in the past that we are, I dont
99 # like to spam its logs with ssh login attempts, so just check if our
100 # gateway interface has an increasing amount of packets sent +
101 # received from last time.
102 athome=false
103 if [[ -s /dev/shm/dynamic-ip-update-state ]]; then
104 oldbytes=$(cat /dev/shm/dynamic-ip-update-state)
105 newbytes=$(awk '$1 == "'$ifdev':" {print $2 + $10}' /proc/net/dev)
106 if [[ $oldbytes == [1-9]* ]] && (( newbytes >= oldbytes )); then
107 athome=true
108 printf "%s\n" "$newbytes" >/dev/shm/dynamic-ip-update-state
109 fi
110 fi
111 if ! $athome && timeout -s 9 5 ssh-keyscan -p 2220 -t rsa $gateway 2>/dev/null | grep -qFx "[$gateway]:2220 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCH+/h1dGEfKEusBblndU2e6QT4wLCm5+yqr/sqh/0X9YfjR7BfWWm8nNmuP55cYc+Wuf5ljB1H1acXEcsl1y8e0j3agHfF0V74FE1N1zz5nn2Ep8NHnmqgEhza38ZxMPh+4p3X7zklEKU7+3SzybKBi8sg0wLzlS2LM0JaUN80zR2sK11Kye3dURUXPk78u5wodOkgcEYRwSYaDMJlUzWP+poRXIDJwFaMQnwmxbl/c84yOyaU0x/d6hFwoRscWecihX+vvBNeSyxR4xr2HDOyUWwJkctyAgt2p7w3tfkXOKcCRzTAjGVIMQLTvo0sG/yJbcyHoEFdFybCsgDvfyYn"; then
112 athome=true
113 awk '$1 == "'$ifdev':" {print $2 + $10}' /proc/net/dev > /dev/shm/dynamic-ip-update-state
114 fi
115
116
117 if $athome; then
118 if ! cur4="$(dig +short $dyndomain @iankelling.org | tail -1)"; then
119 if [[ ! $INVOCATION_ID ]]; then
120 echo "$0: dig failed. internet looks down. giving up"
121 fi
122 return 0
123 fi
124 if ip4=$(curl --connect-timeout 10 -s4 https://iankelling.org/cgi/pubip); then
125 if $force || [[ $cur4 && $ip4 && $cur4 != "$ip4" ]]; then
126 up4=true # update ipv4
127 fi
128 fi
129 fi
130
131 # may not be set yet so allow fail
132 cur6="$(host -4 -t aaaa $fqdn iankelling.org | sed -rn 's/.*has IPv6 address (.*)/\1/p;T;q')" ||:
133
134 up6=false
135
136 out6=$(curl --connect-timeout 10 -s6 https://iankelling.org/cgi/pubip) ||: # failure allowed if we have no ipv6
137
138 if [[ $out6 ]]; then
139 dev=$(ip -o a show to $out6 | awk '{print $2}')
140 # we use slaac with privacy extension, so get our less private more permanent address
141 mac=$(cat /sys/class/net/$dev/address)
142
143 IFS=: read -ra f <<<$mac; set -- ${f[@]}
144 ip6=${out6%:*:*:*:*}:$(printf %x $((0x$1 + 2)))$2:$3'ff:fe'$4:$5$6
145 # in case we aren't using slaac
146 if ! ip a | grep "^ *inet6 $ip6/" &>/dev/null; then
147 ip6=$out6
148 fi
149 fi
150
151 if $force || [[ $cur6 != "$ip6" ]]; then
152 up6=true
153 fi
154
155 # if we failed to get our ipv6 addr, we probably have ipv6
156 # connectivity problem.
157 if [[ ! $ip6 ]]; then
158 ip_arg=-4
159 fi
160
161 if ! $up4 && ! $up6; then
162 return 0
163 fi
164
165 # note, a simpler way to do this would be to ssh and use
166 # "${SSH_CLIENT%% *}
167 # to update bind if needed.
168
169 tmpf=$(mktemp)
170 cat >>$tmpf <<EOF
171 server iankelling.org
172 zone b8.nz
173 EOF
174
175 if $up4; then
176 cat >>$tmpf <<EOF
177 update delete $dyndomain. A
178 update add $dyndomain. 300 A $ip4
179 EOF
180 fi
181
182 if $up6; then
183 if [[ $ip6 ]]; then
184 cat >>$tmpf <<EOF
185 update delete $fqdn. AAAA
186 update add $fqdn. 60 AAAA $ip6
187 EOF
188 else
189 cat >>$tmpf <<EOF
190 update delete $fqdn. AAAA
191 EOF
192 fi
193 fi
194
195 cat >>$tmpf <<EOF
196 show
197 send
198 answer
199 quit
200 EOF
201
202 chronic nsupdate $ip_arg -k /p/c/machine_specific/vps/filesystem/etc/bind/Kb8.nz.*.private <$tmpf || nsupdate_fails=$((nsupdate_fails + 1))
203 sed -i 's/^server .*/server bk.b8.nz/' $tmpf
204 chronic nsupdate $ip_arg -k /p/c/machine_specific/vps/filesystem/etc/bind/Kb8.nz.*.private <$tmpf || nsupdate_fails=$((nsupdate_fails + 1))
205 if (( nsupdate_fails > nsupdate_fail_limit )); then
206 echo error: nsupdate is persistently failing >&2
207 exit 1
208 fi
209 rm -f $tmpf
210 }
211
212 loop-main() {
213 while true; do
214 main
215 sleep 30
216 done
217 }
218
219 nsupdate_fails=0
220 if [[ $INVOCATION_ID ]]; then
221 nsupdate_fail_limit=10
222 loop-main
223 else
224 nsupdate_fail_limit=0
225 main
226 fi
227
228 exit 0
229
230
231 # # # persistent initial setup for this:
232 # # # create files in /a/c/machine_specific/vps/filesystem/etc/bind
233 # # # note, conflink also does some group ownership stuff.
234 # mkc /p/c/machine_specific/vps/filesystem/etc/bind
235 # sudo dnssec-keygen -a HMAC-SHA512 -b 512 -n HOST b8.nz
236 # user=$(id -un)
237 # sudo chown $user:$user *
238
239
240 # f=key.b8.nz
241 # cat >$tmpf <<EOF
242 # key b8.nz. {
243 # algorithm HMAC-SHA512;
244 # secret "$(awk '$1 == "Key:" {print $2}' Kb8.nz.*.private)";
245 # };
246 # EOF
247
248 # chmod 640 [kK]*
249
250 # # push here?
251 # #myunison -ob li
252 # #ssh li conflink
253 # ssh li.b8.nz systemctl reload named
254
255
256 # # b8.nz has address 65.96.178.16
257 # # b8.nz has IPv6 address 2601:197:600:6efb:82fa:5bff:fe1c:6ecf