-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
258 lines (209 loc) · 6.04 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
package main
import (
"flag"
"fmt"
"os"
"time"
"github.com/appcanary/agent/agent"
"github.com/appcanary/agent/agent/detect"
"github.com/appcanary/agent/conf"
)
var CanaryVersion string
var defaultFlags *flag.FlagSet
type CommandToPerform int
const (
PerformAgentLoop CommandToPerform = iota
PerformUpgrade
PerformDisplayVersion
PerformDetectOS
PerformProcessInspection
PerformProcessInspectionJsonDump
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage: appcanary [COMMAND] [OPTIONS]\nOptions:\n")
defaultFlags.PrintDefaults()
fmt.Fprintf(os.Stderr, "\nCommands:\n"+
"\t[none]\t\t\tStart the agent\n"+
"\tupgrade\t\t\tUpgrade system packages to nearest safe version (Ubuntu only)\n"+
"\tinspect-processes\tSend your process library information to Appcanary\n"+
"\tdetect-os\t\tDetect current operating system\n")
}
func parseFlags(argRange int, env *conf.Env) {
var displayVersionFlagged bool
// httptest, used in client.test, sets a usage flag
// that leaks when you use the 'global' FlagSet.
defaultFlags = flag.NewFlagSet("Default", flag.ExitOnError)
defaultFlags.Usage = usage
defaultFlags.StringVar(&env.ConfFile, "conf", env.ConfFile, "Set the config file")
defaultFlags.StringVar(&env.VarFile, "server", env.VarFile, "Set the server file")
defaultFlags.StringVar(&env.LogFile, "log", env.LogFile, "Set the log file (will not override if set in config file)")
defaultFlags.BoolVar(&env.DryRun, "dry-run", false, "Only print, and do not execute, potentially destructive commands")
// -version is handled in parseArguments, but is set here for the usage print out
defaultFlags.BoolVar(&displayVersionFlagged, "version", false, "Display version information")
defaultFlags.BoolVar(&env.FailOnConflict, "fail-on-conflict", false, "Should upgrade encounter a conflict with configuration files, abort (default: old configuration files are kept, or updated if not modified)")
if !env.Prod {
defaultFlags.StringVar(&env.BaseUrl, "url", env.BaseUrl, "Set the endpoint")
}
defaultFlags.Parse(os.Args[argRange:])
}
func parseArguments(env *conf.Env) CommandToPerform {
var performCmd CommandToPerform
if len(os.Args) < 2 {
return PerformAgentLoop
}
// if first arg is a command,
// flags will follow in os.Args[2:]
// else in os.Args[1:]
argRange := 2
switch os.Args[1] {
case "upgrade":
performCmd = PerformUpgrade
case "detect-os":
performCmd = PerformDetectOS
case "inspect-processes":
performCmd = PerformProcessInspection
case "inspect-processes-json":
performCmd = PerformProcessInspectionJsonDump
case "-version":
performCmd = PerformDisplayVersion
case "--version":
performCmd = PerformDisplayVersion
default:
argRange = 1
performCmd = PerformAgentLoop
}
parseFlags(argRange, env)
return performCmd
}
func runDisplayVersion() {
fmt.Println(CanaryVersion)
os.Exit(0)
}
func runDetectOS() {
guess, err := detect.DetectOS()
if err == nil {
fmt.Printf("%s/%s\n", guess.Distro, guess.Release)
} else {
fmt.Printf("%v\n", err.Error())
}
os.Exit(0)
}
func initialize(env *conf.Env) *agent.Agent {
// let's get started eh
// start the logger
conf.InitLogging()
log := conf.FetchLog()
fmt.Println(env.Logo)
// slurp env, instantiate agent
config, err := conf.NewConfFromEnv()
if err != nil {
log.Fatal(err)
}
if config.ApiKey == "" {
log.Fatal("There's no API key set. Get yours from https://appcanary.com/settings and set it in /etc/appcanary/agent.yml")
}
// If the config sets a startup delay, we wait to boot up here
if config.StartupDelay != 0 {
delay := time.Duration(config.StartupDelay) * time.Second
tick := time.Tick(delay)
<-tick
}
a := agent.NewAgent(CanaryVersion, config)
a.DoneChannel = make(chan os.Signal, 1)
// we prob can't reliably fingerprint servers.
// so instead, we assign a uuid by registering
if a.FirstRun() {
log.Debug("Found no server config. Let's register!")
for err := a.RegisterServer(); err != nil; {
// we don't need to wait here because of the backoff
// exponential decay library; by the time we hit this
// point we've been trying for about, what, an hour?
log.Infof("Register server error: %s", err)
err = a.RegisterServer()
}
}
// Now that we're registered,
// let's init our watchers. We auto sync on watcher init.
a.BuildAndSyncWatchers()
return a
}
func runProcessInspection(a *agent.Agent) {
log := conf.FetchLog()
agent.ShipProcessMap(a)
log.Info("Process inspection sent. Check https://appcanary.com")
os.Exit(0)
}
func runProcessInspectionDump() {
agent.DumpProcessMap()
os.Exit(0)
}
func runUpgrade(a *agent.Agent) {
log := conf.FetchLog()
log.Info("Running upgrade...")
a.PerformUpgrade()
os.Exit(0)
}
func runAgentLoop(env *conf.Env, a *agent.Agent) {
log := conf.FetchLog()
// Add hooks to files, and push them over
// whenever they change
a.StartPolling()
// send a heartbeat every ~60min, forever
go func() {
tick := time.Tick(env.HeartbeatDuration)
for {
err := a.Heartbeat()
if err != nil {
log.Infof("<3 error: %s", err)
}
<-tick
}
}()
go func() {
tick := time.Tick(env.SyncAllDuration)
for {
<-tick
a.SyncAllFiles()
}
}()
defer a.CloseWatches()
// wait for the right signal?
// signal.Notify(done, os.Interrupt, os.Kill)
// block forever
<-a.DoneChannel
}
func checkYourPrivilege() {
if os.Getuid() != 0 && os.Geteuid() != 0 {
fmt.Println("Cannot run unprivileged - must be root (UID=0)")
os.Exit(13)
}
}
func main() {
conf.InitEnv(os.Getenv("CANARY_ENV"))
env := conf.FetchEnv()
// parse the args
switch parseArguments(env) {
case PerformDisplayVersion:
runDisplayVersion()
case PerformDetectOS:
runDetectOS()
case PerformProcessInspection:
checkYourPrivilege()
a := initialize(env)
runProcessInspection(a)
case PerformProcessInspectionJsonDump:
checkYourPrivilege()
conf.InitLogging()
runProcessInspectionDump()
case PerformUpgrade:
a := initialize(env)
runUpgrade(a)
case PerformAgentLoop:
a := initialize(env)
runAgentLoop(env, a)
}
// Close the logfile when we exit
if env.LogFileHandle != nil {
defer env.LogFileHandle.Close()
}
}