-
Notifications
You must be signed in to change notification settings - Fork 5
/
proxy_app.go
245 lines (219 loc) · 7.64 KB
/
proxy_app.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
// Package smtpproxy is based heavily on https://github.com/emersion/go-smtp, with increased transparency of response codes and no sasl dependency.
package smtpproxy
import (
"crypto/tls"
"io"
"log"
"net"
"os"
"time"
)
// This file contains functions for an example Proxy app, including
// TLS negotiation, command pass-through, AUTH pass-through.
// CreateProxy sets up a proxy server with provided parameters and options, also returns the backend.
func CreateProxy(inHostPort, outHostPort string, verboseOpt bool, cert, privkey []byte, insecureSkipVerify bool, dbgFile *os.File) (*Server, *ProxyBackend, error) {
// Set up parameters that the backend will use
be := NewBackend(outHostPort, verboseOpt, insecureSkipVerify)
s := NewServer(be)
s.Addr = inHostPort
s.ReadTimeout = 60 * time.Second
s.WriteTimeout = 60 * time.Second
if dbgFile != nil {
s.Debug = dbgFile // Important to write this only if valid
}
var err error
if len(cert) > 0 && len(privkey) > 0 {
err = s.ServeTLS(cert, privkey)
} else {
s.Domain, err = os.Hostname() // This is the fallback in case we have no cert / privkey to give us a Subject
}
return s, be, err
}
//-----------------------------------------------------------------------------
// Backend handlers
// The ProxyBackend implements SMTP server methods.
type ProxyBackend struct {
outHostPort string
verbose bool
insecureSkipVerify bool
}
// NewBackend creates a proxy backend with specified params
func NewBackend(outHostPort string, verbose bool, insecureSkipVerify bool) *ProxyBackend {
b := ProxyBackend{
outHostPort: outHostPort,
verbose: verbose,
insecureSkipVerify: insecureSkipVerify,
}
return &b
}
// SetVerbose allows changing logging options on-the-fly
func (bkd *ProxyBackend) SetVerbose(v bool) {
bkd.verbose = v
}
func (bkd *ProxyBackend) logger(args ...interface{}) {
if bkd.verbose {
log.Println(args...)
}
}
func (bkd *ProxyBackend) loggerAlways(args ...interface{}) {
log.Println(args...)
}
// MakeSession returns a session for this client and backend
func (bkd *ProxyBackend) MakeSession(c *Client) Session {
var s proxySession
s.bkd = bkd // just for logging
s.upstream = c // keep record of the upstream Client connection
return &s
}
// Init the backend. Here we establish the upstream connection
func (bkd ProxyBackend) Init() (Session, error) {
bkd.logger("---Connecting upstream")
c, err := Dial(bkd.outHostPort)
if err != nil {
bkd.loggerAlways("< Connection error", bkd.outHostPort, err.Error())
return nil, err
}
bkd.logger("< Connection success", bkd.outHostPort)
return bkd.MakeSession(c), nil
}
//-----------------------------------------------------------------------------
// Session handlers
// A Session is returned after successful login. Here hold information that needs to persist across message phases.
type proxySession struct {
bkd *ProxyBackend // The backend that created this session. Allows session methods to e.g. log
upstream *Client // the upstream client this backend is driving
}
// cmdTwiddle returns different flow markers depending on whether connection is secure (like Swaks does)
func cmdTwiddle(s *proxySession) string {
if s.upstream != nil {
if _, isTLS := s.upstream.TLSConnectionState(); isTLS {
return "~>"
}
}
return "->"
}
// respTwiddle returns different flow markers depending on whether connection is secure (like Swaks does)
func respTwiddle(s *proxySession) string {
if s.upstream != nil {
if _, isTLS := s.upstream.TLSConnectionState(); isTLS {
return "\t<~"
}
}
return "\t<-"
}
// Greet the upstream host and report capabilities back.
func (s *proxySession) Greet(helotype string) ([]string, int, string, error) {
s.bkd.logger(cmdTwiddle(s), helotype)
host, _, _ := net.SplitHostPort(s.bkd.outHostPort)
if host == "" {
host = "smtpproxy.localhost" // add dummy value in
}
code, msg, err := s.upstream.Hello(host)
if err != nil {
s.bkd.loggerAlways(respTwiddle(s), helotype, "error", err.Error())
if code == 0 {
// some errors don't show up in (code,msg) e.g. TLS cert errors, so map as a specific SMTP code/msg response
code = 599
msg = err.Error()
}
return nil, code, msg, err
}
s.bkd.logger(respTwiddle(s), helotype, "success")
caps := s.upstream.Capabilities()
s.bkd.logger("\tUpstream capabilities:", caps)
return caps, code, msg, err
}
// StartTLS command
func (s *proxySession) StartTLS() (int, string, error) {
host, _, _ := net.SplitHostPort(s.bkd.outHostPort)
// Try the upstream server, it will report error if unsupported
tlsconfig := &tls.Config{
InsecureSkipVerify: s.bkd.insecureSkipVerify,
ServerName: host,
}
s.bkd.logger(cmdTwiddle(s), "STARTTLS")
code, msg, err := s.upstream.StartTLS(tlsconfig)
if err != nil {
s.bkd.loggerAlways(respTwiddle(s), code, msg)
} else {
s.bkd.logger(respTwiddle(s), code, msg)
}
return code, msg, err
}
//Auth command backend handler
func (s *proxySession) Auth(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
//Mail command backend handler
func (s *proxySession) Mail(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
//Rcpt command backend handler
func (s *proxySession) Rcpt(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
//Reset command backend handler
func (s *proxySession) Reset(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
//Quit command backend handler
func (s *proxySession) Quit(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
//Unknown command backend handler
func (s *proxySession) Unknown(expectcode int, cmd, arg string) (int, string, error) {
return s.Passthru(expectcode, cmd, arg)
}
// Passthru a command to the upstream server, logging
func (s *proxySession) Passthru(expectcode int, cmd, arg string) (int, string, error) {
s.bkd.logger(cmdTwiddle(s), cmd, arg)
joined := cmd
if arg != "" {
joined = cmd + " " + arg
}
code, msg, err := s.upstream.MyCmd(expectcode, joined)
if err != nil {
s.bkd.loggerAlways(respTwiddle(s), cmd, code, msg, "error", err.Error())
if code == 0 {
// some errors don't show up in (code,msg) e.g. TLS cert errors, so map as a specific SMTP code/msg response
code = 599
msg = err.Error()
}
} else {
s.bkd.logger(respTwiddle(s), code, msg)
}
return code, msg, err
}
// DataCommand pass upstream, returning a place to write the data AND the usual responses
func (s *proxySession) DataCommand() (io.WriteCloser, int, string, error) {
s.bkd.logger(cmdTwiddle(s), "DATA")
w, code, msg, err := s.upstream.Data()
if err != nil {
s.bkd.loggerAlways(respTwiddle(s), "DATA error", err.Error())
}
return w, code, msg, err
}
// Data body (dot delimited) pass upstream, returning the usual responses
func (s *proxySession) Data(r io.Reader, w io.WriteCloser) (int, string, error) {
// Send the data upstream
count, err := io.Copy(w, r)
if err != nil {
msg := "DATA io.Copy error"
s.bkd.loggerAlways(respTwiddle(s), msg, err.Error())
return 0, msg, err
}
err = w.Close() // Need to close the data phase - then we should have response from upstream
code := s.upstream.DataResponseCode
msg := s.upstream.DataResponseMsg
if err != nil {
s.bkd.loggerAlways(respTwiddle(s), "DATA Close error", err, ", bytes written =", count)
return 0, msg, err
}
if s.bkd.verbose {
s.bkd.logger(respTwiddle(s), "DATA accepted, bytes written =", count)
} else {
// Short-form logging - one line per message - used when "verbose" not set
log.Printf("Message DATA upstream,%d,%d,%s\n", count, code, msg)
}
return code, msg, err
}