-
Notifications
You must be signed in to change notification settings - Fork 51
/
server.go
244 lines (195 loc) · 6.16 KB
/
server.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
package server
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/shirou/gopsutil/process"
"go.aporeto.io/trireme-lib/monitor/registerer"
"go.aporeto.io/trireme-lib/common"
)
// EventServer is a new event server
type EventServer struct {
socketPath string
server *http.Server
registerer registerer.Registerer
}
// NewEventServer creates a new event server
func NewEventServer(address string, registerer registerer.Registerer) (*EventServer, error) {
// Cleanup the socket first.
if _, err := os.Stat(address); err == nil {
if err := os.Remove(address); err != nil {
return nil, fmt.Errorf("Cannot create clean up socket: %s", err)
}
}
return &EventServer{
socketPath: address,
registerer: registerer,
}, nil
}
// ServeHTTP is called for every request.
func (e *EventServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.create(w, r)
}
// Run runs the server. The server will run in the background. It will
// gracefully die with the provided context.
func (e *EventServer) Run(ctx context.Context) error {
// Create the handler
e.server = &http.Server{
Handler: e,
}
// Start a custom listener
addr, _ := net.ResolveUnixAddr("unix", e.socketPath)
nl, err := net.ListenUnix("unix", addr)
if err != nil {
return fmt.Errorf("Unable to start API server: %s", err)
}
// We make the socket accesible to all users of the system.
// TODO: create a trireme group for this
if err := os.Chmod(addr.String(), 0766); err != nil {
return fmt.Errorf("Cannot make the socket accessible to all users: %s", err)
}
listener := &UIDListener{nl}
// Start serving HTTP requests in the background
go e.server.Serve(listener) // nolint
// Listen for context cancellation to close the socket.
go func() {
<-ctx.Done()
nl.Close() // nolint
}()
return nil
}
// create is the main hadler that process and validates the events
// before calling the actual monitor handlers to process the event.
func (e *EventServer) create(w http.ResponseWriter, r *http.Request) {
event := &common.EventInfo{}
if err := json.NewDecoder(r.Body).Decode(event); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
if err := validateTypes(event); err != nil {
http.Error(w, fmt.Sprintf("Invalid request fields: %s", err), http.StatusBadRequest)
return
}
if err := validateUser(r, event); err != nil {
http.Error(w, fmt.Sprintf("Invalid user to pid mapping found: %s", err), http.StatusForbidden)
return
}
if err := validateEvent(event); err != nil {
http.Error(w, fmt.Sprintf("Bad request: %s", err), http.StatusBadRequest)
return
}
if err := e.processEvent(r.Context(), event); err != nil {
http.Error(w, fmt.Sprintf("Cannot handle request: %s", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}
// processEvent processes the event by retrieving the right monitor handler.
func (e *EventServer) processEvent(ctx context.Context, eventInfo *common.EventInfo) (err error) {
if e.registerer == nil {
return fmt.Errorf("No registered handlers")
}
f, err := e.registerer.GetHandler(eventInfo.PUType, eventInfo.EventType)
if err != nil {
return fmt.Errorf("Handler not found: %s", err)
}
if err := f(ctx, eventInfo); err != nil {
return err
}
return nil
}
// validateUser validates that the originating user is not sending a request
// for a process that they don't own. Root users are allowed to send
// any event.
func validateUser(r *http.Request, event *common.EventInfo) error {
// Find the calling user.
parts := strings.Split(r.RemoteAddr, ":")
if len(parts) != 3 {
return fmt.Errorf("Invalid user context")
}
// Accept all requests from root users
if parts[0] == "0" {
return nil
}
// The target process must be valid.
p, err := process.NewProcess(event.PID)
if err != nil {
return fmt.Errorf("Process not found")
}
// The UID of the calling process must match the UID of the target process.
uids, err := p.Uids()
if err != nil {
return fmt.Errorf("Unknown user ID")
}
match := false
for _, uid := range uids {
if strconv.Itoa(int(uid)) == parts[0] {
match = true
}
}
if !match {
return fmt.Errorf("Invalid user - no access to this process: %+v PARTS: %+v", event, parts)
}
return nil
}
// validateTypes validates the various types and prevents any bad strings.
func validateTypes(event *common.EventInfo) error {
regexStrings := regexp.MustCompile("^[a-zA-Z0-9_:.$%/-]{0,64}$")
regexNS := regexp.MustCompile("^[a-zA-Z0-9/-]{0,128}$")
regexCgroup := regexp.MustCompile("^/trireme/(uid/){0,1}[a-zA-Z0-9_:.$%]{1,64}$")
if _, ok := common.EventMap[event.EventType]; !ok {
return fmt.Errorf("invalid event: %s", string(event.EventType))
}
if event.PUType > common.TransientPU {
return fmt.Errorf("invalid pu type %v", event.PUType)
}
if !regexStrings.Match([]byte(event.Name)) {
return fmt.Errorf("Name is not of the right format")
}
if len(event.Cgroup) > 0 && !regexCgroup.Match([]byte(event.Cgroup)) {
return fmt.Errorf("Invalid cgroup format: %s", event.Cgroup)
}
if !regexNS.Match([]byte(event.NS)) {
return fmt.Errorf("Namespace is not of the right format")
}
for k, v := range event.IPs {
if !regexStrings.Match([]byte(k)) {
return fmt.Errorf("Invalid IP name: %s", k)
}
if ip := net.ParseIP(v); ip == nil {
return fmt.Errorf("Invalid IP address: %s", v)
}
}
return nil
}
// validateEvent validates that this is reasonable event and
// modifies the default values.
func validateEvent(event *common.EventInfo) error {
if event.EventType == common.EventCreate || event.EventType == common.EventStart {
if event.HostService {
if event.NetworkOnlyTraffic {
if event.Name == "" {
return fmt.Errorf("Service name must be provided and must not be default")
}
event.PUID = event.Name
}
} else {
if event.PUID == "" {
event.PUID = strconv.Itoa(int(event.PID))
}
}
}
if event.EventType == common.EventStop || event.EventType == common.EventDestroy {
regStop := regexp.MustCompile("^/trireme/[a-zA-Z0-9_].{0,11}$")
if event.Cgroup != "" && !regStop.Match([]byte(event.Cgroup)) {
return fmt.Errorf("Cgroup is not of the right format")
}
}
return nil
}