-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathprotonwire
executable file
·2739 lines (2458 loc) · 94.5 KB
/
protonwire
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# SPDX-License-Identifier: GPL-3.0
# SPDX-FileCopyrightText: 2023 Prasad Tengse <[email protected]>
# shellcheck disable=SC2317
set -o pipefail
if [[ ${BASH_VERSINFO[0]} -lt 4 ]]; then
printf "protonwire requires Bash version >= 4.2" 1>&2
exit 1
elif [[ ${BASH_VERSINFO[1]} -eq 4 ]] && [[ ${BASH_VERSINFO[1]} -lt 2 ]]; then
printf "protonwire requires Bash version >= 4.2" 1>&2
exit 1
fi
trap __cleanup_background_tasks EXIT
trap __sigterm_handler SIGTERM
trap __sigint_handler SIGINT
function __sigterm_handler() {
log_warning "Received SIGTERM, exiting..."
if __protonvpn_disconnect; then
log_debug "Helathcheck errors - $__PROTONWIRE_HC_ERRORS"
if [[ $__PROTONWIRE_HC_ERRORS == "0" ]]; then
exit 0
else
exit 1
fi
fi
}
function __sigint_handler() {
log_warning "Received SIGINT, exiting..."
__protonvpn_disconnect
exit 1
}
function __print_version() {
#diana::dynamic:version:begin#
local PROTONWIRE_VERSION="dev"
local PROTONWIRE_COMMIT="HEAD"
#diana::dynamic:version:end#
printf "protonwire version %s(%s)\n" "$PROTONWIRE_VERSION" "$PROTONWIRE_COMMIT"
}
function __is_stdout_colorable() {
if [[ -n ${CLICOLOR_FORCE} ]] && [[ ${CLICOLOR_FORCE} != "0" ]]; then
return 0
elif [[ -n ${NO_COLOR} ]] || [[ ${CLICOLOR} == "0" ]] || [[ ${TERM} == "dumb" ]] || [[ ${TERM} == "linux" ]]; then
return 1
fi
if [[ -t 2 ]]; then return 0; fi
return 1
}
function __logger_core_event_handler() {
[[ $# -lt 2 ]] && return 1
local lvl_caller="${1:-info}"
case ${lvl_caller} in
trace)
level="0"
;;
debug)
level="10"
;;
info)
level="20"
;;
success)
level="20"
;;
notice)
level="25"
;;
warning)
level="30"
;;
error)
level="40"
;;
*)
level="100"
;;
esac
if [[ ${LOG_LVL:-20} -gt "${level}" ]]; then
return
fi
shift
local lvl_msg="$*"
local lvl_color
local lvl_colorized
local lvl_reset
if __is_stdout_colorable; then
lvl_colorized="true"
# shellcheck disable=SC2155
lvl_reset="\e[0m"
fi
local lvl_prefix
local lvl_string
if [[ ${LOG_FMT:-pretty} == "pretty" ]] && [[ -n ${lvl_colorized} ]]; then
lvl_string="[•]"
elif [[ ${LOG_FMT} = "full" ]] || [[ ${LOG_FMT} = "long" ]]; then
if [[ ${LOG_LVL:-20} -lt 20 ]]; then
printf -v lvl_prefix "%(%FT%TZ)T (%-4s) " -1 "${BASH_LINENO[1]}"
else
printf -v lvl_prefix "%(%FT%TZ)T" -1
fi
elif [[ ${LOG_FMT} = "journald" ]] || [[ ${LOG_FMT} = "journal" ]]; then
if [[ ${LOG_LVL:-20} -lt 20 ]]; then
printf -v lvl_prefix "(%-4s) " "${BASH_LINENO[1]}"
fi
fi
# Define level, color and timestamp. By default we do not show log level and timestamp.
# However, if LOG_FMT is set to "full" or "long", we will enable long format with timestamps
case "$lvl_caller" in
trace)
# if lvl_string is set earlier, that means LOG_FMT is default or pretty
# skip timestamp & level. Otherwise append level name to lvl_prefix.
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[TRACE ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;246m"
;;
debug)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[DEBUG ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;250m"
;;
info)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[INFO ]"
[[ -n "${lvl_colorized}" ]] && lvl_reset=""
;;
success)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[SUCCESS ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;83m"
;;
notice)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[NOTICE ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;81m"
;;
warning)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[WARNING ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;214m"
;;
error)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[ERROR ]"
[[ -n "${lvl_colorized}" ]] && lvl_color="\e[38;5;197m"
;;
*)
[[ -z ${lvl_string} ]] && lvl_string="${lvl_prefix}[UNKNOWN ]"
[[ -n "${lvl_colorized}" ]] && lvl_reset=""
;;
esac
printf "${lvl_color}%s %s ${lvl_reset}\n" "${lvl_string}" "$lvl_msg"
}
function log_trace() {
__logger_core_event_handler "trace" "$@"
}
function log_debug() {
__logger_core_event_handler "debug" "$@"
}
function log_info() {
__logger_core_event_handler "info" "$@"
}
function log_success() {
__logger_core_event_handler "success" "$@"
}
function log_warning() {
__logger_core_event_handler "warning" "$@"
}
function log_notice() {
__logger_core_event_handler "notice" "$@"
}
function log_error() {
__logger_core_event_handler "error" "$@"
}
function log_variable() {
local var="$1"
local __msg_string
printf -v __msg_string "%-${4:-35}s : %s" "${var}" "${!var:-NA}"
__logger_core_event_handler "debug" "${__msg_string}"
}
function log_kv_pair() {
local __msg_string
printf -v __msg_string "%-${4:-25}s : %s" "${1:-NA}" "${2:-NA}"
__logger_core_event_handler "debug" "${__msg_string}"
}
function log_tail() {
local line prefix
[[ -n $1 ]] && prefix="($1) "
while read -r line; do
__logger_core_event_handler "trace" "$prefix$line"
done
}
function __cleanup_background_tasks() {
declare -a pending_tasks
readarray -t pending_tasks < <(jobs -p)
if [[ ${#pending_tasks[@]} -gt 1 ]]; then
log_debug "Cleaning up background tasks - ${pending_tasks[*]:-NONE}"
for pid in "${pending_tasks[@]}"; do
log_debug "Stopping PID - $pid with SIGTERM"
if ! kill -s TERM "$pid" >/dev/null 2>&1; then
log_warning "Failed to stop PID - $pid"
fi
done
fi
}
function has_command() {
if command -v "$1" >/dev/null; then return 0; else return 1; fi
}
function __is_valid_ipv4() {
local IPV4_REGEX="(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))"
local IPV4_REGEX_SUBNET="([0-9]|[12][0-9]|3[012])"
local address
while [[ ${1} != "" ]]; do
case $1 in
--cidr | --subnet)
IPV4_REGEX="${IPV4_REGEX}/${IPV4_REGEX_SUBNET}"
;;
--ip) ;;
-*)
log_error "Unknown option: $1"
return 1
;;
*)
address="$1"
;;
esac
shift
done
if [[ $address =~ ^$IPV4_REGEX$ ]]; then
return 0
fi
return 1
}
function __is_valid_ipv6() {
local IPV6_REGEX="(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))"
local IPV6_REGEX_SUBNET="([0-9]{1,2}|1[01][0-9]|12[0-8])"
local address
while [[ ${1} != "" ]]; do
case $1 in
--cidr | --subnet)
IPV6_REGEX="${IPV6_REGEX}/${IPV6_REGEX_SUBNET}"
;;
--ip) ;;
-*)
log_error "Unknown option: $1"
return 1
;;
*)
address="$1"
;;
esac
shift
done
if [[ $address =~ ^$IPV6_REGEX$ ]]; then
return 0
fi
return 1
}
function __is_valid_ipcheck_url() {
log_info "Verifying IPCHECK_URL - ${IPCHECK_URL}"
if [[ -e ${__PROTONWIRE_HCR} ]]; then
if ! rm -f "${__PROTONWIRE_HCR}" 2>&1 | log_tail "rm ipcheck-response"; then
log_error "Failed to remove existing IP chck response file - ${__PROTONWIRE_HCR}"
return 1
fi
fi
case ${IPCHECK_URL} in
http://*)
log_error "IPCHECK_URL must be secure (https://)"
return 1
;;
https://*)
local curl_rc="-1"
local curl_opts="-sSfL"
if __is_bool_true "${DEBUG}"; then
curl_opts="-vfL"
fi
{
curl "${curl_opts}" -m 20 -A 'protonwire/v7' -o "${__PROTONWIRE_HCR}" \
"${IPCHECK_URL}" 2>&1 | log_tail "curl-ipcheck-url" &
}
wait $!
curl_rc="$?"
if [[ $curl_rc == "0" ]]; then
declare -a ip_check_response
readarray -t ip_check_response <"${__PROTONWIRE_HCR}"
if __is_valid_ipv4 "${ip_check_response[0]}"; then
log_debug "IP Check endpoint returned ${ip_check_response[0]}(IPv4)"
return 0
elif __is_valid_ipv6 "${ip_check_response[0]}"; then
log_debug "IP Check endpoint returned ${ip_check_response[0]}(IPv6)"
return 0
else
log_error "IP Check endpoint returned invalid IP address(${ip_check_response[0]})"
return 1
fi
elif [[ $curl_rc == 6 ]]; then
log_error "Failed to validate ipcheck endpoint ${IPCHECK_URL} (dns error)"
return 1
elif [[ $curl_rc == 28 ]]; then
log_error "Failed to validate ipcheck endpoint ${IPCHECK_URL} (timeout)"
return 1
else
log_error "Failed to validate ipcheck endpoint ${IPCHECK_URL} (curl exit code: ${curl_rc})"
return 1
fi
;;
*)
log_error "Invalid IPCHECK_URL - $IPCHECK_URL"
return 1
;;
esac
}
function __is_ipv6_disabled() {
if [[ $(cat /sys/module/ipv6/parameters/disable) == "1" ]]; then
return 0
elif [[ $(cat /sys/module/ipv6/parameters/disable_ipv6) == "1" ]]; then
return 0
elif [[ $(sysctl -n net.ipv6.conf.all.disable_ipv6) == "1" ]]; then
return 0
elif [[ $(sysctl -n net.ipv6.conf.default.disable_ipv6) == "1" ]]; then
return 0
fi
return 1
}
function __is_bool_true() {
local bool="${1,,}"
case "${bool,,}" in
true | yes | enable | enabled | on | 1)
return 0
;;
esac
return 1
}
function __is_skip_dns_config() {
if __is_bool_true "${SKIP_DNS_CONFIG}"; then return 0; else return 1; fi
}
function __has_notify_socket() {
if [[ -n $NOTIFY_SOCKET ]]; then
if [[ -S ${NOTIFY_SOCKET} ]]; then
return 0
else
log_warning "Notify socket '${NOTIFY_SOCKET}' is not a socket!"
fi
fi
return 1
}
function __systemd_notify() {
local status="${1}"
if [[ -z ${1} ]]; then
log_error "Notify message is not defined or empty!"
return 1
fi
if printf "%s" "${status}" |
timeout 3s nc -w 0 -uU "$NOTIFY_SOCKET" 2>&1 | log_tail "nc-notify"; then
return 0
else
log_debug "nc failed to send status ${status}"
fi
return 1
}
function __sd_notify_checks() {
local errs=0
if [[ -n $NOTIFY_SOCKET ]]; then
if [[ -S $NOTIFY_SOCKET ]]; then
log_debug "NOTIFY_SOCKET is set to $NOTIFY_SOCKET"
if ! __systemd_notify "STATUS=Initializing"; then
log_error "sd_notify socket is not working!"
((++errs))
fi
else
log_warning "NOTIFY_SOCKET is set but not a socket"
fi
fi
if [[ $errs -eq 0 ]]; then
return 0
fi
return 1
}
function __check_caps() {
if capsh --has-p=CAP_NET_ADMIN >/dev/null 2>&1; then
log_debug "Can use CAP_NET_ADMIN capability"
return 0
else
log_error "CAP_NET_ADMIN capability is not available!"
log_error "If running as podman/docker use --cap-add=CAP_NET_ADMIN flag."
log_error "If running in Kubernetes, See https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-capabilities-for-a-container"
fi
return 1
}
function __check_tools() {
local errs=0
log_debug "Checking requirements"
declare -a commands=(
"curl" # curl
"jq" # jq
"ip" # iproute2
"capsh" # libcap/libcap2-bin (pulled by iproute2)
"timeout" # coreutils
"wg" # wireguard-tools | wireguard-tools-wg
"sysctl" # procps
"flock" # flock | linux-utils
)
declare -a missing_commands
for command in "${commands[@]}"; do
if ! has_command "$command"; then
((++errs))
missing_commands+=("$command")
fi
done
if [[ ${#missing_commands[@]} -gt 0 ]]; then
log_error "Following commands are missing - ${missing_commands[*]}"
((++errs))
fi
if [[ $errs -gt 0 ]]; then
return 1
fi
}
function __run_checks() {
local errs=0
if ! __check_tools; then
return 1
fi
__detect_paths
if [[ $(sysctl -n net.ipv4.conf.all.rp_filter) != "2" ]]; then
((++errs))
log_error "Invalid sysctl, net.ipv4.conf.all.rp_filter!=2"
log_error "If using docker/podman add --sysctl net.ipv4.conf.all.rp_filter=2 flag to your run command"
log_error "If using docker-compose add 'net.ipv4.conf.all.rp_filter: 2' under 'sysctls' section for protonvpn service."
log_error "If using Kubernetes see https://kubernetes.io/docs/tasks/administer-cluster/sysctl-cluster/ to set sysctl values."
fi
# check if any interfaces have reserved ip addresses
declare -a ip_on_ifaces
readarray -t ip_on_ifaces < <(ip -4 --json addr show | jq -r '.[] | select(.ifname!="protonwire0") | .addr_info[] | .local' 2>/dev/null)
if [[ ${#ip_on_ifaces[@]} -lt 1 ]]; then
log_error "There are no interfaces with IP addresses"
((++errs))
else
for iface_ip in "${ip_on_ifaces[@]}"; do
log_debug "Checking if IP on other interface is reserved - $iface_ip"
if [[ $iface_ip == "10.2.0.1" ]]; then
log_error "One of the interfaces has IP - 10.2.0.1, which is reserved for server"
((++errs))
fi
if [[ $iface_ip == "10.2.0.2" ]]; then
log_error "One of the interfaces has IP - 10.2.0.2, which is reserved for client"
((++errs))
fi
done
fi
if [[ $IPCHECK_URL != "https://icanhazip.com/" ]]; then
if ! __is_valid_ipcheck_url; then
((++errs))
fi
else
log_notice "Skipped validating default IPCHECK_URL"
fi
if ! __check_caps; then
((++errs))
fi
if [[ $errs -eq 0 ]]; then
return 0
fi
return 1
}
# resolvconf hook. openresolv cannot be used because it uses mv sematics
# and it is unsuitable for container management systems which bind mount /etc/resolv.conf.
function __resolvconf_up_hook() {
local resolvconf_cur
resolvconf_cur="$(cat /etc/resolv.conf 2>/dev/null)"
if [[ $resolvconf_cur != *"nameserver 10.2.0.1"* ]]; then
log_debug "Updating /etc/resolv.conf"
if ! cp --force /etc/resolv.conf /etc/resolv.conf.protonwire 2>&1 | log_tail "resolvconf-backup"; then
log_error "Failed to create backup of /etc/resolv.conf"
return 1
fi
local resolv_conf_vpn
printf -v resolv_conf_vpn "# This file is managed by protonwire. DO NOT EDIT.\n"
printf -v resolv_conf_vpn "%s# If you do not wish to use ProtonVPN DNS servers,\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# disable it via one of the following.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# - Set 'SKIP_DNS_CONFIG' environment variable to '1'.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# - Use '--skip-dns-config' CLI flag.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s#\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# Your old DNS configration has been backed up at /etc/resolv.conf.protonwire.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# Do not delete it, as it will cause issues when disconnecting.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s# protonvpn will automatically restore your previous DNS config upon disconnect.\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s#\n" "$resolv_conf_vpn"
printf -v resolv_conf_vpn "%s%s\n" "$resolv_conf_vpn" "nameserver 10.2.0.1"
if printf "%s" "${resolv_conf_vpn}" >/etc/resolv.conf 2>/dev/null; then
log_success "DNS is is set to 10.2.0.1 via /etc/resolv.conf"
return 0
else
log_error "Failed to update /etc/resolv.conf"
return 1
fi
else
log_success "DNS is already set to 10.2.0.1 in /etc/resolv.conf"
return 0
fi
}
function __resolvconf_down_hook() {
local resolvconf_cur
local resolvconf_bak
resolvconf_cur="$(cat /etc/resolv.conf 2>/dev/null)"
resolvconf_bak="$(cat /etc/resolv.conf.protonwire 2>/dev/null)"
if [[ $resolvconf_cur == *"nameserver 10.2.0.1"* ]]; then
local errs=0
if [[ $resolvconf_bak != *"nameserver"* ]]; then
log_error "/etc/resolv.conf.protonwire is empty or invalid or does not exist"
((++errs))
fi
log_debug "Restoring /etc/resolv.conf"
if cat /etc/resolv.conf.protonwire >/etc/resolv.conf 2>/dev/null; then
log_success "Reverted DNS configuration"
else
log_error "Failed to revert /etc/resolv.conf"
((++errs))
fi
if [[ -f /etc/resolv.conf.protonwire ]]; then
log_debug "Removing backup /etc/resolv.conf.protonwire"
if ! rm -f /etc/resolv.conf.protonwire; then
log_error "Failed to remove backup /etc/resolv.conf.protonwire"
((++errs))
fi
else
log_error "Backup resolv.conf not found - /etc/resolv.conf.protonwire"
((++errs))
fi
if [[ $errs -eq 0 ]]; then
return 0
fi
return 1
else
log_success "DNS is not configured to use 10.2.0.1 in /etc/resolv.conf"
fi
}
function __detect_paths() {
declare -g __PROTONWIRE_SRV_INFO_FILE="/tmp/protonwire.server.json"
declare -g __PROTONWIRE_HCR="/tmp/protonwire.hc.response"
declare -g __PROTONWIRE_HCS="/tmp/protonwire.hc.status"
log_variable "__PROTONWIRE_SRV_INFO_FILE"
log_variable "__PROTONWIRE_HCR"
log_variable "__PROTONWIRE_HCS"
}
# looper command
function protonvpn_looper_cmd() {
if ! __run_checks; then
log_error "Please fix the errors above and try again!"
return 1
fi
log_variable "IPCHECK_THRESHOLD"
log_variable "IPCHECK_INTERVAL"
if __protonvpn_connect; then
if [[ $IPCHECK_INTERVAL != "0" ]]; then
log_info "Verifying connection"
local verify_attemps=0
local max_verify_attemps="${IPCHECK_THRESHOLD:-5}"
while [[ $verify_attemps -lt $max_verify_attemps ]]; do
((++verify_attemps))
if __protonvpn_verify_connection; then
log_success "Connection verified!"
break
else
log_error "Retry ($verify_attemps/$max_verify_attemps) after 2 seconds"
sleep 2 &
wait $!
fi
done
if [[ $verify_attemps -ge $max_verify_attemps ]]; then
log_error "Failed to verify connection!"
if __has_notify_socket; then
__systemd_notify "STATUS=Failed to verify connection - ${PROTONVPN_SERVER}"
fi
__protonvpn_disconnect
return 1
fi
else
log_warning "Not verifying connection, as healthchecks are disabled"
fi
else
log_error "Failed to connect to ${PROTONVPN_SERVER:-NA}"
if [[ -z $(ip link show protonwire0 type wireguard 2>/dev/null) ]]; then
log_debug "Wireguard interface for protonwire is not present."
return 1
fi
if __has_notify_socket; then
__systemd_notify "STATUS=Failed to connect to - ${PROTONVPN_SERVER:-NA}"
fi
__protonvpn_disconnect
return 1
fi
local sleep_int=120
# configure ping interval
if [[ -n $IPCHECK_INTERVAL ]] && [[ $IPCHECK_INTERVAL != "0" ]]; then
sleep_int="$IPCHECK_INTERVAL"
else
log_debug "Using default check interval ${sleep_int}s"
fi
# Initial ready notification.
if __has_notify_socket; then
log_notice "Notifying systemd that we are ready"
if ! __systemd_notify "READY=1"; then
log_error "Failed to notify systemd!"
__protonvpn_disconnect
return 1
fi
else
log_debug "No systemd notify socket found, skiping READY=1 notification"
fi
if [[ $IPCHECK_INTERVAL == "0" ]]; then
log_warning "Healthchecks are disabled"
log_info "Listening for signals"
__PROTONWIRE_HC_ERRORS=0
while :; do
if [[ $__PROTONWIRE_DISCONNECTING == "true" ]]; then
log_debug "Disconnect handler is active, exiting loop"
break
fi
sleep "${sleep_int:-120}" &
wait $!
done
else
log_info "Checking status - every ${sleep_int:-120} seconds"
declare -g __PROTONWIRE_HC_ERRORS=0
while :; do
if [[ $__PROTONWIRE_DISCONNECTING == "true" ]]; then
log_debug "Disconnect handler is active, exiting loop"
break
fi
if [[ $__PROTONWIRE_HC_ERRORS -ge ${max_verify_attemps} ]]; then
log_error "Connection verification (${__PROTONWIRE_HC_ERRORS}/${max_verify_attemps}) failed"
if __has_notify_socket; then
__systemd_notify "Connection verification failed (${__PROTONWIRE_HC_ERRORS}/${max_verify_attemps}) "
else
log_debug "No systemd notify socket found, skiping reconnect notification"
fi
break
fi
sleep "${sleep_int:-120}" &
wait $!
if ! __protonvpn_verify_connection; then
local xt=$((__PROTONWIRE_HC_ERRORS + 1))
log_error "Failed to verify connection (${xt}/${max_verify_attemps})"
((++__PROTONWIRE_HC_ERRORS))
log_warning "Attempting to re-connect to ${PROTONVPN_SERVER}"
if __has_notify_socket; then
__systemd_notify "Attempting to re-connect to ${PROTONVPN_SERVER} (${xt}/${max_verify_attemps})"
else
log_debug "No systemd notify socket found, skiping reconnect notification"
fi
if __protonvpn_connect; then
sleep 2 & # avoid transient errors
wait $!
if ! __protonvpn_verify_connection; then
log_error "Failed to verify after re-connect"
else
log_notice "Successfully reconnected to ${PROTONVPN_SERVER}"
fi
else
log_error "Failed to re-connect to ${PROTONVPN_SERVER}"
fi
fi
done
fi
return 1
}
function __load_srvinfo_json_to_var() {
if [[ -f ${__PROTONWIRE_SRV_INFO_FILE} ]]; then
local __json_tmp
__json_tmp="$(<"${__PROTONWIRE_SRV_INFO_FILE}")"
if jq --exit-status '.Nodes' <<<"$__json_tmp" >/dev/null 2>&1; then
log_debug "__PROTONWIRE_SRV_INFO_FILE JSON valid"
declare -g __PROTONWIRE_SRV_INFO="$__json_tmp"
return 0
else
log_error "JSON file ${__PROTONWIRE_SRV_INFO_FILE:-NA} is invalid!"
fi
else
log_error "Missing server info json file - ${__PROTONWIRE_SRV_INFO_FILE:-NA}"
log_error "Either specify PROTONVPN_SERVER or connect first and try agian!"
fi
return 1
}
# when running as a service, script periodically refreshes the metadata.
function protonvpn_fetch_metadata() {
local metadata_stale="true"
local force_refresh="false"
local wrapped_invocation="false"
if __is_bool_true "${PROTONWIRE_FORCE}"; then
force_refresh="true"
fi
while [[ ${1} != "" ]]; do
case ${1} in
--force-refresh | --force | -f)
force_refresh="true"
;;
--wrapper | -w)
wrapped_invocation="true"
;;
esac
shift
done
# To avoid urlencoding as server names may contain '#' replace it with '-' as required by API.
local api_server_name
api_server_name="${PROTONVPN_SERVER//#/-}"
# Check if __PROTONWIRE_SRV_INFO_FILE is present and corresponds to correct server.
if [[ -f ${__PROTONWIRE_SRV_INFO_FILE} ]]; then
local current_ts=0
local metadata_ts=-1
metadata_ts=$(stat -c %Y "${__PROTONWIRE_SRV_INFO_FILE}")
printf -v current_ts '%(%s)T' -1
if [[ $((current_ts - metadata_ts)) -lt 7200 ]]; then
metadata_stale="false"
else
log_warning "Server info is stale - ${__PROTONWIRE_SRV_INFO_FILE}"
fi
# Check if existing metadata file belongs to correct server
declare -a existing_server_endpoints
local existing_server_name
local existing_server_dns
existing_server_name="$(jq -r '.Name' "${__PROTONWIRE_SRV_INFO_FILE}")"
existing_server_dns="$(jq -r '.DNS' "${__PROTONWIRE_SRV_INFO_FILE}")"
readarray -t existing_server_endpoints < <(jq -r \
'.Nodes[].Endpoint' \
<<<"${__PROTONWIRE_SRV_INFO_FILE}" 2>/dev/null)
# If metadata is not stale, check if it belongs to the server.
if [[ $metadata_stale == "false" ]]; then
if [[ $existing_server_name == "$PROTONVPN_SERVER" ]] ||
[[ $existing_server_dns == "$PROTONVPN_SERVER" ]] ||
[[ ${existing_server_name//#/-} == "$api_server_name" ]]; then
log_debug "Existing metadata belongs to ${PROTONVPN_SERVER}"
else
log_debug "Checking if server endpoints match ${PROTONVPN_SERVER}"
local m="false"
for endpoint in "${existing_server_endpoints[@]}"; do
if [[ ${PROTONVPN_SERVER,,} == "${endpoint,,}" ]]; then
m="true"
break
fi
done
if [[ $m != "true" ]]; then
log_debug "Existing metadata belongs to ${PROTONVPN_SERVER}"
else
log_info "Existing metadata($existing_server_name/$existing_server_dns) does not belong to ${PROTONVPN_SERVER}"
metadata_stale="true"
fi
fi
fi
else
log_debug "Server info file is missing - ${__PROTONWIRE_SRV_INFO_FILE}"
fi
# Fetch if file is stale or forced
if [[ $metadata_stale != "false" ]] || [[ $force_refresh == "true" ]]; then
log_info "Refresing server metadata (for $PROTONVPN_SERVER)"
local api_call="${METADATA_URL}/${api_server_name}"
log_debug "API - ${api_call}"
local curl_rc="-1"
local curl_opts="-sSfL"
if __is_bool_true "${DEBUG}"; then
curl_opts="-vfL"
fi
# we use wait to ensure the term signals can be handled properly
{ flock --timeout 30 --conflict-exit-code 32 "${__PROTONWIRE_SRV_INFO_FILE}.lock" \
curl "${curl_opts}" -m 30 -A 'protonwire/v7' -o "${__PROTONWIRE_SRV_INFO_FILE}.bak" \
"${api_call}" 2>&1 | log_tail "curl" & }
wait $!
curl_rc="$?"
# Save to a backup file as download can fail or be corrupted
if [[ $curl_rc == "0" ]]; then
# Ensure file is json formatted and valid
if jq --exit-status '.Nodes' "${__PROTONWIRE_SRV_INFO_FILE}.bak" >/dev/null 2>&1; then
if mv --force "${__PROTONWIRE_SRV_INFO_FILE}.bak" "${__PROTONWIRE_SRV_INFO_FILE}"; then
log_success "Successfully refreshed server metadata"
else
log_error "Refreshing server metadata failed (trampoline error)"
return 1
fi
else
log_error "Refreshing server metadata failed (invalid json)"
return 1
fi
elif [[ $curl_rc -eq 6 ]]; then
log_error "Failed to refresh ProtonVPN server metadata (failed to resolve DNS)"
log_error "See https://github.com/tprasadtp/protonvpn-docker/blob/master/docs/help.md for troubleshooting."
return 1
elif [[ $curl_rc -eq 28 ]]; then
log_error "Failed to refresh ProtonVPN server metadata (curl timeout)"
return 1
elif [[ $curl_rc -eq 22 ]]; then
log_error "Failed to refresh ProtonVPN server metadata (server name is invalid or not found)"
log_error "Please verify that server ${PROTONVPN_SERVER:NA} is valid and available on ProtonVPN Website"
log_error "See https://github.com/tprasadtp/protonvpn-docker/blob/master/docs/help.md for troubleshooting."
return 1
elif [[ $curl_rc -eq 32 ]]; then
log_error "Failed to refresh ProtonVPN server metadata (flock timeout)"
return 1
else
log_error "Failed to refresh ProtonVPN server metadata (curl exit code: ${curl_rc})"
return 1
fi
else
if [[ $wrapped_invocation == "true" ]]; then
log_debug "Server metadata is already upto date"
else
log_success "Server metadata is already upto date"
fi
fi
__load_srvinfo_json_to_var && return 0
return 1
}
function protonvpn_healthcheck_status_file() {
if [[ $IPCHECK_INTERVAL == "0" ]]; then
log_warning "Healthchecks are disabled, cannot use status file!"
return 0
fi
__detect_paths
log_debug "Checking via file timestamp (${__PROTONWIRE_HCS})"
if [[ -n $IPCHECK_INTERVAL ]]; then
local check_interval="$IPCHECK_INTERVAL"
else
log_debug "No healthcheck interval defined, using default(120)"
local check_interval="120"
fi
if [[ -f ${__PROTONWIRE_HCS} ]]; then
local hc_time
local current_ts
printf -v current_ts '%(%s)T' -1
hc_time="$(stat -c '%Y' "${__PROTONWIRE_HCS}")"
local hc_diff="-1"
hc_diff=$((current_ts - hc_time))
if [[ $hc_diff -lt $((check_interval + 10)) ]]; then
log_success "Healthcheck is up (via status file), last checked ${hc_diff}s ago"
return 0
else
log_error "Healthcheck is down (via status file), last checked ${hc_diff}s ago"
return 1
fi
else
log_error "Healthcheck status file (${__PROTONWIRE_HCS}) does not exist!"
return 1
fi
}
function __protonvpn_verify_connection() {
if [[ -z ${__PROTONWIRE_SRV_INFO} ]]; then
declare -g __PROTONWIRE_SRV_INFO
__PROTONWIRE_SRV_INFO="$(<"$__PROTONWIRE_SRV_INFO_FILE")"
fi
if [[ -z ${__PROTONWIRE_SRV_INFO} ]]; then
log_debug "__PROTONWIRE_SRV_INFO is undefined!"
return 1
fi
if [[ -z $(ip link show protonwire0 type wireguard 2>/dev/null) ]]; then
log_error "WireGuard interface - protonwire0 is not present"
return 1
else
log_debug "WireGuard interface - protonwire0 is present"
fi
declare -a configured_endpoints
readarray -t configured_endpoints < <(wg show protonwire0 peers 2>/dev/null)
if [[ ${#configured_endpoints[@]} -eq 0 ]]; then
log_error "WireGuard interface 'protonwire0' is not connected to any peers"
return 1
elif [[ ${#configured_endpoints[@]} -gt 1 ]]; then
log_debug "Connected peers - ${configured_endpoints[*]}"
log_error "WireGuard interface 'protonwire0' is connected to multiple peers(${#configured_endpoints[@]})"
return 1
else
log_debug "Connected to peer - ${configured_endpoints[*]}"
fi
declare -a allowed_exit_ips
declare -a node_endpoints
local node_name
local node_dns
node_name="$(jq -r --arg peer "${configured_endpoints[0]}" 'select(.Nodes[].PublicKey==$peer) | .Name' <<<"${__PROTONWIRE_SRV_INFO}" 2>/dev/null)"
node_dns="$(jq -r --arg peer "${configured_endpoints[0]}" 'select(.Nodes[].PublicKey==$peer) | .DNS' <<<"${__PROTONWIRE_SRV_INFO}" 2>/dev/null)"
readarray -t node_endpoints < <(jq -r \
'.Nodes[].Endpoint' \
<<<"${__PROTONWIRE_SRV_INFO}" 2>/dev/null)
if [[ -n $PROTONVPN_SERVER ]]; then
if [[ ${PROTONVPN_SERVER^^} == "${node_name^^}" ]] ||
[[ ${PROTONVPN_SERVER^^//#/-} == "${node_name^^}" ]] ||
[[ ${PROTONVPN_SERVER,,} == "${node_dns,,}" ]]; then
log_debug "Connected to server: ${node_name:-NA}(${node_dns:-NA})"
if ! __protonvpn_verify_server_attributes; then
return 1
fi
else
local m="false"
for endpoint in "${node_endpoints[@]}"; do
if [[ ${PROTONVPN_SERVER,,} == "${endpoint,,}" ]]; then
m="true"
break
fi
done
if [[ $m != "true" ]]; then
log_error "Expected to be connected to server $PROTONVPN_SERVER, but is connected to ${node_name:-NA}(${node_dns:-NA})"
return 1
else
if ! __protonvpn_verify_server_attributes; then
return 1
fi
fi
fi
else