aboutsummaryrefslogtreecommitdiffstats
path: root/GNS3/gns3-install-on-remote-server.sh
blob: 7868d2511ba33b3cbce7e01a34c66b298b73d739 (about) (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
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
#!/bin/bash
########################################################################################################################
# gns3-install-on-remote-server.sh
########################################################################################################################
# Copyright 2017-2019 Jean-Christophe Manciot <manciot.jeanchristophe@gmail.com>
#
# Licensed under a GPLv3 License.
# You may not use this file except in compliance with the License. You may obtain a copy of the License at
#
#    https://www.gnu.org/licenses/gpl-3.0.md
#
# The licensor cannot revoke these freedoms as long as you follow the license terms.
#
# Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. 
# You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
########################################################################################################################

########################################################################################################################
#
# Installing GNS3 as a Service on a recent remote Debian/Ubuntu bare-metal/VM server inside an OpenVPN tunnel.
# The server must be remotely accessible through Internet, for instance a VM or a bare metal server in a public cloud 
# such as packet.net. 
# This sets up all the required packages.
# An OpenVPN management interface has also been setup to enable management commands with 'telnet 127.0.0.1 1195' on the 
# server.
# The security of the whole process has been enforced and hardened.
#
########################################################################################################################
#
# Requirements:
# ------------
#
# - We assume that this script is run as **root**.
#
########################################################################################################################
#
# Parameters:
# ----------
#
# The follwoing parameters are all optional, except --username:
# --apt-sources-url=<URL>:                      URL of latest stable Debian/Ubuntu APT sources
#                                               By default, it is http://deb.debian.org/debian or http://archive.ubuntu.com/ubuntu
# --gns3-port=<port_number>                     Port number which GNS3 server listens to
#                                               By default, it is 3080
# --openvpn-tunnel-ip-address=<ip_address>      OpenVPN tunnel IPv4 address on which GNS3 server listens
#                                               By default, it is 172.31.255.1
# --repository=<DR/PPA>:                        Choose a repository between:
#                                                       + gns3: official GNS3 repository
#                                                       + jc-manciot: latest deb packages including GNS3 on the latest stable 
#                                                         Debian/Ubuntu release for x86_64 architectures
#                                               By default, it is jc-manciot.
# --username=<username>:                        on the server
# --without-new-apt-sources:                    Don't install new /etc/apt/sources.list
#                                               By default, on Debian, the follwoing are installed in /etc/apt/sources.list:
#                                                       + deb http://deb.debian.org/debian/debian testing main contrib non-free
#                                                       + deb deb http://security.debian.org/ testing/updates main contrib non-free
#                                               By default, on Ubuntu, the follwoing are installed /etc/apt/sources.list:
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name> main restricted multiverse universe
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name>-updates main restricted multiverse universe
#                                                       + deb http://archive.ubuntu.com/ubuntu <os_code_name>-security main restricted multiverse universe
# --without-openvpn:                            Don't install Open VPN: the communications with GNS3 server won't be encrypted
#                                               By default, an Open VPN is installed & configured.
# --without-openvpn-purge:                      Don't purge OpenVPN prior to its reinstallation if it is set to be used
#                                               By default, openVPN is purged before its installation.
# --without-ufw-gns3-port:                      Don't open GNS3 port on UFW firewall.
#                                               By default, UFW is used and GNS3 port is allowed for all sources within or outside  
#                                               OpenVPN tunnel depending on the configuration.
#                                               3080 port must be allowed manually somehow on UFW for GNS3 server to be able to 
#                                               connect to its client(s).
# --without-ufw-openvpn-port:                   Don't open openvpn port on UFW firewall.
#                                               By default, UFW is used and openVPN port is allowed for all sources.
#                                               udp/1194 port must be allowed manually somehow on UFW for the OpenVPN tunnel to work.
# --without-ufw-ssh-port:                       Don't open ssh port on UFW firewall.
#                                               By default, UFW is used and ssh port is allowed for all sources.
#                                               tcp/22 port must be allowed manually somehow on UFW beforehand to be able to:
#                                                       + keep the current SSH session alive
#                                                       + retrieve the OpenVPN bundle.
# --without-unstable-repository:                Use only JC Manciot's DR/PPA stable repository
#                                               By default, stable & unstable JC Manciot's DR/PPA are used
# --help
#
#######################################################################################################################
#
# Usage:
# -----
#
# ssh root@<remote_server_ip_address>
#
# Inside the server terminal:
# --------------------------
# sudo -i
# wget https://git.sdxlive.com/DR/plain/GNS3/gns3-install-on-remote-server.sh
# chmod +x gns3-install-on-remote-server.sh
# ./gns3-install-on-remote-server.sh --username=<username>
# shutdown now
# 
# Inside the client terminal after having restarted the server:
# ------------------------------------------------------------
# sudo -i
# scp root@<server_wan_ip_address>:/etc/openvpn/<server_hostname>.tar.bz2 ~/Downloads
# tar jxvf ~/Downloads/<server_hostname>.tar.bz2
# nm-connection-editor -> Add -> Import a saved configuration -> Create -> ~/Downloads/client.ovpn
#
# On the client Gnome's top right hand side menu:
# ----------------------------------------------
# VPN Off -> Connect
#
# Inside the client GNS3:
# ----------------------
# Once the OpenVPN tunnel has been correctly setup, you should be able to define a node on the remote server:
# ----------------------------------------------------------------------------------------------------------
# Defining the remote server:
# --------------------------
# Edit Preferences -> Server -> Remote Servers -> Add -> http - 172.31.255.1 - 3080 -> OK
#
# Defining the remote node:
# ------------------------
# Qemu VMs -> New -> Run this Qemu VM on a remote computer -> Run on <remote_server> -> Next -> Name -> Next
# If the connection is successful, the Qemu binary name is retrieved.
#
# Inside the server terminal, purge this MOTD with:
# ------------------------------------------------
# sudo rm -fv /etc/update-motd.d/70-openvpn
#
########################################################################################################################
# set -x
# Allowing extended pattern matching
shopt -s extglob

function help 
{
        printf "%s\n" "________________________________________________________________________________________" >&2
        printf "%s\n" "Installing GNS3-as-a-Service on a recent remote cloud Debian/Ubuntu bare-metal/VM server" >&2
        printf "%s\n" "========================================================================================" >&2
        printf "%s\n" "Necessary:" >&2
        printf "%s\n" "---------" >&2
        printf "%s\n" "--username=<username>                    Username on the server" >&2
        printf "\n" >&2
        printf "%s\n" "Optional:" >&2
        printf "%s\n" "--------" >&2
        printf "%s\n" "--apt-sources-url=<URL>                  URL of latest stable Debian/Ubuntu APT sources" >&2
        printf "%s\n" "                                         By default, it is http://deb.debian.org/debian or http://archive.ubuntu.com/ubuntu" >&2
        printf "%s\n" "--gns3-port=<port_number>                Port number which GNS3 server listens to" >&2
        printf "%s\n" "                                         By default, it is 3080" >&2
        printf "%s\n" "--openvpn-tunnel-ip-address=<ip_address> OpenVPN tunnel IPv4 address on which GNS3 server listens" >&2
        printf "%s\n" "                                         By default, it is 172.31.255.1" >&2
        printf "%s\n" "--repository=<DR/PPA>                    Choose a repository between:" >&2
        printf "%s\n" "                                                 + gns3: official GNS3 repository" >&2
        printf "%s\n" "                                                 + jc-manciot: latest deb packages including GNS3 on the latest stable Debian/Ubuntu" >&2
        printf "%s\n" "                                                   release for x86_64 architectures" >&2
        printf "%s\n" "                                         By default, it is jc-manciot." >&2
        printf "%s\n" "--without-new-apt-sources                Don't install new /etc/apt/sources.list" >&2
        printf "%s\n" "                                         By default, on Debian, the follwoing are installed in /etc/apt/sources.list:" >&2
        printf "%s\n" "                                                 + deb http://deb.debian.org/debian/debian testing main contrib non-free" >&2
        printf "%s\n" "                                                 + deb http://security.debian.org/ testing/updates main contrib non-free" >&2
        printf "%s\n" "                                         By default, on Ubuntu, the follwoing are installed /etc/apt/sources.list:" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name> main restricted multiverse universe" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name>-updates main restricted multiverse universe" >&2
        printf "%s\n" "                                                 + deb http://archive.ubuntu.com/ubuntu <os_code_name>-security main restricted multiverse universe" >&2
        printf "%s\n" "--without-openvpn                        Don't install Open VPN; the communications with GNS3 server won't be encrypted" >&2
        printf "%s\n" "                                         By default, an Open VPN is installed & configured." >&2
        printf "%s\n" "--without-openvpn-purge                  Don't purge OpenVPN prior to its reinstallation if it is set to be used" >&2
        printf "%s\n" "                                         By default, openVPN is purged before its installation." >&2
        printf "%s\n" "--without-ufw-gns3-port                  Don't open GNS3 port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and GNS3 port is allowed for all sources within or outside" >&2
        printf "%s\n" "                                         OpenVPN tunnel depending on the configuration." >&2
        printf "%s\n" "                                         3080 port must be allowed manually somehow on UFW for GNS3 server to be able to" >&2
        printf "%s\n" "                                         connect to its client(s)." >&2
        printf "%s\n" "--without-ufw-openvpn-port               Don't open openvpn port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and openVPN port is allowed for all sources." >&2
        printf "%s\n" "                                         udp/1194 port must be allowed manually somehow on UFW for the OpenVPN tunnel to work." >&2
        printf "%s\n" "--without-ufw-ssh-port                   Don't open ssh port on UFW firewall." >&2
        printf "%s\n" "                                         By default, UFW is used and ssh port is allowed for all sources." >&2
        printf "%s\n" "                                         tcp/22 port must be allowed manually somehow on UFW beforehand to be able to:" >&2
        printf "%s\n" "                                                 + keep the current SSH session alive" >&2
        printf "%s\n" "                                                 + retrieve the OpenVPN bundle" >&2
        printf "%s\n" "--without-unstable-repository            Use only JC Manciot's DR/PPA stable repository" >&2
        printf "%s\n" "                                         By default, stable & unstable JC Manciot's DR/PPA are used" >&2
        printf "%s\n" "--help:                                  This help" >&2
}

function report 
{
        printf "%s\n" "______________________________________________________________________________________________________________" >&2
        printf "%s\n" "=> $1" >&2
        printf "%s\n" "==============================================================================================================" >&2
}

if [[ $(whoami) != root ]]; then
        report "This script must be run as root"
        exit 1
fi        

username=""
url_regex='(http[s]*|ftp)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]'
gns3_port=3080
openvpn_tunnel_ip_address=172.31.255.1
repository=jc-manciot
new_apt_sources_enabled=true
openvpn_enabled=true
openvpn_purge_enabled=true
ufw_gns3_port_enabled=true
ufw_openvpn_port_enabled=true
ufw_ssh_port_enabled=true
unstable_repository_enabled=true

# Reading the options
OPTIONS=`getopt -o h --long apt-sources-url:,gns3-port:,openvpn-tunnel-ip-address:,repository:,username:,without-new-apt-sources,without-openvpn,without-openvpn-purge,without-ufw-gns3-port,without-ufw-openvpn-port,without-ufw-ssh-port,without-unstable-repository,help -n 'gns3-install-on-local-server.sh' -- "$@"`
if [ $? -ne 0 ]
then
        help
        exit 1
fi
eval set -- "$OPTIONS"

# Extracting options and their arguments into variables.
while true ; do
        case "$1" in
                --apt-sources-url)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        apt_sources_url=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --gns3-port)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        gns3_port=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --openvpn-tunnel-ip-address)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        openvpn_tunnel_ip_address=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --repository)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        repository=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --username)
                        case "$2" in
                                "") 
                                        ;;
                                *)
                                        username=$2
                                        ;;
                        esac
                        shift 2
                        ;;
                --without-new-apt-sources)
                        new_apt_sources_enabled=false
                        shift
                        ;;
                --without-openvpn)
                        openvpn_enabled=false
                        shift
                        ;;
                --without-openvpn-purge)
                        openvpn_purge_enabled=false
                        shift
                        ;;
                --without-ufw-gns3-port)
                        ufw_gns3_port_enabled=false
                        shift
                        ;;
                --without-ufw-openvpn-port)
                        ufw_openvpn_port_enabled=false
                        shift
                        ;;
                --without-ufw-ssh-port)
                        ufw_ssh_port_enabled=false
                        shift
                        ;;
                --without-unstable-repository)
                        unstable_repository_enabled=false
                        shift
                        ;;
                -h|--help)
                        help
                        exit 1
                        ;;
                --) 
                        shift
                        break
                        ;;
                *)
                        report "Internal error $1"
                        exit 1
                        ;;
        esac
done

if [[ -z $username ]]; then
        report "--username=<username> option is missing"
        exit 1
elif [[ (-n "$apt_sources_url") && (! "$apt_sources_url" =~ $url_regex) ]]; then
        report "$apt_sources_url URL format is not valid"
        exit 1
fi

export DEBIAN_FRONTEND="noninteractive"

os_distribution=$(lsb_release -a  2>/dev/null | grep "Distributor ID" | cut -d ':' -f 2)
os_distribution=${os_distribution//[[:space:]]/}
os_version=$(lsb_release -a  2>/dev/null | grep "Release" | cut -d ':' -f 2)
os_version=${os_version//[[:space:]]/}
os_code_name=$(lsb_release -a  2>/dev/null | grep "Codename" | cut -d ':' -f 2)
os_code_name=${os_code_name//[[:space:]]/}
linux_kernel_version=$(uname -r)
case $os_distribution in
        Debian)
                if [[ $os_version =~ testing ]]; then
                        os_version='11.0'
                fi
                if [[ -z "$apt_sources_url" ]]; then
                        apt_sources_url="http://deb.debian.org/debian"
                fi
                case $os_version in
                        11*) # bullseye
                                # Verifying that it is what it says it is
                                if [[ "$linux_kernel_version" < 4.19 ]]; then
                                        echo "Linux kernel version $linux_kernel_version is incompatible with $os_distribution 11.x"
                                        exit 1
                                fi

                                if [[ $new_apt_sources_enabled == true ]]; then
                                        report "Installing new apt sources"
cat <<EOFAPT > /etc/apt/sources.list
deb "$apt_sources_url" testing main contrib non-free
deb-src "$apt_sources_url" testing main contrib non-free
deb http://security.debian.org/ testing/updates main contrib non-free
deb-src http://security.debian.org/ testing/updates main contrib non-free
EOFAPT
                                fi

                                report "Updating system deb packages list"
                                apt update

                                report "Installing primary package"
                                apt install --show-progress --assume-yes apt-transport-https

                                case $repository in
                                        gns3)
                                                report "Installing GNS3 PPA"
                                                apt install --show-progress --assume-yes software-properties-common
                                                add-apt-repository ppa:gns3/ppa
                                                ;;
                                        jc-manciot)
                                                report "Adding JC Manciot's Public GPG key"
                                                if [[ -z $(gpg --list-keys | grep DF7396D82BBA3684FCCADD4DB063838ED13997FD) ]]; then
                                                        gpg --keyserver keyring.debian.org --recv-keys DF7396D82BBA3684FCCADD4DB063838ED13997FD
                                                fi
                                                if [[ -z $(apt-key list 2>/dev/null | grep "DF73 96D8 2BBA 3684 FCCA  DD4D B063 838E D139 97FD") ]]; then
                                                        gpg --export --armor DF7396D82BBA3684FCCADD4DB063838ED13997FD | apt-key add -
                                                fi

                                                report "Adding stable JC Manciot's DR"
                                                bash -c $'echo "deb https://git.sdxlive.com/DR/plain/Debian ${os_code_name} stable #JC Manciot\'s DR" > /etc/apt/sources.list.d/jean-christophe-manciot.list'
                                                #"

                                                if [[ $unstable_repository_enabled == true ]]; then
                                                        report "Adding unstable JC Manciot's DR"
                                                        bash -c $'echo "deb https://git.sdxlive.com/DR/plain/Debian ${os_code_name} unstable #JC Manciot\'s DR" >> /etc/apt/sources.list.d/jean-christophe-manciot.list'
                                                        #"
                                                fi
                                                ;;
                                        *)
                                                report "$repository is not supported"
                                                exit 1
                                                ;;
                                esac
                                ;;
                        *)
                                report "Current OS/version is not supported:"
                                printf "%s\n" "Detected OS $os_distribution"
                                printf "%s\n" "Detected OS version $os_version"
                                printf "%s\n" "Detected OS code name $os_code_name"
                                report "Only the latest stable Debian release is supported"
                                exit 1
                                ;;
                esac
                ;;
        *buntu)
                if [[ -z "$apt_sources_url" ]]; then
                        apt_sources_url="http://archive.ubuntu.com/ubuntu/"
                fi
                case $os_version in
                        '19.10') # eoan
                                # Verifying that it is what it says it is
                                if [[ "$linux_kernel_version" < 5.0 ]]; then
                                        echo "Linux kernel version $linux_kernel_version is incompatible with $os_distribution 19.10"
                                        exit 1
                                fi
                                if [[ $new_apt_sources_enabled == true ]]; then
                                        report "Installing new apt sources"
cat <<EOFAPT > /etc/apt/sources.list
deb "$apt_sources_url" ${os_code_name} main restricted multiverse universe partner
deb-src "$apt_sources_url" ${os_code_name} main restricted multiverse universe
deb "$apt_sources_url" ${os_code_name}-updates main restricted multiverse universe
deb-src "$apt_sources_url" ${os_code_name}-updates main restricted multiverse universe
deb "$apt_sources_url" ${os_code_name}-security main restricted multiverse universe
deb-src "$apt_sources_url" ${os_code_name}-security main restricted multiverse universe
EOFAPT
                                fi

                                report "Updating system deb packages list"
                                apt update

                                report "Installing primary package"
                                apt install --show-progress --assume-yes apt-transport-https

                                case $repository in
                                        gns3)
                                                report "Installing GNS3 PPA"
                                                apt install --show-progress --assume-yes software-properties-common
                                                add-apt-repository ppa:gns3/ppa
                                                ;;
                                        jc-manciot)
                                                report "Adding JC Manciot's Public GPG key"
                                                if [[ -z $(gpg --list-keys | grep DF7396D82BBA3684FCCADD4DB063838ED13997FD) ]]; then
                                                        gpg --keyserver keyserver.ubuntu.com --recv-keys DF7396D82BBA3684FCCADD4DB063838ED13997FD
                                                fi
                                                if [[ -z $(apt-key list 2>/dev/null | grep "DF73 96D8 2BBA 3684 FCCA  DD4D B063 838E D139 97FD") ]]; then
                                                        gpg --export --armor DF7396D82BBA3684FCCADD4DB063838ED13997FD | apt-key add -
                                                fi

                                                report "Adding stable JC Manciot's PPA"
                                                bash -c $'echo "deb https://git.sdxlive.com/PPA/plain/Ubuntu ${os_code_name} stable #JC Manciot\'s Stable PPA" > /etc/apt/sources.list.d/jean-christophe-manciot.list'
                                                #"

                                                if [[ $unstable_repository_enabled == true ]]; then
                                                        report "Adding unstable JC Manciot's PPA"
                                                        bash -c $'echo "deb https://git.sdxlive.com/PPA/plain/Ubuntu ${os_code_name} unstable #JC Manciot\'s Unstable PPA" >> /etc/apt/sources.list.d/jean-christophe-manciot.list'
                                                        #"
                                                fi
                                                ;;
                                        *)
                                                report "$repository is not supported"
                                                exit 1
                                                ;;
                                esac
                                ;;
                        *)
                                report "Current OS/version is not supported:"
                                printf "%s\n" "Detected OS $os_distribution"
                                printf "%s\n" "Detected OS version $os_version"
                                printf "%s\n" "Detected OS code name $os_code_name"
                                report "Only the latest Ubuntu release is supported"
                                exit 1
                                ;;
                esac
                ;;
        *)
                report "Current OS/version is not supported:"
                printf "%s\n" "Detected OS $os_distribution"
                printf "%s\n" "Detected OS version $os_version"
                printf "%s\n" "Detected OS code name $os_code_name"
                report "Only the latest Ubuntu release is supported"
                exit 1
                ;;
esac

report "Updating system deb packages list"
apt update

report "Upgrading deb packages"
apt upgrade --yes --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"

report "Installing & enabling UFW firewall"
apt install --show-progress --assume-yes ufw
if [[ $ufw_ssh_port_enabled == true ]]; then
        report "Allowing SSH on UFW firewall for all sources"
        ufw allow 22/tcp
fi
ufw --force enable
report "Listing UFW Firewall rules"
ufw status verbose

report "Installing python setuptools"
apt install --show-progress --assume-yes python-pip python3-pip
pip3 install --upgrade setuptools

# report "Upgrading all python packages"
# pip3 list --outdated | cut -d " " -f 1 | xargs -n1 pip3 install -U

report "Installing some utilities"
apt --show-progress --assume-yes install coreutils cpu-checker grep intel-microcode iproute2 kmod libc-bin libsystemd-dev net-tools ovmf passwd qemu-kvm

report "Configuring nested KVM"
echo "options kvm_intel nested=1" > /etc/modprobe.d/qemu-system-x86.conf

# "Making sure /etc/modprobe.d/* files are read"
if [[ $(lsmod | grep "kvm_intel") =~ ^kvm_intel ]]; then
        rmmod kvm_intel
fi
if [[ $(lsmod | grep "kvm ") =~ ^kvm ]]; then
        rmmod kvm
fi
getent group kvm || groupadd kvm
modprobe kvm
modprobe kvm_intel
chown --no-dereference root:kvm /dev/kvm

report "Settinbg SUID for all /usr/bin/qemu-* binaries"
chmod u+s /usr/bin/qemu-*

if [[ -z $(kvm-ok | grep "KVM acceleration can be used") ]]; then
        report "KVM acceleration cannot be used: exiting"
        exit 1
elif [[ $(cat /sys/module/kvm_intel/parameters/nested | grep Y) == Y ]]; then
        vCPUs=$(egrep -c '(vmx|svm)' /proc/cpuinfo)
        report "Nested KVM acceleration can be used on $vCPUs vCPUs"
else
        report "Nested KVM acceleration cannot be used: exiting"
        exit 1
fi

id -u ${username}
if [[ $? -eq 1 ]]; then
        report "Creating user ${username}"
        useradd -m ${username}
fi

report "Creating group ubridge"
getent group ubridge || groupadd ubridge

report "Adding ${username} to the ubridge group"
usermod -aG ubridge ${username}

report "Adding ${username} to the kvm group"
usermod -aG kvm ${username}

report "Detecting the server LAN IP address"
default_interface=$(ip route show | grep default  | head -n 1 | cut -d ' ' -f 5)
server_lan_ip_address=$(ifconfig $default_interface | grep "inet " | sed 's|^.* inet \(.*\) netmask .*|\1|g')
# Removing all spaces, tabs, line breaks
server_lan_ip_address=${server_lan_ip_address//[[:space:]]/}

report "Installing GNS3 Server"
apt --show-progress --assume-yes install --reinstall gns3-server xvfb

report "Setting up GNS3 folders"
if [[ ! (-d /home/${username}/GNS3/Images) ]]; then
        mkdir -pv /home/${username}/GNS3/Images
fi
if [[ ! (-d /home/${username}/GNS3/Labs) ]]; then
        mkdir -pv /home/${username}/GNS3/Labs
fi
if [[ ! (-d /root/.config/GNS3) ]]; then
        mkdir -pv /root/.config/GNS3
fi
chown --no-dereference -R ${username}: /home/${username}/GNS3
chmod -R 700 /home/${username}/GNS3

report "Setting up GNS3 server"
if [[ ! (-f /root/.config/GNS3/gns3_server.conf) ]]; then
cat <<EOFC > /root/.config/GNS3/gns3_server.conf
[Server]
host = $server_lan_ip_address
port = $gns3_port 
images_path = /home/${username}/GNS3/Images
projects_path = /home/${username}/GNS3/Labs
report_errors = True

[Qemu]
enable_kvm = True
EOFC
else
        sed -i "s|host =.*|host = ${server_lan_ip_address}|g" /root/.config/GNS3/gns3_server.conf
        sed -i "s|port =.*|port = ${gns3_port}|g" /root/.config/GNS3/gns3_server.conf
        sed -i "s|images_path =.*|images_path = /home/${username}/GNS3/Images|g" /root/.config/GNS3/gns3_server.conf
        sed -i "s|projects_path =.*|projects_path = /home/${username}/GNS3/Labs|g" /root/.config/GNS3/gns3_server.conf
        sed -i "s|report_errors =.*|report_errors = True|g" /root/.config/GNS3/gns3_server.conf
        sed -i "s|enable_kvm =.*|enable_kvm = True|g" /root/.config/GNS3/gns3_server.conf
fi

report "Starting GNS3 as a service"
systemctl enable gns3
systemctl restart gns3
systemctl --no-pager --full status gns3
return_code=$?
if [[ $return_code -eq 0 ]]; then
        report "GNS3 installed with success"
else 
        report "GNS3 installed with error"
        report "Consult /var/log/syslog for details"
        report "or journalctl --no-pager --full -xe | grep gns3"
        exit $return_code      
fi

if [[ $ufw_gns3_port_enabled == true ]]; then
        report "Opening GNS3 server port on UFW firewall"
        ufw allow ${gns3_port}
fi

if [[ $openvpn_enabled == true ]]; then
        if [[ $openvpn_purge_enabled == true ]]; then
                report "Purging potential previous OpenVPN"
                if [[ $(systemctl is-active openvpn) == active ]]; then
                        systemctl stop openvpn
                fi
                dpkg --get-selections | grep -q "^openvpn[[:space:]]*install$"
                if [[ $? -eq 0 ]]; then
                        apt purge --show-progress --assume-yes openvpn
                        rm -rfv /etc/openvpn
                        rm -fv /var/log/openvpn.log
                fi
        fi

        report "Installing packages for OpenVPN"
        apt install --reinstall --show-progress --assume-yes dnsutils easy-rsa openssl openvpn whois

        report "Setting up OpenVPN"
        [[ -d /dev/net ]] || mkdir -p /dev/net
        [[ -c /dev/net/tun ]] || mknod /dev/net/tun c 10 200

        server_wan_ip_address=$(dig @ns1.google.com -t txt o-o.myaddr.l.google.com +short | sed 's/"//g')
        server_country=$(curl ipinfo.io/${server_wan_ip_address} | grep -iE country | cut -d ':' -f 2 | sed 's| "\(..\)",|\1|g')
        server_region=$(curl ipinfo.io/${server_wan_ip_address} | grep -iE region | cut -d ':' -f 2 | sed 's| "\(.*\)",|\1|g')
        server_city=$(curl ipinfo.io/${server_wan_ip_address} | grep -iE city | cut -d ':' -f 2 | sed 's| "\(.*\)",|\1|g')
        server_org="S.I.T"
        server_email="manciot.jeanchristophe@gmail.com"
        server_ou="Freelancers"
        # Removing all spaces, tabs, line breaks
        server_region=${server_region//[[:space:]]/}
        server_city=${server_city//[[:space:]]/}

        report "My detected LAN IPv4 address:   $server_lan_ip_address"
        report "My detected WAN IPv4 address:   $server_wan_ip_address"
        report "My detected country:            $server_country"
        report "My detected region:             $server_region"
        report "My detected city:               $server_city"

        report "Creating OpenVPN server configuration"
        # Example VPN server configuration
        gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz > /etc/openvpn/server.conf
        # Listening on our IP address
        sed -i "s|^;local .*|local $server_lan_ip_address|g" /etc/openvpn/server.conf
        # Setting our IP address
        sed -i 's|^server .*|server 172.31.255.0 255.255.255.0|g' /etc/openvpn/server.conf
        # Setting key direction
        if [[ -z $(cat /etc/openvpn/server.conf | grep -- "^key-direction 0") ]]; then
                sed -i "s|^tls-auth ta.key 0 # This file is secret|tls-auth ta.key 0 # This file is secret\nkey-direction 0|g" /etc/openvpn/server.conf
        fi
        # Setting HMAC message digest algorithm 
        if [[ -z $(cat /etc/openvpn/server.conf | grep -- "^auth SHA256") ]]; then
                sed -i "s|^cipher AES-256-CBC|cipher AES-256-CBC\nauth SHA256|g" /etc/openvpn/server.conf
        fi
        # Allowing multiple clients to use the same certificate/key files or common names
        sed -i 's|^;duplicate-cn|duplicate-cn|g' /etc/openvpn/server.conf
        # Allowing older compression
        # sed -i 's|^;comp-lzo|comp-lzo|g' /etc/openvpn/server.conf
        # Reducing dead timer from 2 mns to 1 mn
        sed -i 's|^keepalive .*|keepalive 10 60|g' /etc/openvpn/server.conf
        # Logging file
        sed -i 's|^;log-append .*|log-append /var/log/openvpn.log|g' /etc/openvpn/server.conf
        # Setting up a local management interface which can be accessed with 'telnet 127.0.0.1 1195'
        printf "\n%s\n%s\n" "# Setting up a local management interface which can be accessed with 'telnet 127.0.0.1 1195'" "management 127.0.0.1 1195" >> /etc/openvpn/server.conf

        report "Setting up the Easy-RSA generation scripts"
        # Copying over the Easy-RSA generation scripts
        cp -frv /usr/share/easy-rsa/ /etc/openvpn
        cp -fv /etc/openvpn/easy-rsa/openssl-1.0.0.cnf /etc/openvpn/easy-rsa/openssl.cnf
        
        # Creating a directory to house the keys
        if [[ ! (-d /etc/openvpn/easy-rsa/keys) ]]; then
                mkdir -pv /etc/openvpn/easy-rsa/keys
        fi

        # Setting all the variables for our certificate
        sed -i "s|^export KEY_COUNTRY=.*|export KEY_COUNTRY=\"$server_country\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_PROVINCE=.*|export KEY_PROVINCE=\"$server_region\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_CITY=.*|export KEY_CITY=\"$server_city\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_ORG=.*|export KEY_ORG=\"$server_org\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_EMAIL=.*|export KEY_EMAIL=\"$server_email\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_OU=.*|export KEY_OU=\"$server_ou\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^export KEY_NAME=.*|export KEY_NAME=\"server\"|g" /etc/openvpn/easy-rsa/vars
        sed -i "s|^# export KEY_CN=.*|export KEY_CN=\"${HOSTNAME}\"|g" /etc/openvpn/easy-rsa/vars
        # Workaround to an issue triggering the error message "error on line 198"
        echo "export KEY_ALTNAMES=$server_email" >> /etc/openvpn/easy-rsa/vars

        cd /etc/openvpn/easy-rsa
        # Sourcing the variables
        . ./vars

        # Clearing all other keys that may interfere with our installation
        ./clean-all

        report "Generating the Diffie-Helman parameters"
        report "Expect long lines of dots"
        ./build-dh
        cp -fv /etc/openvpn/easy-rsa/keys/dh2048.pem /etc/openvpn
        chmod 600 /etc/openvpn/dh2048.pem

        report "Generating the Certificate Authority"
        # Building the CA
        printf '\n\n\n\n\n\n\n\n' | ./build-ca

        report "Generating the Certificate and Key for the Server"
        # Making a certificate/private key pair using a locally generated root certificate.
        # This will designate the certificate as a server-only certificate by setting the right attributes.
        # This is useful as a protection against a MITM attack; 
        # cf. https://openvpn.net/index.php/open-source/documentation/howto.html#mitm
        (printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf 'y\n'; sleep 1 ; printf 'y\n'; sleep 1) | ./build-key-server server
        cp -fv /etc/openvpn/easy-rsa/keys/{server.crt,server.key,ca.crt} /etc/openvpn
        chmod 600 /etc/openvpn/{server.crt,server.key,ca.crt}

        report "Generating the Certificate and Key for the client"
        (printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf '\n'; sleep 1 ; printf 'y\n'; sleep 1 ; printf 'y\n'; sleep 1) | ./build-key client
        cp -fv /etc/openvpn/easy-rsa/keys/{client.crt,client.key} /etc/openvpn
        chmod 600 /etc/openvpn/{client.crt,client.key}
        
        report "Generating the shared secret Key for the both server and client(s)"
        cd /etc/openvpn
        openvpn --genkey --secret ta.key
        chmod 600 /etc/openvpn/ta.key

        report "Creating OpenVPN client configuration"
        cp -fv /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn/client.ovpn

        # Setting our IP address
        sed -i "s|^remote .*|remote $server_wan_ip_address 1194|g" /etc/openvpn/client.ovpn
        # Setting key direction
        if [[ -z $(cat /etc/openvpn/client.ovpn | grep -- "^key-direction 1") ]]; then
                sed -i "s|^tls-auth ta.key 1|tls-auth ta.key 1 # This file is secret\nkey-direction 1|g" /etc/openvpn/client.ovpn
        fi
        # Setting HMAC message digest algorithm 
        if [[ -z $(cat /etc/openvpn/client.ovpn | grep -- "^auth SHA256") ]]; then
                sed -i "s|^cipher AES-256-CBC|cipher AES-256-CBC\nauth SHA256|g" /etc/openvpn/client.ovpn
        fi
        # Allowing older compression
        # sed -i 's|^#comp-lzo|comp-lzo|g' /etc/openvpn/client.conf

        report "Creating the client bundle"
        tar jcvf client.tar.bz2 client.ovpn client.crt client.key ca.crt ta.key
        mv -v client.tar.bz2 ${HOSTNAME}.tar.bz2
        
        report "Allowing IPv4 Forwarding"
        sed -i 's|^.*DEFAULT_FORWARD_POLICY=".*"|DEFAULT_FORWARD_POLICY="ACCEPT"|g' /etc/default/ufw
        sed -i "s|^.*net.ipv4.ip_forward=.*|net.ipv4.ip_forward=1|g" /etc/sysctl.conf
        sysctl -p

        report "Adjusting the UFW Firewall Rules to Masquerade Client Connections"
        if [[ -z $(cat /etc/ufw/before.rules | grep -- "^-A POSTROUTING -s 172.31.255.0/24 -o ${default_interface} -j MASQUERADE") ]]; then
                sed -i "s|^# Don't delete these required lines, otherwise there will be errors|# START OPENVPN RULES\n# NAT table rules\n*nat\n:POSTROUTING ACCEPT [0:0]\n# Allow traffic from OpenVPN client to default interface\n-A POSTROUTING -s 172.31.255.0/24 -o ${default_interface} -j MASQUERADE\nCOMMIT\n# END OPENVPN RULES\n\n# Don't delete these required lines, otherwise there will be errors|g" /etc/ufw/before.rules
        fi

        report "Restarting OpenVPN"
        systemctl enable openvpn@server
        systemctl start openvpn@server
        systemctl --no-pager --full status openvpn
        
        if [[ $ufw_openvpn_port_enabled == true ]]; then
                report "Opening OpenVPN port on UFW firewall"
                ufw allow 1194/udp
        fi

        report "Making GNS3 Server listen inside the OpenVPN Tunnel"
        sed -i "s|host = ${server_lan_ip_address}|host = ${openvpn_tunnel_ip_address}|g" /root/.config/GNS3/gns3_server.conf

        report "Restarting GNS3 service"
        systemctl restart gns3
        systemctl --no-pager --full status gns3
        return_code=$?
        if [[ $return_code -eq 0 ]]; then
                report "GNS3 installed with success inside the tunnel"
        else 
                report "GNS3 installed with error inside the tunnel"
                report "Consult /var/log/syslog for details"
                report "or journalctl --no-pager --full -xe | grep gns3"
                exit $return_code      
        fi

        report "Updating UFW Firewall Rules"
        if [[ $ufw_gns3_port_enabled == true ]]; then
                ufw_gns3_port_v4_rule_number=$(ufw status numbered | grep -E "${gns3_port} \s* ALLOW" | sed 's|^\[\(.*\)\] .*|\1|g')
                ufw_gns3_port_v6_rule_number=$(ufw status numbered | grep "${gns3_port} (v6)" | sed 's|^\[\(.*\)\] .*|\1|g')
                if [[ $ufw_gns3_port_v6_rule_number -ne 0 ]]; then
                        ufw --force delete $ufw_gns3_port_v6_rule_number
                fi
                if [[ $ufw_gns3_port_v4_rule_number -ne 0 ]]; then
                        ufw --force delete $ufw_gns3_port_v4_rule_number
                fi
        fi
        ufw allow in to ${openvpn_tunnel_ip_address} port ${gns3_port}
        # In case all out are denied on pre-existing UFW configuration
        ufw allow out from ${openvpn_tunnel_ip_address}

        report "Updating MOTD"
# The following cannot be prepended with spaces
cat <<EOFMOTD > /etc/update-motd.d/70-openvpn
#!/bin/sh
printf "%s\n" "__________________________________________________________________________________________________________"
printf "%s\n" "Inside the client terminal:"
printf "%s\n" "--------------------------"
printf "%s\n" "Download the OpenVPN configuration bundle from the server with:"
printf "%s\n" "scp root@${server_wan_ip_address}:/etc/openvpn/${HOSTNAME}.tar.bz2 ~/Downloads"
printf "\n"
printf "%s\n" "Extract it with:"
printf "%s\n" "tar jxvf ~/Downloads/${HOSTNAME}.tar.bz2"
printf "\n"
printf "%s\n" "Import into your OpenVPN client with:"
printf "%s\n" "nm-connection-editor -> Add -> Import a saved configuration -> Create -> ~/Downloads/client.ovpn"
printf "\n"
printf "%s\n" "On the client Gnome's top right hand side menu:"
printf "%s\n" "----------------------------------------------"
printf "%s\n" "VPN Off -> Connect"
printf "\n"
printf "%s\n" "Inside the client GNS3:"
printf "%s\n" "----------------------"
printf "%s\n" "Once the OpenVPN tunnel has been correctly setup, you should be able to define a node on the remote server"
printf "%s\n" "Defining the remote server:"
printf "%s\n" "Edit Preferences -> Server -> Remote Servers -> Add -> http - ${openvpn_tunnel_ip_address} - ${gns3_port} -> OK"
printf "\n"
printf "%s\n" "Defining the remote node:"
printf "%s\n" "Qemu VMs -> New -> Run this Qemu VM on a remote computer -> Run on <remote_server> -> Next -> Name -> Next"
printf "%s\n" "If the connection is successful, the Qemu binary name is retrieved"
printf "\n"
printf "%s\n" "Inside the server terminal:"
printf "%s\n" "--------------------------"
printf "%s\n" "Purge this MOTD with:"
printf "%s\n" "sudo rm -fv /etc/update-motd.d/70-openvpn"
printf "%s\n" "=========================================================================================================="
EOFMOTD

        chmod 754 /etc/update-motd.d/70-openvpn
fi

report "Saving UFW Firewall rules"
if [[ ! (-d /etc/iptables) ]]; then
        mkdir -v /etc/iptables
fi
iptables-save > /etc/iptables/rules.v4 && ip6tables-save > /etc/iptables/rules.v6

report "Re-enabling UFW Firewall"
ufw disable && ufw --force enable

report "Listing UFW Firewall rules"
ufw status numbered
        
if [[ ($ufw_gns3_port_enabled == false) && ($openvpn_enabled == false) ]]; then
        report "GNS3 server port has to be manually opened on UFW firewall"
fi

if [[ ($ufw_openvpn_port_enabled == false) && ($openvpn_enabled == true) ]]; then
        report "OpenVPN port has to be manually opened on UFW firewall"
fi

report "You can now reboot the server"

exit 0