@@ -2,10 +2,18 @@ package src
2
2
3
3
import (
4
4
"bytes"
5
+ cryptoRand "crypto/rand"
6
+ "crypto/rsa"
7
+ "crypto/tls"
8
+ "crypto/x509"
9
+ "crypto/x509/pkix"
5
10
"fmt"
6
11
"io"
7
12
"log"
13
+ "math/big"
8
14
"math/rand"
15
+ "net"
16
+ "os"
9
17
"sync"
10
18
"time"
11
19
@@ -148,6 +156,7 @@ type StartEmailServerOptions struct {
148
156
Username string
149
157
Password string
150
158
MaxEmails uint16
159
+ Tls bool
151
160
}
152
161
153
162
// StartEmailServer starts the email server
@@ -179,9 +188,72 @@ func StartEmailServer(opts StartEmailServerOptions) {
179
188
server .AllowInsecureAuth = true
180
189
server .AuthDisabled = backend .Credentials == nil
181
190
191
+ if opts .Tls {
192
+ tlsConfig , err := generateTLSConfig ()
193
+ if err != nil {
194
+ fmt .Println ("WARN: failed to generate self signed tls certificate for email server, error:" , err )
195
+ os .Exit (1 )
196
+ } else {
197
+ server .TLSConfig = tlsConfig
198
+ }
199
+ }
200
+
182
201
fmt .Println ("Running SMTP server at" , server .Addr , "with a emails dequeue length of" , opts .MaxEmails )
183
202
err := server .ListenAndServe ()
184
203
if err != nil {
185
204
log .Fatal (err )
186
205
}
187
206
}
207
+
208
+ func generateTLSConfig () (* tls.Config , error ) {
209
+ // Generate a private key
210
+ privateKey , err := rsa .GenerateKey (cryptoRand .Reader , 2048 )
211
+ if err != nil {
212
+ return nil , err
213
+ }
214
+
215
+ // Set up certificate template
216
+ serialNumberLimit := new (big.Int ).Lsh (big .NewInt (1 ), 128 )
217
+ serialNumber , err := cryptoRand .Int (cryptoRand .Reader , serialNumberLimit )
218
+ if err != nil {
219
+ return nil , err
220
+ }
221
+
222
+ template := x509.Certificate {
223
+ SerialNumber : serialNumber ,
224
+ Subject : pkix.Name {
225
+ Organization : []string {"Self-Signed Cert" },
226
+ CommonName : "localhost" ,
227
+ },
228
+ NotBefore : time .Now (),
229
+ NotAfter : time .Now ().AddDate (1 , 0 , 0 ),
230
+ KeyUsage : x509 .KeyUsageKeyEncipherment | x509 .KeyUsageDigitalSignature ,
231
+ ExtKeyUsage : []x509.ExtKeyUsage {x509 .ExtKeyUsageServerAuth },
232
+ BasicConstraintsValid : true ,
233
+ IPAddresses : []net.IP {net .ParseIP ("127.0.0.1" )},
234
+ DNSNames : []string {"localhost" },
235
+ }
236
+
237
+ // Create the certificate
238
+ derBytes , err := x509 .CreateCertificate (
239
+ cryptoRand .Reader ,
240
+ & template ,
241
+ & template ,
242
+ & privateKey .PublicKey ,
243
+ privateKey ,
244
+ )
245
+ if err != nil {
246
+ return nil , err
247
+ }
248
+
249
+ // Create the TLS certificate
250
+ cert := tls.Certificate {
251
+ Certificate : [][]byte {derBytes },
252
+ PrivateKey : privateKey ,
253
+ }
254
+
255
+ // Return the TLS config
256
+ return & tls.Config {
257
+ Certificates : []tls.Certificate {cert },
258
+ }, nil
259
+ }
0 commit comments