-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
3454 lines (3048 loc) · 99.9 KB
/
main.go
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
package main
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/exp/slices"
"github.com/mjl-/adns"
"github.com/mjl-/autocert"
"github.com/mjl-/bstore"
"github.com/mjl-/sconf"
"github.com/mjl-/sherpa"
"github.com/mjl-/mox/config"
"github.com/mjl-/mox/dane"
"github.com/mjl-/mox/dkim"
"github.com/mjl-/mox/dmarc"
"github.com/mjl-/mox/dmarcdb"
"github.com/mjl-/mox/dmarcrpt"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/dnsbl"
"github.com/mjl-/mox/message"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/moxio"
"github.com/mjl-/mox/moxvar"
"github.com/mjl-/mox/mtasts"
"github.com/mjl-/mox/publicsuffix"
"github.com/mjl-/mox/smtp"
"github.com/mjl-/mox/smtpclient"
"github.com/mjl-/mox/spf"
"github.com/mjl-/mox/store"
"github.com/mjl-/mox/tlsrpt"
"github.com/mjl-/mox/tlsrptdb"
"github.com/mjl-/mox/updates"
"github.com/mjl-/mox/webadmin"
)
var (
changelogDomain = "xmox.nl"
changelogURL = "https://updates.xmox.nl/changelog"
changelogPubKey = base64Decode("sPNiTDQzvb4FrytNEiebJhgyQzn57RwEjNbGWMM/bDY=")
)
func base64Decode(s string) []byte {
buf, err := base64.StdEncoding.DecodeString(s)
if err != nil {
panic(err)
}
return buf
}
func envString(k, def string) string {
s := os.Getenv(k)
if s == "" {
return def
}
return s
}
var commands = []struct {
cmd string
fn func(c *cmd)
}{
{"serve", cmdServe},
{"quickstart", cmdQuickstart},
{"stop", cmdStop},
{"setaccountpassword", cmdSetaccountpassword},
{"setadminpassword", cmdSetadminpassword},
{"loglevels", cmdLoglevels},
{"queue list", cmdQueueList},
{"queue kick", cmdQueueKick},
{"queue drop", cmdQueueDrop},
{"queue dump", cmdQueueDump},
{"import maildir", cmdImportMaildir},
{"import mbox", cmdImportMbox},
{"export maildir", cmdExportMaildir},
{"export mbox", cmdExportMbox},
{"localserve", cmdLocalserve},
{"help", cmdHelp},
{"backup", cmdBackup},
{"verifydata", cmdVerifydata},
{"config test", cmdConfigTest},
{"config dnscheck", cmdConfigDNSCheck},
{"config dnsrecords", cmdConfigDNSRecords},
{"config describe-domains", cmdConfigDescribeDomains},
{"config describe-static", cmdConfigDescribeStatic},
{"config account add", cmdConfigAccountAdd},
{"config account rm", cmdConfigAccountRemove},
{"config address add", cmdConfigAddressAdd},
{"config address rm", cmdConfigAddressRemove},
{"config domain add", cmdConfigDomainAdd},
{"config domain rm", cmdConfigDomainRemove},
{"config describe-sendmail", cmdConfigDescribeSendmail},
{"config printservice", cmdConfigPrintservice},
{"config ensureacmehostprivatekeys", cmdConfigEnsureACMEHostprivatekeys},
{"example", cmdExample},
{"checkupdate", cmdCheckupdate},
{"cid", cmdCid},
{"clientconfig", cmdClientConfig},
{"deliver", cmdDeliver},
// todo: turn cmdDANEDialmx into a regular "dialmx" command that follows mta-sts policy, with options to require dane, mta-sts or requiretls. the code will be similar to queue/direct.go
{"dane dial", cmdDANEDial},
{"dane dialmx", cmdDANEDialmx},
{"dane makerecord", cmdDANEMakeRecord},
{"dns lookup", cmdDNSLookup},
{"dkim gened25519", cmdDKIMGened25519},
{"dkim genrsa", cmdDKIMGenrsa},
{"dkim lookup", cmdDKIMLookup},
{"dkim txt", cmdDKIMTXT},
{"dkim verify", cmdDKIMVerify},
{"dkim sign", cmdDKIMSign},
{"dmarc lookup", cmdDMARCLookup},
{"dmarc parsereportmsg", cmdDMARCParsereportmsg},
{"dmarc verify", cmdDMARCVerify},
{"dmarc checkreportaddrs", cmdDMARCCheckreportaddrs},
{"dnsbl check", cmdDNSBLCheck},
{"dnsbl checkhealth", cmdDNSBLCheckhealth},
{"mtasts lookup", cmdMTASTSLookup},
{"retrain", cmdRetrain},
{"sendmail", cmdSendmail},
{"spf check", cmdSPFCheck},
{"spf lookup", cmdSPFLookup},
{"spf parse", cmdSPFParse},
{"tlsrpt lookup", cmdTLSRPTLookup},
{"tlsrpt parsereportmsg", cmdTLSRPTParsereportmsg},
{"version", cmdVersion},
{"bumpuidvalidity", cmdBumpUIDValidity},
{"reassignuids", cmdReassignUIDs},
{"fixuidmeta", cmdFixUIDMeta},
{"fixmsgsize", cmdFixmsgsize},
{"reparse", cmdReparse},
{"ensureparsed", cmdEnsureParsed},
{"recalculatemailboxcounts", cmdRecalculateMailboxCounts},
{"message parse", cmdMessageParse},
{"reassignthreads", cmdReassignthreads},
// Not listed.
{"helpall", cmdHelpall},
{"junk analyze", cmdJunkAnalyze},
{"junk check", cmdJunkCheck},
{"junk play", cmdJunkPlay},
{"junk test", cmdJunkTest},
{"junk train", cmdJunkTrain},
{"dmarcdb addreport", cmdDMARCDBAddReport},
{"tlsrptdb addreport", cmdTLSRPTDBAddReport},
{"updates addsigned", cmdUpdatesAddSigned},
{"updates genkey", cmdUpdatesGenkey},
{"updates pubkey", cmdUpdatesPubkey},
{"updates serve", cmdUpdatesServe},
{"updates verify", cmdUpdatesVerify},
{"gentestdata", cmdGentestdata},
{"ximport maildir", cmdXImportMaildir},
{"ximport mbox", cmdXImportMbox},
{"openaccounts", cmdOpenaccounts},
{"readmessages", cmdReadmessages},
}
var cmds []cmd
func init() {
for _, xc := range commands {
c := cmd{words: strings.Split(xc.cmd, " "), fn: xc.fn}
cmds = append(cmds, c)
}
}
type cmd struct {
words []string
fn func(c *cmd)
// Set before calling command.
flag *flag.FlagSet
flagArgs []string
_gather bool // Set when using Parse to gather usage for a command.
// Set by invoked command or Parse.
unlisted bool // If set, command is not listed until at least some words are matched from command.
params string // Arguments to command. Multiple lines possible.
help string // Additional explanation. First line is synopsis, the rest is only printed for an explicit help/usage for that command.
args []string
}
func (c *cmd) Parse() []string {
// To gather params and usage information, we just run the command but cause this
// panic after the command has registered its flags and set its params and help
// information. This is then caught and that info printed.
if c._gather {
panic("gather")
}
c.flag.Usage = c.Usage
c.flag.Parse(c.flagArgs)
c.args = c.flag.Args()
return c.args
}
func (c *cmd) gather() {
c.flag = flag.NewFlagSet("mox "+strings.Join(c.words, " "), flag.ExitOnError)
c._gather = true
defer func() {
x := recover()
// panic generated by Parse.
if x != "gather" {
panic(x)
}
}()
c.fn(c)
}
func (c *cmd) makeUsage() string {
var r strings.Builder
cs := "mox " + strings.Join(c.words, " ")
for i, line := range strings.Split(strings.TrimSpace(c.params), "\n") {
s := ""
if i == 0 {
s = "usage:"
}
if line != "" {
line = " " + line
}
fmt.Fprintf(&r, "%6s %s%s\n", s, cs, line)
}
c.flag.SetOutput(&r)
c.flag.PrintDefaults()
return r.String()
}
func (c *cmd) printUsage() {
fmt.Fprint(os.Stderr, c.makeUsage())
if c.help != "" {
fmt.Fprint(os.Stderr, "\n"+c.help+"\n")
}
}
func (c *cmd) Usage() {
c.printUsage()
os.Exit(2)
}
func cmdHelp(c *cmd) {
c.params = "[command ...]"
c.help = `Prints help about matching commands.
If multiple commands match, they are listed along with the first line of their help text.
If a single command matches, its usage and full help text is printed.
`
args := c.Parse()
if len(args) == 0 {
c.Usage()
}
prefix := func(l, pre []string) bool {
if len(pre) > len(l) {
return false
}
return slices.Equal(pre, l[:len(pre)])
}
var partial []cmd
for _, c := range cmds {
if slices.Equal(c.words, args) {
c.gather()
fmt.Print(c.makeUsage())
if c.help != "" {
fmt.Print("\n" + c.help + "\n")
}
return
} else if prefix(c.words, args) {
partial = append(partial, c)
}
}
if len(partial) == 0 {
fmt.Fprintf(os.Stderr, "%s: unknown command\n", strings.Join(args, " "))
os.Exit(2)
}
for _, c := range partial {
c.gather()
line := "mox " + strings.Join(c.words, " ")
fmt.Printf("%s\n", line)
if c.help != "" {
fmt.Printf("\t%s\n", strings.Split(c.help, "\n")[0])
}
}
}
func cmdHelpall(c *cmd) {
c.unlisted = true
c.help = `Print all detailed usage and help information for all listed commands.
Used to generate documentation.
`
args := c.Parse()
if len(args) != 0 {
c.Usage()
}
n := 0
for _, c := range cmds {
c.gather()
if c.unlisted {
continue
}
if n > 0 {
fmt.Fprintf(os.Stderr, "\n")
}
n++
fmt.Fprintf(os.Stderr, "# mox %s\n\n", strings.Join(c.words, " "))
if c.help != "" {
fmt.Fprintln(os.Stderr, c.help+"\n")
}
s := c.makeUsage()
s = "\t" + strings.ReplaceAll(s, "\n", "\n\t")
fmt.Fprintln(os.Stderr, s)
}
}
func usage(l []cmd, unlisted bool) {
var lines []string
if !unlisted {
lines = append(lines, "mox [-config config/mox.conf] [-pedantic] ...")
}
for _, c := range l {
c.gather()
if c.unlisted && !unlisted {
continue
}
for _, line := range strings.Split(c.params, "\n") {
x := append([]string{"mox"}, c.words...)
if line != "" {
x = append(x, line)
}
lines = append(lines, strings.Join(x, " "))
}
}
for i, line := range lines {
pre := " "
if i == 0 {
pre = "usage: "
}
fmt.Fprintln(os.Stderr, pre+line)
}
os.Exit(2)
}
var loglevel string
var pedantic bool
// subcommands that are not "serve" should use this function to load the config, it
// restores any loglevel specified on the command-line, instead of using the
// loglevels from the config file and it does not load files like TLS keys/certs.
func mustLoadConfig() {
mox.MustLoadConfig(false, false)
if level, ok := mlog.Levels[loglevel]; loglevel != "" && ok {
mox.Conf.Log[""] = level
mlog.SetConfig(mox.Conf.Log)
} else if loglevel != "" && !ok {
log.Fatal("unknown loglevel", mlog.Field("loglevel", loglevel))
}
if pedantic {
moxvar.Pedantic = true
}
}
func main() {
// CheckConsistencyOnClose is true by default, for all the test packages. A regular
// mox server should never use it. But integration tests enable it again with a
// flag.
store.CheckConsistencyOnClose = false
ctxbg := context.Background()
mox.Shutdown = ctxbg
mox.Context = ctxbg
log.SetFlags(0)
// If invoked as sendmail, e.g. /usr/sbin/sendmail, we do enough so cron can get a
// message sent using smtp submission to a configured server.
if len(os.Args) > 0 && filepath.Base(os.Args[0]) == "sendmail" {
c := &cmd{
flag: flag.NewFlagSet("sendmail", flag.ExitOnError),
flagArgs: os.Args[1:],
}
cmdSendmail(c)
return
}
flag.StringVar(&mox.ConfigStaticPath, "config", envString("MOXCONF", filepath.FromSlash("config/mox.conf")), "configuration file, other config files are looked up in the same directory, defaults to $MOXCONF with a fallback to mox.conf")
flag.StringVar(&loglevel, "loglevel", "", "if non-empty, this log level is set early in startup")
flag.BoolVar(&pedantic, "pedantic", false, "protocol violations result in errors instead of accepting/working around them")
flag.BoolVar(&store.CheckConsistencyOnClose, "checkconsistency", false, "dangerous option for testing only, enables data checks that abort/panic when inconsistencies are found")
var cpuprofile, memprofile, tracefile string
flag.StringVar(&cpuprofile, "cpuprof", "", "store cpu profile to file")
flag.StringVar(&memprofile, "memprof", "", "store mem profile to file")
flag.StringVar(&tracefile, "trace", "", "store execution trace to file")
flag.Usage = func() { usage(cmds, false) }
flag.Parse()
args := flag.Args()
if len(args) == 0 {
usage(cmds, false)
}
if tracefile != "" {
defer traceExecution(tracefile)()
}
defer profile(cpuprofile, memprofile)()
if pedantic {
moxvar.Pedantic = true
}
mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
if level, ok := mlog.Levels[loglevel]; ok && loglevel != "" {
mox.Conf.Log[""] = level
mlog.SetConfig(mox.Conf.Log)
// note: SetConfig may be called again when subcommands loads config.
}
var partial []cmd
next:
for _, c := range cmds {
for i, w := range c.words {
if i >= len(args) || w != args[i] {
if i > 0 {
partial = append(partial, c)
}
continue next
}
}
c.flag = flag.NewFlagSet("mox "+strings.Join(c.words, " "), flag.ExitOnError)
c.flagArgs = args[len(c.words):]
c.fn(&c)
return
}
if len(partial) > 0 {
usage(partial, true)
}
usage(cmds, false)
}
func xcheckf(err error, format string, args ...any) {
if err == nil {
return
}
msg := fmt.Sprintf(format, args...)
log.Fatalf("%s: %s", msg, err)
}
func xparseIP(s, what string) net.IP {
ip := net.ParseIP(s)
if ip == nil {
log.Fatalf("invalid %s: %q", what, s)
}
return ip
}
func xparseDomain(s, what string) dns.Domain {
d, err := dns.ParseDomain(s)
xcheckf(err, "parsing %s %q", what, s)
return d
}
func cmdClientConfig(c *cmd) {
c.params = "domain"
c.help = `Print the configuration for email clients for a domain.
Sending email is typically not done on the SMTP port 25, but on submission
ports 465 (with TLS) and 587 (without initial TLS, but usually added to the
connection with STARTTLS). For IMAP, the port with TLS is 993 and without is
143.
Without TLS/STARTTLS, passwords are sent in clear text, which should only be
configured over otherwise secured connections, like a VPN.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
printClientConfig(d)
}
func printClientConfig(d dns.Domain) {
cc, err := mox.ClientConfigsDomain(d)
xcheckf(err, "getting client config")
fmt.Printf("%-20s %-30s %5s %-15s %s\n", "Protocol", "Host", "Port", "Listener", "Note")
for _, e := range cc.Entries {
fmt.Printf("%-20s %-30s %5d %-15s %s\n", e.Protocol, e.Host, e.Port, e.Listener, e.Note)
}
}
func cmdConfigTest(c *cmd) {
c.help = `Parses and validates the configuration files.
If valid, the command exits with status 0. If not valid, all errors encountered
are printed.
`
args := c.Parse()
if len(args) != 0 {
c.Usage()
}
mox.FilesImmediate = true
_, errs := mox.ParseConfig(context.Background(), mox.ConfigStaticPath, true, true, false)
if len(errs) > 1 {
log.Printf("multiple errors:")
for _, err := range errs {
log.Printf("%s", err)
}
os.Exit(1)
} else if len(errs) == 1 {
log.Fatalf("%s", errs[0])
os.Exit(1)
}
fmt.Println("config OK")
}
func cmdConfigDescribeStatic(c *cmd) {
c.params = ">mox.conf"
c.help = `Prints an annotated empty configuration for use as mox.conf.
The static configuration file cannot be reloaded while mox is running. Mox has
to be restarted for changes to the static configuration file to take effect.
This configuration file needs modifications to make it valid. For example, it
may contain unfinished list items.
`
if len(c.Parse()) != 0 {
c.Usage()
}
var sc config.Static
err := sconf.Describe(os.Stdout, &sc)
xcheckf(err, "describing config")
}
func cmdConfigDescribeDomains(c *cmd) {
c.params = ">domains.conf"
c.help = `Prints an annotated empty configuration for use as domains.conf.
The domains configuration file contains the domains and their configuration,
and accounts and their configuration. This includes the configured email
addresses. The mox admin web interface, and the mox command line interface, can
make changes to this file. Mox automatically reloads this file when it changes.
Like the static configuration, the example domains.conf printed by this command
needs modifications to make it valid.
`
if len(c.Parse()) != 0 {
c.Usage()
}
var dc config.Dynamic
err := sconf.Describe(os.Stdout, &dc)
xcheckf(err, "describing config")
}
func cmdConfigPrintservice(c *cmd) {
c.params = ">mox.service"
c.help = `Prints a systemd unit service file for mox.
This is the same file as generated using quickstart. If the systemd service file
has changed with a newer version of mox, use this command to generate an up to
date version.
`
if len(c.Parse()) != 0 {
c.Usage()
}
pwd, err := os.Getwd()
if err != nil {
log.Printf("current working directory: %v", err)
pwd = "/home/mox"
}
service := strings.ReplaceAll(moxService, "/home/mox", pwd)
fmt.Print(service)
}
func cmdConfigDomainAdd(c *cmd) {
c.params = "domain account [localpart]"
c.help = `Adds a new domain to the configuration and reloads the configuration.
The account is used for the postmaster mailboxes the domain, including as DMARC and
TLS reporting. Localpart is the "username" at the domain for this account. If
must be set if and only if account does not yet exist.
`
args := c.Parse()
if len(args) != 2 && len(args) != 3 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
var localpart string
if len(args) == 3 {
localpart = args[2]
}
ctlcmdConfigDomainAdd(xctl(), d, args[1], localpart)
}
func ctlcmdConfigDomainAdd(ctl *ctl, domain dns.Domain, account, localpart string) {
ctl.xwrite("domainadd")
ctl.xwrite(domain.Name())
ctl.xwrite(account)
ctl.xwrite(localpart)
ctl.xreadok()
fmt.Printf("domain added, remember to add dns records, see:\n\nmox config dnsrecords %s\nmox config dnscheck %s\n", domain.Name(), domain.Name())
}
func cmdConfigDomainRemove(c *cmd) {
c.params = "domain"
c.help = `Remove a domain from the configuration and reload the configuration.
This is a dangerous operation. Incoming email delivery for this domain will be
rejected.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
ctlcmdConfigDomainRemove(xctl(), d)
}
func ctlcmdConfigDomainRemove(ctl *ctl, d dns.Domain) {
ctl.xwrite("domainrm")
ctl.xwrite(d.Name())
ctl.xreadok()
fmt.Printf("domain removed, remember to remove dns records for %s\n", d)
}
func cmdConfigAccountAdd(c *cmd) {
c.params = "account address"
c.help = `Add an account with an email address and reload the configuration.
Email can be delivered to this address/account. A password has to be configured
explicitly, see the setaccountpassword command.
`
args := c.Parse()
if len(args) != 2 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAccountAdd(xctl(), args[0], args[1])
}
func ctlcmdConfigAccountAdd(ctl *ctl, account, address string) {
ctl.xwrite("accountadd")
ctl.xwrite(account)
ctl.xwrite(address)
ctl.xreadok()
fmt.Printf("account added, set a password with \"mox setaccountpassword %s\"\n", account)
}
func cmdConfigAccountRemove(c *cmd) {
c.params = "account"
c.help = `Remove an account and reload the configuration.
Email addresses for this account will also be removed, and incoming email for
these addresses will be rejected.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAccountRemove(xctl(), args[0])
}
func ctlcmdConfigAccountRemove(ctl *ctl, account string) {
ctl.xwrite("accountrm")
ctl.xwrite(account)
ctl.xreadok()
fmt.Println("account removed")
}
func cmdConfigAddressAdd(c *cmd) {
c.params = "address account"
c.help = `Adds an address to an account and reloads the configuration.
If address starts with a @ (i.e. a missing localpart), this is a catchall
address for the domain.
`
args := c.Parse()
if len(args) != 2 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAddressAdd(xctl(), args[0], args[1])
}
func ctlcmdConfigAddressAdd(ctl *ctl, address, account string) {
ctl.xwrite("addressadd")
ctl.xwrite(address)
ctl.xwrite(account)
ctl.xreadok()
fmt.Println("address added")
}
func cmdConfigAddressRemove(c *cmd) {
c.params = "address"
c.help = `Remove an address and reload the configuration.
Incoming email for this address will be rejected after removing an address.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
mustLoadConfig()
ctlcmdConfigAddressRemove(xctl(), args[0])
}
func ctlcmdConfigAddressRemove(ctl *ctl, address string) {
ctl.xwrite("addressrm")
ctl.xwrite(address)
ctl.xreadok()
fmt.Println("address removed")
}
func cmdConfigDNSRecords(c *cmd) {
c.params = "domain"
c.help = `Prints annotated DNS records as zone file that should be created for the domain.
The zone file can be imported into existing DNS software. You should review the
DNS records, especially if your domain previously/currently has email
configured.
`
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
domConf, ok := mox.Conf.Domain(d)
if !ok {
log.Fatalf("unknown domain")
}
resolver := dns.StrictResolver{Pkg: "main"}
_, result, err := resolver.LookupTXT(context.Background(), d.ASCII+".")
if !dns.IsNotFound(err) {
xcheckf(err, "looking up record for dnssec-status")
}
records, err := mox.DomainRecords(domConf, d, result.Authentic)
xcheckf(err, "records")
fmt.Print(strings.Join(records, "\n") + "\n")
}
func cmdConfigDNSCheck(c *cmd) {
c.params = "domain"
c.help = "Check the DNS records with the configuration for the domain, and print any errors/warnings."
args := c.Parse()
if len(args) != 1 {
c.Usage()
}
d := xparseDomain(args[0], "domain")
mustLoadConfig()
_, ok := mox.Conf.Domain(d)
if !ok {
log.Fatalf("unknown domain")
}
// todo future: move http.Admin.CheckDomain to mox- and make it return a regular error.
defer func() {
x := recover()
if x == nil {
return
}
err, ok := x.(*sherpa.Error)
if !ok {
panic(x)
}
log.Fatalf("%s", err)
}()
printResult := func(name string, r webadmin.Result) {
if len(r.Errors) == 0 && len(r.Warnings) == 0 {
return
}
fmt.Printf("# %s\n", name)
for _, s := range r.Errors {
fmt.Printf("error: %s\n", s)
}
for _, s := range r.Warnings {
fmt.Printf("warning: %s\n", s)
}
}
result := webadmin.Admin{}.CheckDomain(context.Background(), args[0])
printResult("DNSSEC", result.DNSSEC.Result)
printResult("IPRev", result.IPRev.Result)
printResult("MX", result.MX.Result)
printResult("TLS", result.TLS.Result)
printResult("DANE", result.DANE.Result)
printResult("SPF", result.SPF.Result)
printResult("DKIM", result.DKIM.Result)
printResult("DMARC", result.DMARC.Result)
printResult("Host TLSRPT", result.HostTLSRPT.Result)
printResult("Domain TLSRPT", result.DomainTLSRPT.Result)
printResult("MTASTS", result.MTASTS.Result)
printResult("SRV conf", result.SRVConf.Result)
printResult("Autoconf", result.Autoconf.Result)
printResult("Autodiscover", result.Autodiscover.Result)
}
func cmdConfigEnsureACMEHostprivatekeys(c *cmd) {
c.params = ""
c.help = `Ensure host private keys exist for TLS listeners with ACME.
In mox.conf, each listener can have TLS configured. Long-lived private key files
can be specified, which will be used when requesting ACME certificates.
Configuring these private keys makes it feasible to publish DANE TLSA records
for the corresponding public keys in DNS, protected with DNSSEC, allowing TLS
certificate verification without depending on a list of Certificate Authorities
(CAs). Previous versions of mox did not pre-generate private keys for use with
ACME certificates, but would generate private keys on-demand. By explicitly
configuring private keys, they will not change automatedly with new
certificates, and the DNS TLSA records stay valid.
This command looks for listeners in mox.conf with TLS with ACME configured. For
each missing host private key (of type rsa-2048 and ecdsa-p256) a key is written
to config/hostkeys/. If a certificate exists in the ACME "cache", its private
key is copied. Otherwise a new private key is generated. Snippets for manually
updating/editing mox.conf are printed.
After running this command, and updating mox.conf, run "mox config dnsrecords"
for a domain and create the TLSA DNS records it suggests to enable DANE.
`
args := c.Parse()
if len(args) != 0 {
c.Usage()
}
// Load a private key from p, in various forms. We only look at the first PEM
// block. Files with only a private key, or with multiple blocks but private key
// first like autocert does, can be loaded.
loadPrivateKey := func(f *os.File) (any, error) {
buf, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("reading private key file: %v", err)
}
block, _ := pem.Decode(buf)
if block == nil {
return nil, fmt.Errorf("no pem block found in pem file")
}
var privKey any
switch block.Type {
case "EC PRIVATE KEY":
privKey, err = x509.ParseECPrivateKey(block.Bytes)
case "RSA PRIVATE KEY":
privKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
case "PRIVATE KEY":
privKey, err = x509.ParsePKCS8PrivateKey(block.Bytes)
default:
return nil, fmt.Errorf("unrecognized pem block type %q", block.Type)
}
if err != nil {
return nil, fmt.Errorf("parsing private key of type %q: %v", block.Type, err)
}
return privKey, nil
}
// Either load a private key from file, or if it doesn't exist generate a new
// private key.
xtryLoadPrivateKey := func(kt autocert.KeyType, p string) any {
f, err := os.Open(p)
if err != nil && errors.Is(err, fs.ErrNotExist) {
switch kt {
case autocert.KeyRSA2048:
privKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)
xcheckf(err, "generating new 2048-bit rsa private key")
return privKey
case autocert.KeyECDSAP256:
privKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
xcheckf(err, "generating new ecdsa p-256 private key")
return privKey
}
log.Fatalf("unexpected keytype %v", kt)
return nil
}
xcheckf(err, "%s: open acme key and certificate file", p)
// Load private key from file. autocert stores a PEM file that starts with a
// private key, followed by certificate(s). So we can just read it and should find
// the private key we are looking for.
privKey, err := loadPrivateKey(f)
if xerr := f.Close(); xerr != nil {
log.Printf("closing private key file: %v", xerr)
}
xcheckf(err, "parsing private key from acme key and certificate file")
switch k := privKey.(type) {
case *rsa.PrivateKey:
if k.N.BitLen() == 2048 {
return privKey
}
log.Printf("warning: rsa private key in %s has %d bits, skipping and generating new 2048-bit rsa private key", p, k.N.BitLen())
privKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)
xcheckf(err, "generating new 2048-bit rsa private key")
return privKey
case *ecdsa.PrivateKey:
if k.Curve == elliptic.P256() {
return privKey
}
log.Printf("warning: ecdsa private key in %s has curve %v, skipping and generating new p-256 ecdsa key", p, k.Curve.Params().Name)
privKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
xcheckf(err, "generating new ecdsa p-256 private key")
return privKey
default:
log.Fatalf("%s: unexpected private key file of type %T", p, privKey)
return nil
}
}
// Write privKey as PKCS#8 private key to p. Only if file does not yet exist.
writeHostPrivateKey := func(privKey any, p string) error {
os.MkdirAll(filepath.Dir(p), 0700)
f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("create: %v", err)
}
defer func() {
if f != nil {
if err := f.Close(); err != nil {
log.Printf("closing new hostkey file %s after error: %v", p, err)
}
if err := os.Remove(p); err != nil {
log.Printf("removing new hostkey file %s after error: %v", p, err)
}
}
}()
buf, err := x509.MarshalPKCS8PrivateKey(privKey)
if err != nil {
return fmt.Errorf("marshal private host key: %v", err)
}
block := pem.Block{
Type: "PRIVATE KEY",
Bytes: buf,
}
if err := pem.Encode(f, &block); err != nil {
return fmt.Errorf("write as pem: %v", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("close: %v", err)
}
f = nil
return nil
}
mustLoadConfig()
timestamp := time.Now().Format("20060102T150405")
didCreate := false
for listenerName, l := range mox.Conf.Static.Listeners {