forked from noahpowers/ServerSetup
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserversetup.sh
executable file
·1569 lines (1358 loc) · 56.9 KB
/
serversetup.sh
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
### Variables ###
# If you have NameCheap API access, update these two variables
apikeyValue="<APIKEY>"
usernameValue="<USERNAME>"
# Typically, you do not need to update this variable
updateIP=$(curl icanhazip.com)
### Notification ###
RED='\033[0;31m'
LRED='\033[1;31m'
GREEN='\033[0;32m'
LGREEN='\033[1;32m'
NC='\033[0m' # No Color
if [[ $EUID -ne 0 ]]; then
echo "Please run this script as root" 1>&2
exit 1
fi
### Functions ###
function debian_initialize() {
echo "Updating and Installing Dependencies"
# echo "deb http://ftp.debian.org/debian stretch-backports main" >> /etc/apt/sources.list
apt-get -qq update > /dev/null 2>&1
echo "...keep waiting..."
apt-get -qq -y upgrade > /dev/null 2>&1
echo -n "almost there..."
apt-get install -qq -y nmap jq apache2 curl tcpdump > /dev/null 2>&1
apt-get install -qq -y procmail dnsutils screen zip ufw > /dev/null 2>&1
echo -n "don't be impatient..."
apt-get remove -qq -y exim4 exim4-base exim4-config exim4-daemon-light > /dev/null 2>&1
rm -r /var/log/exim4/ > /dev/null 2>&1
update-rc.d nfs-common disable > /dev/null 2>&1
update-rc.d rpcbind disable > /dev/null 2>&1
echo "IPv6 Disabled"
cat <<-EOF >> /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.eth0.disable_ipv6 = 1
net.ipv6.conf.eth1.disable_ipv6 = 1
net.ipv6.conf.ppp0.disable_ipv6 = 1
net.ipv6.conf.tun0.disable_ipv6 = 1
EOF
sysctl -p > /dev/null 2>&1
echo "Changing Hostname"
read -p "Enter your hostname (e.g. 'mail'): " -r primary_hostname
read -p "Enter your hostname[.]FQDN (e.g. 'mail.foo.example'): " -r primary_domain
read -p "Enter your External IP Address (or range). Enter 10.0.0.0/8 if you are running on AWS: " -r extIP
IFS="." read -ra values <<< "$primary_domain"
dName=${values[1]}
toplevel=${values[2]}
cat <<-EOF > /etc/hosts
127.0.1.1 $primary_hostname $primary_domain
127.0.0.1 localhost $primary_domain
EOF
#Check to see if this is a Cloud instance and update manage_etc_hosts so it doesn't clobber our /etc/hosts changes
if test -f "/etc/cloud/cloud.cfg.d/01_debian_cloud.cfg"; then
sed -i 's/manage_etc_hosts: true/manage_etc_hosts: false/g' /etc/cloud/cloud.cfg.d/01_debian_cloud.cfg
fi
cat <<-EOF > /etc/hostname
$primary_hostname
EOF
read -p "Are you using the NameCheap API for DNS? (y/N)" answer
answer=${answer:-n}
case ${answer:0:1} in
y|Y )
curl "https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.setHosts&ClientIp=${updateIP}&SLD=${dName}&TLD=${toplevel}&HostName1=@&RecordType1=A&Address1=${updateIP}&TTL1=300"
;;
esac
ufw allow from $extIP to any > /dev/null 2>&1
ufw allow from 10.0.0.0/8 > /dev/null 2>&1 # Allows Internal IP space just in case. . .
ufw allow 22/tcp > /dev/null 2>&1
# UFW Deny from Censys.io Scanners: https://support.censys.io/hc/en-us/articles/360043177092-Opt-Out-of-Data-Collection
ufw deny from 162.142.125.0/24 > /dev/null 2>&1
ufw deny from 167.94.138.0/24 > /dev/null 2>&1
ufw deny from 167.94.145.0/24 > /dev/null 2>&1
ufw deny from 167.94.146.0/24 > /dev/null 2>&1
ufw deny from 167.248.133.0/24 > /dev/null 2>&1
ufw deny from 199.45.154.0/24 > /dev/null 2>&1
ufw deny from 199.45.155.0/24 > /dev/null 2>&1
# UFW Deny from Microsoft IP Space
ufw deny from 20.48.0.0/12 to any > /dev/null 2>&1
ufw deny from 20.33.0.0/16 to any > /dev/null 2>&1
ufw deny from 20.36.0.0/14 to any > /dev/null 2>&1
ufw deny from 20.34.0.0/15 to any > /dev/null 2>&1
ufw deny from 20.40.0.0/13 to any > /dev/null 2>&1
ufw deny from 20.128.0.0/16 to any > /dev/null 2>&1
ufw deny from 20.64.0.0/10 to any > /dev/null 2>&1
ufw deny from 20.0.0.0/11 to any > /dev/null 2>&1
ufw deny from 104.208.0.0/13 to any > /dev/null 2>&1
# Allow Web/SSH/DNS
ufw allow 53/tcp > /dev/null 2>&1
ufw allow 53/udp > /dev/null 2>&1
ufw allow 80/tcp > /dev/null 2>&1
ufw allow 443/tcp > /dev/null 2>&1
update-rc.d ufw enable > /dev/null 2>&1
printf 'y\n' | ufw enable > /dev/null 2>&1
echo "The System will now reboot!"
reboot
}
function reset_firewall() {
apt-get install iptables-persistent -q -y > /dev/null 2>&1
iptables -F
echo "Current iptables rules flushed"
cat <<-ENDOFRULES > /etc/iptables/rules.v4
*filter
# Allow all loopback (lo) traffic and reject anything to localhost that does not originate from lo.
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT
-A OUTPUT -o lo -j ACCEPT
# Allow ping and ICMP error returns.
-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT
-A INPUT -p icmp -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
# Allow SSH.
# -A INPUT -i eth0 -p tcp -m state --state NEW,ESTABLISHED --dport 22 -j ACCEPT
# -A OUTPUT -o eth0 -p tcp -m state --state NEW,ESTABLISHED --sport 22 -j ACCEPT
# Allow DNS resolution and limited HTTP/S on eth0.
# Necessary for updating the server and keeping time.
-A INPUT -p udp -m state --state NEW,ESTABLISHED --sport 53 -j ACCEPT
-A OUTPUT -p udp -m state --state NEW,ESTABLISHED --dport 53 -j ACCEPT
-A INPUT -p tcp -m state --state ESTABLISHED --sport 80 -j ACCEPT
-A INPUT -p tcp -m state --state ESTABLISHED --sport 443 -j ACCEPT
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 80 -j ACCEPT
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 443 -j ACCEPT
# Allow Mail Server Traffic outbound
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 143 -j ACCEPT
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 587 -j ACCEPT
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 993 -j ACCEPT
-A OUTPUT -p tcp -m state --state NEW,ESTABLISHED --dport 25 -j ACCEPT
# Allow Mail Server Traffic inbound
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --sport 143 -j ACCEPT
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --sport 587 -j ACCEPT
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --sport 993 -j ACCEPT
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --sport 25 -j ACCEPT
COMMIT
ENDOFRULES
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
cat <<-ENDOFRULES > /etc/iptables/rules.v6
*filter
-A INPUT -j DROP
-A FORWARD -j DROP
-A OUTPUT -j DROP
COMMIT
ENDOFRULES
echo "Loading new firewall rules"
iptables-restore /etc/iptables/rules.v4
ip6tables-restore /etc/iptables/rules.v6
iptables -D ufw-before-input 4 2>&1
iptables -D ufw-before-input 3 2>&1
}
function install_ssl_Cert() {
if [ -d "/opt/letsencrypt/" ]
then
echo $'\n';echo "[ + ] LetsEncrypt already installed. ";echo $'\n'
printf 'y\n' | ufw enable > /dev/null 2>&1
ufw allow 80/tcp > /dev/null 2>&1
ufw allow 443/tcp > /dev/null 2>&1
else
echo $'\nPlease be patient as we download any necessary files...'
service apache2 stop
apt-get update > /dev/null 2>&1
#apt-get install -y python-certbot-apache -t stretch-backports > /dev/null 2>&1
apt-get install -y python3-certbot-apache > /dev/null 2>&1
git clone https://github.com/certbot/certbot.git /opt/letsencrypt > /dev/null 2>&1
fi
cd /opt/letsencrypt
letsencryptdomains=()
end="false"
i=0
read -p "Would you like to setup a wildcard SSL cert (generally Yes)? (y/n)" answer
answer=${answer:-n}
case ${answer:0:1} in
y|Y )
cd /opt/letsencrypt
echo $'\n[!]\tThis script creates a wildcard certificate for all subdomains to your domain'
echo $'\n[!]\tJust enter your domain name (e.g. foo.example)'
echo $'\n'
read -p "Enter your server's domain (e.g. foo.example): " -r domain
read -p "Are you using the NameCheap API for DNS? (y/N)" answer
answer=${answer:-n}
case ${answer:0:1} in
y|Y )
IFS="." read -ra values <<< "$domain"
sld=${values[0]}
tld=${values[1]}
echo $'\nUse this reference API call to enter the upcoming certbot ACME challenges:'
echo "curl \"https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.setHosts&ClientIp=${updateIP}&SLD=${sld}&TLD=${tld}&HostName1=_acme-challenge&RecordType1=TXT&Address1=<CERTBOT-TXT-1>&TTL1=300&HostName2=_acme-challenge&RecordType2=TXT&Address1=<CERTBOT-TXT-2>&TTL2=300\""
echo $'\nBe aware that this API call will REPLACE (not append to) all current entries in NameCheap'
echo "See https://www.namecheap.com/support/api/methods/domains-dns/set-hosts/"
echo $'\n'
;;
esac
command="certbot certonly --manual --register-unsafely-without-email --agree-tos --preferred-challenges dns -d '${domain},*.${domain}'"
eval $command
printf 'y\n' | ufw enable > /dev/null 2>&1
;;
* )
echo $'\nRemember to make records for both \twww.FQDN\tand\tFQDN\n'
while [ "$end" != "true" ]
do
read -p "Enter your server's domain or done to exit: " -r domain
if [ "$domain" != "done" ]
then
letsencryptdomains[$i]=$domain
else
end="true"
fi
((i++))
done
command="certbot certonly --standalone "
for i in "${letsencryptdomains[@]}";
do
command="$command -d $i"
done
command="$command -n --register-unsafely-without-email --agree-tos"
eval $command
printf 'y\n' | ufw enable > /dev/null 2>&1
;;
esac
}
function install_postfix_dovecot() {
printf 'y\n' | ufw enable > /dev/null 2>&1
ufw allow 587/tcp > /dev/null 2>&1
ufw allow 993/tcp > /dev/null 2>&1
ufw allow 25/tcp > /dev/null 2>&1
password=$(openssl rand -hex 10 | base64)
adduser mailarchive --quiet --disabled-password --shell /usr/sbin/nologin --gecos "" > /dev/null 2>&1
echo "mailarchive:${password}" | chpasswd > /dev/null 2>&1
password2=$(openssl rand -hex 10 | base64)
adduser mailcheck --quiet --disabled-password --shell /usr/sbin/nologin --gecos "" > /dev/null 2>&1
echo "mailcheck:${password2}" | chpasswd > /dev/null 2>&1
echo $'\nInstalling Dependencies\n'
apt-get install -qq -y mariadb-server
systemctl enable mariadb --now
apt-get install -qq -y dovecot-common dovecot-imapd dovecot-lmtpd
apt-get install -qq -y postfix postgrey postfix-policyd-spf-python
apt-get install -qq -y opendkim opendkim-tools
apt-get install -qq -y opendmarc
apt-get install -qq -y mailutils
echo $'\n[ ] We use the "mailarchive" account to archive sent emails.\n'
echo $'###################################################################' #'
echo "# [ + ] 'mailarchive' password is: ${password} #"
echo $'###################################################################\n'
echo $'\n[ ] We use the "mailcheck" account to verify any email problems.\n'
echo $'###################################################################' #'
echo "# [ + ] 'mailcheck' password is: ${password2} #"
echo $'###################################################################\n'
read -p "Enter your mail server's domain (everything after the '@' sign e.g. foo.example): " -r primary_domain
echo $'\n'
read -p "Enter IPs or CIDRs to allow Relay, such as other Teamservers or GoPhish External (if none just hit enter): " -r relay_ip
echo $'\n[ ] Configuring Postfix'
cat <<-EOF > /etc/postfix/main.cf
smtpd_banner = \$myhostname ESMTP \$mail_name (Debian/GNU)
biff = no
append_dot_mydomain = no
readme_directory = no
smtpd_tls_cert_file=/etc/letsencrypt/live/${primary_domain}/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/${primary_domain}/privkey.pem
smtpd_tls_security_level = may
smtp_tls_security_level = may
smtpd_tls_protocols = !SSLv2, !SSLv3
smtpd_tls_session_cache_database = btree:\${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:\${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = ${primary_domain}
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = ${primary_domain}
mydestination = ${primary_domain}, localhost.com, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 ${relay_ip}
mailbox_command = procmail -a "\$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:12301,inet:localhost:54321
non_smtpd_milters = inet:12301,inet:localhost:54321
disable_vrfy_command = yes
smtp_tls_note_starttls_offer = yes
always_bcc = mailarchive@${primary_domain}
smtpd_discard_ehlo_keyword_address_maps = cidr:/etc/postfix/esmtp_access
notify_classes = bounce, delay, policy, protocol, resource, software
bounce_notice_recipient = mailcheck
delay_notice_recipient = mailcheck
error_notice_recipient = mailcheck
EOF
cat <<-EOF >> /etc/postfix/esmtp_access
# Allow DSN requests from local subnet only
192.168.0.0/16 silent-discard
172.16.0.0/16 silent-discard
0.0.0.0/0 silent-discard, dsn
::/0 silent-discard, dsn
EOF
cat <<-EOF >> /etc/postfix/master.cf
submission inet n - - - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_wrappermode=no
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
-o smtpd_sender_restrictions=reject_unknown_sender_domain
-o milter_macro_daemon_name=ORIGINATING
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth
EOF
echo "Configuring Opendkim"
mkdir -p "/etc/opendkim/keys/${primary_domain}"
mkdir -p "/etc/opendkim/debug"
cp /etc/opendkim.conf /etc/opendkim.conf.orig
cat <<-EOF > /etc/opendkim.conf
domain *
AutoRestart Yes
AutoRestartRate 10/1h
Umask 0002
Syslog Yes
SyslogSuccess Yes
LogWhy Yes
Canonicalization relaxed/simple
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
InternalHosts refile:/etc/opendkim/TrustedHosts
KeyFile /etc/opendkim/keys/${primary_domain}/mail.private
Selector mail
Mode sv
PidFile /var/run/opendkim/opendkim.pid
SignatureAlgorithm rsa-sha256
UserID opendkim:opendkim
Socket inet:12301@localhost
SignHeaders Date,Subject,To,From,List-ID,List-Unsubscribe,List-Unsubscribe-Post
EOF
cat <<-EOF > /etc/opendkim/TrustedHosts
127.0.0.1
localhost
${primary_domain}
${relay_ip}
EOF
cd "/etc/opendkim/keys/${primary_domain}" || exit
opendkim-genkey -b 1024 -s mail -d "${primary_domain}"
echo 'SOCKET="inet:12301"' >> /etc/default/opendkim
chown -R opendkim:opendkim /etc/opendkim
echo "Configuring opendmarc"
cat <<-EOF > /etc/opendmarc.conf
AuthservID ${primary_domain}
PidFile /var/run/opendmarc/opendmarc.pid
RejectFailures false
Syslog true
TrustedAuthservIDs ${primary_domain}
Socket inet:54321@localhost
UMask 0002
UserID opendmarc:opendmarc
IgnoreHosts /etc/opendmarc/ignore.hosts
HistoryFile /var/run/opendmarc/opendmarc.dat
EOF
mkdir "/etc/opendmarc/"
echo "localhost" > /etc/opendmarc/ignore.hosts
chown -R opendmarc:opendmarc /etc/opendmarc
echo 'SOCKET="inet:54321"' >> /etc/default/opendmarc
echo "Configuring Dovecot"
cat <<-EOF > /etc/dovecot/dovecot.conf
log_path = /var/log/dovecot.log
auth_verbose=yes
auth_debug=yes
auth_debug_passwords=yes
mail_debug=yes
verbose_ssl=yes
disable_plaintext_auth = no
mail_privileged_group = mail
mail_location = mbox:~/mail:INBOX=/var/mail/%u
userdb {
driver = passwd
}
passdb {
args = %s
driver = pam
}
protocols = "imap"
#protocol imap {
# mail_plugins = " autocreate"
#}
#
#plugin {
# autocreate = Trash
# autocreate2 = Sent
# autosubscribe = Trash
# autosubscribe2 = Sent
#}
namespace inbox {
inbox = yes
mailbox Trash {
auto = subscribe
special_use = \Trash
}
mailbox Sent {
auto = subscribe
special_use = \Sent
}
}
service imap-login {
inet_listener imap {
port = 0
}
inet_listener imaps {
port = 993
}
}
service auth {
unix_listener /var/spool/postfix/private/auth {
group = postfix
mode = 0660
user = postfix
}
}
ssl=required
ssl_cert=</etc/letsencrypt/live/${primary_domain}/fullchain.pem
ssl_key=</etc/letsencrypt/live/${primary_domain}/privkey.pem
EOF
cat <<-EOF > /etc/pam.d/imap
#%PAM-1.0
auth required pam_unix.so nullok
account required pam_unix.so
EOF
cat <<-EOF > /etc/logrotate.d/dovecot
# dovecot SIGUSR1: Re-opens the log files.
/var/log/dovecot*.log {
missingok
notifempty
delaycompress
sharedscripts
postrotate
/bin/kill -USR1 `cat /var/run/dovecot/master.pid 2>/dev/null` 2> /dev/null || true
endscript
}
EOF
# read -p "What user would you like to assign to recieve email for root: " -r user_name
# echo "${user_name}: root" >> /etc/aliases
# echo "root email assigned to ${user_name}"
echo "Restarting Services"
service postfix restart
service opendkim restart
service opendmarc restart
service dovecot restart
echo "Checking Service Status"
service postfix status
service opendkim status
service opendmarc status
service dovecot status
printf 'y\n' | ufw enable > /dev/null 2>&1
}
function always_https() {
mkdir -p /var/www/html/donate > /dev/null 2>&1
mkdir -p /var/www/html/archive > /dev/null 2>&1
cd /var/www/html/
wget -l 1 -O index.html https://blog.charitywater.org/ > /dev/null 2>&1
cd /var/www/html/donate
wget -l 1 -O index.html https://blog.charitywater.org/donate > /dev/null 2>&1
cd /var/www/html/archive
wget -l 1 -O index.html https://blog.charitywater.org/archive > /dev/null 2>&1
read -p 'What is your URL (e.g.www.example.com)? ' -r webaddr
a2enmod rewrite
service apache2 stop > /dev/null
a2enmod ssl > /dev/null
a2enmod headers > /dev/null
a2enmod http2 > /dev/null
cd /etc/apache2/sites-enabled/
a2dissite 000-default > /dev/null 2>&1
a2dissite default-ssl > /dev/null 2>&1
a2dissite 000-default.conf > /dev/null 2>&1
a2dissite default-ssl.conf > /dev/null 2>&1
if [ ! -f /etc/apache2/sites-available/000-default.conf-bkup ];
then echo "[ - ] backing-up 000-default.conf";
cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf-bkup;
else echo "[ / ] 000-default.conf already backed up at some point";
fi
if [ ! -f /etc/apache2/sites-available/default-ssl.conf-bkup ];
then printf "[ - ] backing-up default-ssl.conf";
cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf-bkup;
else echo "[ / ] default-ssl.conf already backed up at some point"
fi
cat <<-EOF > /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory "/var/www/html">
AllowOverride All
</Directory>
ErrorLog \${APACHE_LOG_DIR}/error.log
CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF
echo "[ + ] Writing SSL config file"
cat <<-EOF > /etc/apache2/sites-available/default-ssl.conf
<IfModule mod_ssl.c>
SSLStaplingCache shmcb:/var/logs/apache2/ocsp(128000)
<VirtualHost _default_:443>
<Directory "/var/www/html">
AllowOverride All
</Directory>
Protocols h2 http/1.1
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Access-Control-Allow-Origin "*"
Header always set X-Xss-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Feature-Policy "speaker *"
RequestHeader set X-HTTPS 1
Header set Referrer-Policy "no-referrer-when-downgrade"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog \${APACHE_LOG_DIR}/error.log
CustomLog \${APACHE_LOG_DIR}/access.log combined
SSLProtocol -TLSv1.1 +TLSv1.2 -SSLv2 -SSLv3
SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:HIGH:!aNULL:!MD5
SSLHonorCipherOrder on
SSLCompression off
SSLUseStapling on
SSLSessionTickets off
SSLCertificateFile /etc/letsencrypt/live/${webaddr}/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/${webaddr}/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/${webaddr}/chain.pem
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
</VirtualHost>
</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF
echo "[ + ] Creating HTACCESS file with REWRITE rules"
cat <<-EOF > /var/www/html/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
EOF
cd /var/www/ && chown -R www-data:www-data html/ > /dev/null 2>&1
cd /etc/apache2/sites-available/
echo "[ + ] Restarting Apache2"
service apache2 start > /dev/null
echo "[ + ] Enabling HTTP-S site"
a2ensite default-ssl.conf > /dev/null
echo "[ + ] Enabling HTTP site"
a2ensite 000-default.conf > /dev/null
echo "[ + ] Restarting Apache2"
service apache2 reload > /dev/null
sleep 3
if [ $(lsof -nPi | grep -i apache | grep -c ":443 (LISTEN)") -ge 1 ];
then echo '[+] Apache2 SSL is running!'
fi
printf 'y\n' | ufw enable > /dev/null 2>&1
}
function httpsc2doneright(){
echo -n "NOTE: Traffic profiles should only be added to https communications!"
echo ""
read -p "Enter your core domain name (e.g. github.com) [ENTER]: " -r domain
echo ""
#read -p "Enter a random password to be used for the Java Keystore [ENTER]: " -r password
#echo ""
cslocation="/opt/cobaltstrike"
read -e -i "$cslocation" -p "Enter the folder-path to cobaltstrike (tip: Use tab complete) [ENTER]: " -r cobaltStrike
cobaltStrike="${cobaltStrike:-$cslocation}"
echo
password=$(openssl rand -hex 10 | base64)
domainPkcs="$domain.p12"
domainStore="$domain.store"
cobaltStrikeProfilePath="$cobaltStrike/httpsProfile"
cd /etc/letsencrypt/live/$domain
echo '[Starting] Building PKCS12 .p12 cert.'
openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out $domainPkcs -name $domain -passout pass:$password
echo '[Success] Built $domainPkcs PKCS12 cert.'
echo '[Starting] Building Java keystore via keytool.'
keytool -importkeystore -deststorepass $password -destkeypass $password -destkeystore $domainStore -srckeystore $domainPkcs -srcstoretype PKCS12 -srcstorepass $password -alias $domain
echo '[Success] Java keystore $domainStore built.'
mkdir $cobaltStrikeProfilePath
cp $domainStore $cobaltStrikeProfilePath
echo '[Success] Moved Java keystore to CS profile Folder.'
cd $cobaltStrikeProfilePath
echo '[Starting] Cloning into amazon.profile for testing.'
wget https://raw.githubusercontent.com/rsmudge/Malleable-C2-Profiles/master/normal/amazon.profile --no-check-certificate -O amazon.profile
wget https://raw.githubusercontent.com/rsmudge/Malleable-C2-Profiles/master/normal/ocsp.profile --no-check-certificate -O ocsp.profile
echo '[Success] ocsp.profile cloned.'
echo '[Starting] Adding java keystore / password to amazon.profile.'
echo " " >> amazon.profile
echo 'https-certificate {' >> amazon.profile
echo set keystore \"$domainStore\"\; >> amazon.profile
echo set password \"$password\"\; >> amazon.profile
echo '}' >> amazon.profile
echo '[Success] amazon.profile updated with HTTPs settings.'
echo '[Starting] Adding java keystore / password to oscp.profile.'
echo " " >> ocsp.profile
echo 'https-certificate {' >> ocsp.profile
echo set keystore \"$domainStore\"\; >> ocsp.profile
echo set password \"$password\"\; >> ocsp.profile
echo '}' >> ocsp.profile
echo '[Success] ocsp.profile updated with HTTPs settings.'
}
function get_dns_entries() {
extip=$(curl icanhazip.com)
domain=$(ls /etc/opendkim/keys/ | head -1)
fields=$(echo "${domain}" | tr '.' '\n' | wc -l)
dkimrecord=$(cut -d '"' -f 2 "/etc/opendkim/keys/${domain}/mail.txt" | tr -d "[:space:]")
# dName=$( cat /etc/hosts | cut -d"." -f5 | uniq )
# toplevel=$( cat /etc/hosts | cut -d"." -f6 | uniq )
# fulldomain=$( cat /etc/hosts | cut -d"." -f5-7 | uniq )
dkim2=$( echo ${dkimrecord} | sed -r 's/\+/\%2B/g' | sed -r 's/\=/\%3D/g' | sed -r 's/\;/\%3B/g' | sed -r 's/\//\%2F/g' )
dmarcTemp0="v=DMARC1; p=reject; rua=mailto:postmaster@${domain}"
dmarcTemp1=$( echo ${dmarcTemp0} | sed -r 's/\=/\%3D/g' | sed -r 's/\;/\%3B/g' | sed -r 's/\ /\%20/g' )
if [[ $fields -eq 2 ]]; then
fulldomain=$( cat /etc/hosts | cut -d"." -f5-6 | uniq )
dName=$( cat /etc/hosts | cut -d"." -f5 | uniq )
toplevel=$( cat /etc/hosts | cut -d"." -f6 | uniq )
cat <<-EOF > dnsentries.txt
DNS Entries for ${domain}:
====================================================================
Namecheap - Enter under Advanced DNS
Record Type: A
Host: @
Value: ${extip}
TTL: 5 min
Record Type: TXT
Host: @
Value: v=spf1 ip4:${extip} -all
TTL: 5 min
Record Type: TXT
Host: mail._domainkey
Value: ${dkimrecord}
TTL: 5 min
Record Type: TXT
Host: ._dmarc
Value: v=DMARC1; p=reject; rua=mailto:postmaster@${domain}
TTL: 5 min
Change Mail Settings to Custom MX and Add New Record
Record Type: MX
Host: @
Value: ${domain}
Priority: 10
TTL: 5 min
EOF
read -p "Are you using the NameCheap API for DNS? (y/N)" answer
answer=${answer:-n}
case ${answer:0:1} in
y|Y )
curl -v "https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.setHosts&ClientIp=${updateIP}&SLD=${dName}&TLD=${toplevel}&HostName1=@&RecordType1=A&Address1=${extip}&TTL1=300&HostName2=www&RecordType2=A&Address2=${extip}&TTL2=300&HostName3=mail&RecordType3=A&Address3=${extip}&TTL3=300&HostName4=@&RecordType4=MX&Address4=${fulldomain}&TTL4=300&MXPref4=10&EmailType=MX&HostName5=@&RecordType5=TXT&Address5=v=spf1+ip4:${extip}%20-all&TTL5=300&HostName6=mail._domainkey&RecordType6=TXT&Address6=${dkim2}&TTL6=300&HostName7=._dmarc&RecordType7=TXT&Address7=${dmarcTemp1}&TTL7=300&HostName8=temp&RecordType8=A&Address8=${extip}&TTL8=60&HostName9=dns&RecordType9=A&Address9=${extip}&TTL9=300&&HostName10=ns1&RecordType10=NS&Address10=dns.${fulldomain}.&TTL10=300"
echo "Current NameCheap Records:"
curl -v "https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.getHosts&ClientIp=${updateIP}&SLD=${dName}&TLD=${toplevel}"
cat dnsentries.txt
;;
* )
cat dnsentries.txt
;;
esac
else
fulldomain=$( cat /etc/hosts | cut -d"." -f6-7 | uniq )
dName=$( cat /etc/hosts | cut -d"." -f6 | uniq )
toplevel=$( cat /etc/hosts | cut -d"." -f7 | uniq )
namehost=$( cat /etc/hostname | grep -E -iv "localhost|127.0.0.1" )
prefix=$( echo "${domain}" | rev | cut -d '.' -f 3- | rev )
cat <<-EOF > dnsentries.txt
DNS Entries for ${domain}:
====================================================================
Namecheap - Enter under Advanced DNS
Record Type: A
Host: ${prefix}
Value: ${extip}
TTL: 5 min
Record Type: A
Host: ${namehost}
Value: ${extip}
TTL: 5 min
Record Type: TXT
Host: ${prefix}
Value: v=spf1 ip4:${extip} -all
TTL: 5 min
Record Type: TXT
Host: mail._domainkey.${prefix}
Value: ${dkimrecord}
TTL: 5 min
Record Type: TXT
Host: ._dmarc.${prefix}
Value: v=DMARC1; p=reject
TTL: 5 min
Change Mail Settings to Custom MX and Add New Record
Record Type: MX
Host: ${prefix}
Value: ${domain}
Priority: 10
TTL: 5 min
EOF
read -p "Are you using the NameCheap API for DNS? (y/N)" answer
answer=${answer:-n}
case ${answer:0:1} in
y|Y )
curl -v "https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.setHosts&ClientIp=${updateIP}&SLD=${dName}&TLD=${toplevel}&HostName1=@&RecordType1=A&Address1=${extip}&TTL1=300&HostName2=www&RecordType2=A&Address2=${extip}&TTL2=300&HostName3=mail&RecordType3=A&Address3=${extip}&TTL3=300&HostName4=@&RecordType4=MX&Address4=${fulldomain}&TTL4=300&MXPref4=10&EmailType=MX&HostName5=@&RecordType5=TXT&Address5=v=spf1+ip4:${extip}%20-all&TTL5=300&HostName6=mail._domainkey&RecordType6=TXT&Address6=${dkim2}&TTL6=300&HostName7=._dmarc&RecordType7=TXT&Address7=${dmarcTemp1}&TTL7=300&HostName8=temp&RecordType8=A&Address8=${extip}&TTL8=60&HostName9=dns&RecordType9=A&Address9=${extip}&TTL9=300&&HostName10=ns1&RecordType10=NS&Address10=dns.${fulldomain}.&TTL10=300"
echo "Current NameCheap Records:"
curl -v "https://api.namecheap.com/xml.response?ApiUser=${usernameValue}&ApiKey=${apikeyValue}&UserName=${usernameValue}&Command=namecheap.domains.dns.getHosts&ClientIp=${updateIP}&SLD=${dName}&TLD=${toplevel}"
cat dnsentries.txt
;;
* )
cat dnsentries.txt
;;
esac
fi
}
function roll_domain() {
read -p ' Your NEW Domain (everything after the @ sign): ' -r newDomain
mkdir -p /etc/opendkim/old-keys/
cp -a /etc/opendkim/keys/* /etc/opendkim/old-keys/
rm -rf /etc/opendkim/keys/*
mkdir -p "/etc/opendkim/keys/${newDomain}"
cd "/etc/opendkim/keys/${newDomain}" || exit
opendkim-genkey -b 1024 -s mail -d "${newDomain}"
cat <<-EOF > /etc/opendkim.conf
domain *
AutoRestart Yes
AutoRestartRate 10/1h
Umask 0002
Syslog Yes
SyslogSuccess Yes
LogWhy Yes
Canonicalization relaxed/simple
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
InternalHosts refile:/etc/opendkim/TrustedHosts
KeyFile /etc/opendkim/keys/${newDomain}/mail.private
Selector mail
Mode sv
PidFile /var/run/opendkim/opendkim.pid
SignatureAlgorithm rsa-sha256
UserID opendkim:opendkim
Socket inet:12301@localhost
SignHeaders Date,Subject,To,From,List-ID,List-Unsubscribe,List-Unsubscribe-Post
EOF
cat <<-EOF > /etc/opendmarc.conf
AuthservID ${newDomain}
PidFile /var/run/opendmarc/opendmarc.pid
RejectFailures false
Syslog true
TrustedAuthservIDs ${newDomain}
Socket inet:54321@localhost
UMask 0002
UserID opendmarc:opendmarc
IgnoreHosts /etc/opendmarc/ignore.hosts
HistoryFile /var/run/opendmarc/opendmarc.dat
EOF
cat <<-EOF > /etc/hostname
127.0.0.1
localhost
${newDomain}
EOF
echo "${newDomain}" > /etc/mailname
cat <<-EOF > /etc/hosts
127.0.1.1 mail mail.${newDomain}
127.0.0.1 localhost mail.${newDomain}
EOF
cat <<-EOF > /etc/opendkim/TrustedHosts
127.0.1.1
localhost
${newDomain}
EOF
chown -R opendkim:opendkim /etc/opendkim/
cat <<-EOF > /etc/postfix/main.cf
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
append_dot_mydomain = no
readme_directory = no
smtpd_tls_cert_file=/etc/letsencrypt/live/${newDomain}/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/${newDomain}/privkey.pem
smtpd_tls_security_level = may
smtp_tls_security_level = may
smtpd_tls_protocols = !SSLv2, !SSLv3
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = ${newDomain}
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = ${newDomain}
mydestination = ${newDomain}, localhost.com, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = ipv4
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:12301,inet:localhost:54321
non_smtpd_milters = inet:12301,inet:localhost:54321
disable_vrfy_command = yes
smtp_tls_note_starttls_offer = yes
always_bcc = mailarchive@${newDomain}
EOF
cat <<-EOF > /etc/dovecot/dovecot.conf
log_path = /var/log/dovecot.log
auth_verbose=yes
auth_debug=yes
auth_debug_passwords=yes
mail_debug=yes
verbose_ssl=yes
disable_plaintext_auth = no
mail_privileged_group = mail
mail_location = mbox:~/mail:INBOX=/var/mail/%u
userdb {
driver = passwd
}
passdb {
args = %s
driver = pam
}
protocols = " imap"
protocol imap {
mail_plugins = " autocreate"
}
plugin {
autocreate = Trash
autocreate2 = Sent
autosubscribe = Trash
autosubscribe2 = Sent
}
service imap-login {
inet_listener imap {
port = 0
}
inet_listener imaps {
port = 993
}
}
service auth {
unix_listener /var/spool/postfix/private/auth {
group = postfix
mode = 0660
user = postfix
}
}
ssl=required
ssl_cert = </etc/letsencrypt/live/${newDomain}/fullchain.pem
ssl_key = </etc/letsencrypt/live/${newDomain}/privkey.pem
EOF
echo "Restarting Services"
service postfix restart
service opendkim restart
service opendmarc restart
service dovecot restart
echo "Checking Service Status"
service postfix status
service opendkim status
service opendmarc status
service dovecot status
printf 'y\n' | ufw enable > /dev/null 2>&1
}
function sender_account() {
echo $'\n'
read -p '[ ] Enter an (all lowercase) account name for the email sender:' -r accountname
accountpassword=$(openssl rand -hex 10 | base64)
credentials="[ + ] ${accountname} password is: ${accountpassword}"
topline="###########################################################################"
bottomline=$topline
echo $'\n';echo $topline
echo $credentials
echo $bottomline;echo $'\n'
adduser ${accountname} --quiet --force-badname --disabled-password --shell /usr/sbin/nologin --gecos "" > /dev/null 2>&1
echo "${accountname}:${accountpassword}" | chpasswd > /dev/null 2>&1
mkdir -p /home/${accountname}/mail
chown -R ${accountname}:${accountname} /home/${accountname}/
printf 'y\n' | ufw enable > /dev/null 2>&1
}
function check_dkim() {
read -p '[ ] What domain will emails come from? ' -r domain
echo -e "\n[ / ] Checking DKIM Record propagation "
sleep 1
dnsDKIM=$(dig +short -t TXT mail._domainkey.${domain} | tr -d "\"" | tr -d " ")
localDKIM=""
if [ -f /etc/opendkim/keys/${domain}/mail.txt ]; then
localDKIM=$(cat /etc/opendkim/keys/${domain}/mail.txt | tr -d "\n" | tr -d "\t" | cut -f 2 -d "(" | cut -f 1 -d ")" |tr -d " " | tr -d "\"")
else
echo "[ - ] WARNING: Can not find local DKIM record for that domain"
fi