forked from mushorg/glutton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glutton.go
250 lines (209 loc) · 6 KB
/
glutton.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
package glutton
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"time"
"github.com/kung-foo/freki"
"github.com/mushorg/glutton/config"
"github.com/mushorg/glutton/producer"
uuid "github.com/satori/go.uuid"
"github.com/spf13/viper"
log "go.uber.org/zap"
)
// Glutton struct
type Glutton struct {
id uuid.UUID
conf *viper.Viper
logger *log.Logger
processor *freki.Processor
rules []*freki.Rule
producer *producer.Config
protocolHandlers map[string]protocolHandlerFunc
sshProxy *sshProxy
ctx context.Context
cancel context.CancelFunc
}
type protocolHandlerFunc func(ctx context.Context, conn net.Conn) error
// New creates a new Glutton instance
func New(args map[string]interface{}) (*Glutton, error) {
var (
iface string = args["--interface"].(string)
logPath = args["--logpath"].(string)
confPath = args["--confpath"].(string)
debug string = args["--debug"].(string)
)
gtn := &Glutton{}
err := gtn.makeID()
if err != nil {
return nil, err
}
if gtn.logger, err = initLogger(&logPath, gtn.id.String(), &debug); err != nil {
return nil, err
}
// Loading the congiguration
gtn.logger.Info("[glutton ] Loading configurations from: config/conf.yaml")
gtn.conf = config.Init(&confPath, gtn.logger)
rulesPath := gtn.conf.GetString("rules_path")
rulesFile, err := os.Open(rulesPath)
defer rulesFile.Close()
if err != nil {
return nil, err
}
gtn.rules, err = freki.ReadRulesFromFile(rulesFile)
if err != nil {
return nil, err
}
// Initiate the freki processor
gtn.processor, err = freki.New(iface, gtn.rules, nil)
if err != nil {
return nil, err
}
return gtn, nil
}
// Init initializes freki and handles
func (g *Glutton) Init() (err error) {
ctx := context.Background()
g.ctx, g.cancel = context.WithCancel(ctx)
g.protocolHandlers = make(map[string]protocolHandlerFunc, 0)
gluttonServerPort := uint(g.conf.GetInt("glutton_server"))
// Initiating glutton server
g.processor.AddServer(freki.NewUserConnServer(gluttonServerPort))
// Initiating log producer
if g.conf.GetBool("enableGollum") {
g.producer = producer.Init(g.id.String(), g.conf.GetString("gollumAddress"))
}
// Initiating protocol handlers
g.mapProtocolHandlers()
g.registerHandlers()
err = g.processor.Init()
if err != nil {
return
}
return nil
}
// Start the packet processor
func (g *Glutton) Start() (err error) {
quit := make(chan struct{}) // stop monitor on shutdown
defer func() {
quit <- struct{}{}
g.Shutdown()
}()
g.startMonitor(quit)
err = g.processor.Start()
return
}
func (g *Glutton) makeID() error {
dirName := "/var/lib/glutton"
fileName := "glutton.id"
filePath := filepath.Join(dirName, fileName)
err := os.MkdirAll(dirName, 0644)
if err != nil {
return err
}
if f, err := os.OpenFile(filePath, os.O_RDWR, 0644); os.IsNotExist(err) {
g.id = uuid.NewV4()
errWrite := ioutil.WriteFile(filePath, g.id.Bytes(), 0644)
if err != nil {
return errWrite
}
} else {
if err != nil {
return err
}
buff, err := ioutil.ReadAll(f)
if err != nil {
return err
}
g.id, err = uuid.FromBytes(buff)
if err != nil {
return err
}
}
return nil
}
// registerHandlers register protocol handlers to glutton_server
func (g *Glutton) registerHandlers() {
for _, rule := range g.rules {
if rule.Type == "conn_handler" && rule.Target != "" {
var handler string
switch rule.Name {
case "proxy_tcp":
handler = rule.Name
g.protocolHandlers[rule.Target] = g.protocolHandlers[handler]
delete(g.protocolHandlers, handler)
handler = rule.Target
break
case "proxy_ssh":
handler = rule.Name
err := g.NewSSHProxy(rule.Target)
if err != nil {
g.logger.Error(fmt.Sprintf("[ssh.prxy] failed to initialize SSH proxy"))
continue
}
rule.Target = handler
break
default:
handler = rule.Target
break
}
if g.protocolHandlers[handler] == nil {
g.logger.Warn(fmt.Sprintf("[glutton ] no handler found for %v protocol", handler))
continue
}
g.processor.RegisterConnHandler(handler, func(conn net.Conn, md *freki.Metadata) error {
host, port, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
return err
}
if md == nil {
g.logger.Debug(fmt.Sprintf("[glutton ] connection not tracked: %s:%s", host, port))
return nil
}
g.logger.Debug(fmt.Sprintf("[glutton ] new connection: %s:%s -> %d", host, port, md.TargetPort))
if g.producer != nil {
err = g.producer.LogHTTP(conn, md, nil, "")
if err != nil {
g.logger.Error(fmt.Sprintf("[glutton ] error: %v", err))
}
}
done := make(chan struct{})
go g.closeOnShutdown(conn, done)
conn.SetDeadline(time.Now().Add(45 * time.Second))
ctx := g.contextWithTimeout(72)
err = g.protocolHandlers[handler](ctx, conn)
done <- struct{}{}
return err
})
}
}
}
// Shutdown the packet processor
func (g *Glutton) Shutdown() (err error) {
defer g.logger.Sync()
g.cancel() // close all connection
/** TODO:
** May be there exist a better way to wait for all connections to be closed but I am unable
** to find. The only link we have between program and goroutines is context.
** context.cancel() signal routines to abandon their work and does not wait
** for the work to stop. And in any case if fails then there will be definitely a
** goroutine leak. May be it is possible in future when we have connection counter so we can keep
** that counter synchronized with number of goroutines (connections) with help of context and on
** shutdown we wait until counter goes to zero.
*/
time.Sleep(2 * time.Second)
return g.processor.Shutdown()
}
// OnErrorClose prints the error, closes the connection and exits
func (g *Glutton) onErrorClose(err error, conn net.Conn) {
if err != nil {
g.logger.Error(fmt.Sprintf("[glutton ] error: %v", err))
err = conn.Close()
if err != nil {
g.logger.Error(fmt.Sprintf("[glutton ] error: %v", err))
}
}
}