-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathlauncher.go
640 lines (550 loc) · 22.5 KB
/
launcher.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
package main
import (
"bytes"
"context"
"crypto/x509"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/apache/thrift/lib/go/thrift"
"github.com/go-kit/kit/log"
"github.com/kolide/kit/fsutil"
"github.com/kolide/kit/ulid"
"github.com/kolide/kit/version"
"github.com/kolide/launcher/cmd/launcher/internal"
"github.com/kolide/launcher/ee/agent"
"github.com/kolide/launcher/ee/agent/flags"
"github.com/kolide/launcher/ee/agent/flags/keys"
"github.com/kolide/launcher/ee/agent/knapsack"
"github.com/kolide/launcher/ee/agent/startupsettings"
"github.com/kolide/launcher/ee/agent/storage"
agentbbolt "github.com/kolide/launcher/ee/agent/storage/bbolt"
"github.com/kolide/launcher/ee/agent/timemachine"
"github.com/kolide/launcher/ee/agent/types"
"github.com/kolide/launcher/ee/control"
"github.com/kolide/launcher/ee/control/actionqueue"
"github.com/kolide/launcher/ee/control/consumers/acceleratecontrolconsumer"
"github.com/kolide/launcher/ee/control/consumers/flareconsumer"
"github.com/kolide/launcher/ee/control/consumers/keyvalueconsumer"
"github.com/kolide/launcher/ee/control/consumers/notificationconsumer"
"github.com/kolide/launcher/ee/control/consumers/remoterestartconsumer"
"github.com/kolide/launcher/ee/control/consumers/uninstallconsumer"
"github.com/kolide/launcher/ee/debug/checkups"
desktopRunner "github.com/kolide/launcher/ee/desktop/runner"
"github.com/kolide/launcher/ee/gowrapper"
"github.com/kolide/launcher/ee/localserver"
"github.com/kolide/launcher/ee/powereventwatcher"
"github.com/kolide/launcher/ee/tuf"
"github.com/kolide/launcher/ee/watchdog"
"github.com/kolide/launcher/pkg/augeas"
"github.com/kolide/launcher/pkg/backoff"
"github.com/kolide/launcher/pkg/contexts/ctxlog"
"github.com/kolide/launcher/pkg/debug"
"github.com/kolide/launcher/pkg/launcher"
"github.com/kolide/launcher/pkg/log/logshipper"
"github.com/kolide/launcher/pkg/log/multislogger"
"github.com/kolide/launcher/pkg/log/teelogger"
"github.com/kolide/launcher/pkg/osquery"
"github.com/kolide/launcher/pkg/osquery/runsimple"
osqueryruntime "github.com/kolide/launcher/pkg/osquery/runtime"
osqueryInstanceHistory "github.com/kolide/launcher/pkg/osquery/runtime/history"
"github.com/kolide/launcher/pkg/rungroup"
"github.com/kolide/launcher/pkg/service"
"github.com/kolide/launcher/pkg/traces"
"github.com/kolide/launcher/pkg/traces/exporter"
"go.etcd.io/bbolt"
)
const (
// Subsystems that launcher listens for control server updates on
agentFlagsSubsystemName = "agent_flags"
serverDataSubsystemName = "kolide_server_data"
desktopMenuSubsystemName = "kolide_desktop_menu"
authTokensSubsystemName = "auth_tokens"
katcSubsystemName = "katc_config" // Kolide ATC
)
// runLauncher is the entry point into running launcher. It creates a
// rungroups with the various options, and goes! If autoupdate is
// enabled, the finalizers will trigger various restarts.
func runLauncher(ctx context.Context, cancel func(), multiSlogger, systemMultiSlogger *multislogger.MultiSlogger, opts *launcher.Options) error {
initialTraceBuffer := exporter.NewInitialTraceBuffer()
ctx, startupSpan := traces.StartSpan(ctx)
thrift.ServerConnectivityCheckInterval = 100 * time.Millisecond
logger := ctxlog.FromContext(ctx)
logger = log.With(logger, "caller", log.DefaultCaller, "session_pid", os.Getpid())
slogger := multiSlogger.Logger
// If delay_start is configured, wait before running launcher.
if opts.DelayStart > 0*time.Second {
slogger.Log(ctx, slog.LevelDebug,
"delay_start configured, waiting before starting launcher",
"delay_start", opts.DelayStart.String(),
)
time.Sleep(opts.DelayStart)
startupSpan.AddEvent("delay_start_completed")
}
slogger.Log(ctx, slog.LevelDebug,
"runLauncher starting",
)
// We've seen launcher intermittently be unable to recover from
// DNS failures in the past, so this check gives us a little bit
// of room to ensure that we are able to resolve DNS requests
// before proceeding with starting launcher.
//
// Note that the SplitN won't work for bare ip6 addresses.
if err := backoff.WaitFor(func() error {
hostport := strings.SplitN(opts.KolideServerURL, ":", 2)
if len(hostport) < 1 {
return fmt.Errorf("unable to parse url: %s", opts.KolideServerURL)
}
_, lookupErr := net.LookupIP(hostport[0])
return lookupErr
}, 10*time.Second, 1*time.Second); err != nil {
slogger.Log(ctx, slog.LevelInfo,
"could not successfully perform IP lookup before starting launcher, proceeding anyway",
"kolide_server_url", opts.KolideServerURL,
"err", err,
)
}
startupSpan.AddEvent("dns_lookup_completed")
// determine the root directory, create one if it's not provided
rootDirectory := opts.RootDirectory
var err error
if rootDirectory == "" {
rootDirectory, err = agent.MkdirTemp(launcher.DefaultRootDirectoryPath)
if err != nil {
return fmt.Errorf("creating temporary root directory: %w", err)
}
slogger.Log(ctx, slog.LevelInfo,
"using default system root directory",
"path", rootDirectory,
)
// Make sure we have record of this new root directory in the opts, so it will be set
// correctly in the knapsack later.
opts.RootDirectory = rootDirectory
}
if err := os.MkdirAll(rootDirectory, fsutil.DirMode); err != nil {
return fmt.Errorf("creating root directory: %w", err)
}
// Ensure permissions are correct, regardless of umask settings -- we use
// DirMode (0755) because the desktop processes that run as the user
// must be able to access the root directory as well.
if err := os.Chmod(rootDirectory, fsutil.DirMode); err != nil {
return fmt.Errorf("chmodding root directory: %w", err)
}
if filepath.Dir(rootDirectory) == "/var/kolide-k2" {
// We need to ensure the same for the parent of the root directory, but we only
// want to do the same for Kolide-created directories.
if err := os.Chmod(filepath.Dir(rootDirectory), fsutil.DirMode); err != nil {
return fmt.Errorf("chmodding root directory parent: %w", err)
}
}
startupSpan.AddEvent("root_directory_created")
if _, err := osquery.DetectPlatform(); err != nil {
return fmt.Errorf("detecting platform: %w", err)
}
debugAddrPath := filepath.Join(rootDirectory, "debug_addr")
debug.AttachDebugHandler(debugAddrPath, slogger)
defer os.Remove(debugAddrPath)
// open the database for storing launcher data, we do it here
// because it's passed to multiple actors. Add a timeout to
// this. Note that the timeout is documented as failing
// unimplemented on windows, though empirically it seems to
// work.
agentbbolt.UseBackupDbIfNeeded(rootDirectory, slogger)
boltOptions := &bbolt.Options{Timeout: time.Duration(30) * time.Second}
db, err := bbolt.Open(agentbbolt.LauncherDbLocation(rootDirectory), 0600, boltOptions)
if err != nil {
return fmt.Errorf("open launcher db: %w", err)
}
defer db.Close()
startupSpan.AddEvent("database_opened")
if err := writePidFile(filepath.Join(rootDirectory, "launcher.pid")); err != nil {
return fmt.Errorf("write launcher pid to file: %w", err)
}
stores, err := agentbbolt.MakeStores(ctx, slogger, db)
if err != nil {
return fmt.Errorf("failed to create stores: %w", err)
}
fcOpts := []flags.Option{flags.WithCmdLineOpts(opts)}
flagController := flags.NewFlagController(slogger, stores[storage.AgentFlagsStore], fcOpts...)
k := knapsack.New(stores, flagController, db, multiSlogger, systemMultiSlogger)
// Generate a new run ID
newRunID := k.GetRunID()
// Apply the run ID to both logger and slogger
logger = log.With(logger, "run_id", newRunID)
slogger = slogger.With("run_id", newRunID)
// start counting uptime
processStartTime := time.Now().UTC()
k.LauncherHistoryStore().Set([]byte("process_start_time"), []byte(processStartTime.Format(time.RFC3339)))
gowrapper.Go(ctx, slogger, func() {
runOsqueryVersionCheckAndAddToKnapsack(ctx, slogger, k, k.LatestOsquerydPath(ctx))
})
gowrapper.Go(ctx, slogger, func() {
timemachine.AddExclusions(ctx, k)
})
if k.Debug() && runtime.GOOS != "windows" {
// If we're in debug mode, then we assume we want to echo _all_ logs to stderr.
k.AddSlogHandler(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
}))
}
// create a rungroup for all the actors we create to allow for easy start/stop
runGroup := rungroup.NewRunGroup()
// Need to set up the log shipper so that we can get the logger early
// and pass it to the various systems.
var logShipper *logshipper.LogShipper
var traceExporter *exporter.TraceExporter
if k.ControlServerURL() != "" {
startupSpan.AddEvent("log_shipper_init_start")
initialDebugDuration := 10 * time.Minute
// Set log shipping level to debug for the first X minutes of
// run time. This will also increase the sending frequency.
k.SetLogShippingLevelOverride("debug", initialDebugDuration)
logShipper = logshipper.New(k, logger)
runGroup.Add("logShipper", logShipper.Run, logShipper.Stop)
logger = teelogger.New(logger, logShipper)
logger = log.With(logger, "caller", log.Caller(5))
k.AddSlogHandler(logShipper.SlogHandler())
ctx = ctxlog.NewContext(ctx, logger) // Set the logger back in the ctx
k.SetTraceSamplingRateOverride(1.0, initialDebugDuration)
k.SetExportTracesOverride(true, initialDebugDuration)
traceExporter, err = exporter.NewTraceExporter(ctx, k, initialTraceBuffer)
if err != nil {
slogger.Log(ctx, slog.LevelDebug,
"could not set up trace exporter",
"err", err,
)
} else {
runGroup.Add("traceExporter", traceExporter.Execute, traceExporter.Interrupt)
}
startupSpan.AddEvent("log_shipper_init_completed")
}
// Now that log shipping is set up, set the slogger on the rungroup so that rungroup logs
// will also be shipped.
runGroup.SetSlogger(k.Slogger())
startupSettingsWriter, err := startupsettings.OpenWriter(ctx, k)
if err != nil {
return fmt.Errorf("creating startup db: %w", err)
}
defer startupSettingsWriter.Close()
if err := startupSettingsWriter.WriteSettings(); err != nil {
slogger.Log(ctx, slog.LevelError,
"writing startup settings",
"err", err,
)
}
// If we have successfully opened the DB, and written a pid,
// we expect we're live. Record the version for osquery to
// pickup
internal.RecordLauncherVersion(ctx, rootDirectory)
dbBackupSaver := agentbbolt.NewDatabaseBackupSaver(k)
runGroup.Add("dbBackupSaver", dbBackupSaver.Execute, dbBackupSaver.Interrupt)
// create the certificate pool
var rootPool *x509.CertPool
if k.RootPEM() != "" {
rootPool = x509.NewCertPool()
pemContents, err := os.ReadFile(k.RootPEM())
if err != nil {
return fmt.Errorf("reading root certs PEM at path: %s: %w", k.RootPEM(), err)
}
if ok := rootPool.AppendCertsFromPEM(pemContents); !ok {
return fmt.Errorf("found no valid certs in PEM at path: %s", k.RootPEM())
}
}
// Add the log checkpoints to the rungroup, and run it once early, to try to get data into the logs.
// The checkpointer can take up to 5 seconds to run, so do this in the background.
checkpointer := checkups.NewCheckupLogger(slogger, k)
gowrapper.Go(ctx, slogger, func() {
checkpointer.Once(ctx)
})
runGroup.Add("logcheckpoint", checkpointer.Run, checkpointer.Interrupt)
watchdogController, err := watchdog.NewController(ctx, k, opts.ConfigFilePath)
if err != nil { // log any issues here but move on, watchdog is not critical path
slogger.Log(ctx, slog.LevelError,
"could not init watchdog controller",
"err", err,
)
} else if watchdogController != nil { // watchdogController will be nil on non-windows platforms for now
k.RegisterChangeObserver(watchdogController, keys.LauncherWatchdogEnabled)
runGroup.Add("watchdogController", watchdogController.Run, watchdogController.Interrupt)
}
// Create a channel for signals
sigChannel := make(chan os.Signal, 1)
// Add a rungroup to catch things on the sigChannel
signalListener := newSignalListener(sigChannel, cancel, slogger)
runGroup.Add("sigChannel", signalListener.Execute, signalListener.Interrupt)
// For now, remediation is not performed -- we only log the hardware change.
agent.DetectAndRemediateHardwareChange(ctx, k)
powerEventSubscriber := powereventwatcher.NewKnapsackSleepStateUpdater(slogger, k)
powerEventWatcher, err := powereventwatcher.New(ctx, slogger, powerEventSubscriber)
if err != nil {
slogger.Log(ctx, slog.LevelDebug,
"could not init power event watcher",
"err", err,
)
} else {
runGroup.Add("powerEventWatcher", powerEventWatcher.Execute, powerEventWatcher.Interrupt)
}
var client service.KolideService
{
switch k.Transport() {
case "grpc":
grpcConn, err := service.DialGRPC(k, rootPool)
if err != nil {
return fmt.Errorf("dialing grpc server: %w", err)
}
defer grpcConn.Close()
client = service.NewGRPCClient(k, grpcConn)
case "jsonrpc":
client = service.NewJSONRPCClient(k, rootPool)
case "osquery":
client = service.NewNoopClient(logger)
default:
return errors.New("invalid transport option selected")
}
}
// make sure keys exist -- we expect these keys to exist before rungroup starts
if err := osquery.SetupLauncherKeys(k.ConfigStore()); err != nil {
return fmt.Errorf("setting up initial launcher keys: %w", err)
}
if err := agent.SetupKeys(ctx, k.Slogger(), k.ConfigStore()); err != nil {
return fmt.Errorf("setting up agent keys: %w", err)
}
// init osquery instance history
if err := osqueryInstanceHistory.InitHistory(k.OsqueryHistoryInstanceStore()); err != nil {
return fmt.Errorf("error initializing osquery instance history: %w", err)
}
// create the runner that will launch osquery
osqueryRunner := osqueryruntime.New(
k,
client,
osqueryruntime.WithAugeasLensFunction(augeas.InstallLenses),
)
runGroup.Add("osqueryRunner", osqueryRunner.Run, osqueryRunner.Interrupt)
k.SetInstanceQuerier(osqueryRunner)
versionInfo := version.Version()
k.SystemSlogger().Log(ctx, slog.LevelInfo,
"started kolide launcher",
"version", versionInfo.Version,
"build", versionInfo.Revision,
)
if traceExporter != nil {
traceExporter.SetOsqueryClient(osqueryRunner)
}
// Create the control service and services that depend on it
var runner *desktopRunner.DesktopUsersProcessesRunner
var actionsQueue *actionqueue.ActionQueue
if k.ControlServerURL() == "" {
slogger.Log(ctx, slog.LevelDebug,
"control server URL not set, will not create control service",
)
} else {
controlService, err := createControlService(ctx, k.ControlStore(), k)
if err != nil {
return fmt.Errorf("failed to setup control service: %w", err)
}
runGroup.Add("controlService", controlService.ExecuteWithContext(ctx), controlService.Interrupt)
// serverDataConsumer handles server data table updates
controlService.RegisterConsumer(serverDataSubsystemName, keyvalueconsumer.New(k.ServerProvidedDataStore()))
// agentFlagConsumer handles agent flags pushed from the control server
controlService.RegisterConsumer(agentFlagsSubsystemName, keyvalueconsumer.New(flagController))
// katcConfigConsumer handles updates to Kolide's custom ATC tables
controlService.RegisterConsumer(katcSubsystemName, keyvalueconsumer.NewConfigConsumer(k.KatcConfigStore()))
controlService.RegisterSubscriber(katcSubsystemName, osqueryRunner)
controlService.RegisterSubscriber(katcSubsystemName, startupSettingsWriter)
runner, err = desktopRunner.New(
k,
controlService,
desktopRunner.WithAuthToken(ulid.New()),
desktopRunner.WithUsersFilesRoot(rootDirectory),
)
if err != nil {
return fmt.Errorf("failed to create desktop runner: %w", err)
}
execute, interrupt, err := agent.SetHardwareKeysRunner(ctx, k.Slogger(), k.ConfigStore(), runner)
if err != nil {
return fmt.Errorf("setting up hardware keys: %w", err)
}
runGroup.Add("hardwareKeys", execute, interrupt)
runGroup.Add("desktopRunner", runner.Execute, runner.Interrupt)
controlService.RegisterConsumer(desktopMenuSubsystemName, runner)
// create an action queue for all other action style commands
actionsQueue = actionqueue.New(
k,
actionqueue.WithContext(ctx),
actionqueue.WithStore(k.ControlServerActionsStore()),
actionqueue.WithOldNotificationsStore(k.SentNotificationsStore()),
)
runGroup.Add("actionsQueue", actionsQueue.StartCleanup, actionsQueue.StopCleanup)
controlService.RegisterConsumer(actionqueue.ActionsSubsystem, actionsQueue)
// register accelerate control consumer
actionsQueue.RegisterActor(acceleratecontrolconsumer.AccelerateControlSubsystem, acceleratecontrolconsumer.New(k))
// register uninstall consumer
actionsQueue.RegisterActor(uninstallconsumer.UninstallSubsystem, uninstallconsumer.New(k))
// register flare consumer
actionsQueue.RegisterActor(flareconsumer.FlareSubsystem, flareconsumer.New(k))
// register force full control data fetch consumer
actionsQueue.RegisterActor(control.ForceFullControlDataFetchAction, controlService)
// create notification consumer
notificationConsumer, err := notificationconsumer.NewNotifyConsumer(
ctx,
k,
runner,
)
if err != nil {
return fmt.Errorf("failed to set up notifier: %w", err)
}
// register notifications consumer
actionsQueue.RegisterActor(notificationconsumer.NotificationSubsystem, notificationConsumer)
remoteRestartConsumer := remoterestartconsumer.New(k)
runGroup.Add("remoteRestart", remoteRestartConsumer.Execute, remoteRestartConsumer.Interrupt)
actionsQueue.RegisterActor(remoterestartconsumer.RemoteRestartActorType, remoteRestartConsumer)
// Set up our tracing instrumentation
authTokenConsumer := keyvalueconsumer.New(k.TokenStore())
if err := controlService.RegisterConsumer(authTokensSubsystemName, authTokenConsumer); err != nil {
return fmt.Errorf("failed to register auth token consumer: %w", err)
}
// begin log shipping and subsribe to token updates
// nil check incase it failed to create for some reason
if logShipper != nil {
controlService.RegisterSubscriber(authTokensSubsystemName, logShipper)
}
if traceExporter != nil {
controlService.RegisterSubscriber(authTokensSubsystemName, traceExporter)
}
if metadataWriter := internal.NewMetadataWriter(slogger, k); metadataWriter == nil {
slogger.Log(ctx, slog.LevelDebug,
"unable to set up metadata writer",
"err", err,
)
} else {
controlService.RegisterSubscriber(serverDataSubsystemName, metadataWriter)
// explicitly trigger the ping at least once to ensure updated metadata is written
// on upgrades, the subscriber will continue to do this automatically when new
// information is made available from server_data (e.g. on a fresh install)
metadataWriter.Ping()
}
}
runEECode := k.ControlServerURL() != "" || k.IAmBreakingEELicense()
// at this moment, these values are the same. This variable is here to help humans parse what's happening
runLocalServer := runEECode
if runLocalServer {
ls, err := localserver.New(
ctx,
k,
runner,
)
if err != nil {
// For now, log this and move on. It might be a fatal error
slogger.Log(ctx, slog.LevelError,
"failed to setup local server",
"err", err,
)
}
ls.SetQuerier(osqueryRunner)
runGroup.Add("localserver", ls.Start, ls.Interrupt)
}
// If autoupdating is enabled, run the autoupdater
if k.Autoupdate() {
metadataClient := http.DefaultClient
metadataClient.Timeout = 30 * time.Second
mirrorClient := http.DefaultClient
mirrorClient.Timeout = 8 * time.Minute // gives us extra time to avoid a timeout on download
tufAutoupdater, err := tuf.NewTufAutoupdater(
ctx,
k,
metadataClient,
mirrorClient,
osqueryRunner,
tuf.WithOsqueryRestart(osqueryRunner.Restart),
)
if err != nil {
return fmt.Errorf("creating TUF autoupdater updater: %w", err)
}
runGroup.Add("tufAutoupdater", tufAutoupdater.Execute, tufAutoupdater.Interrupt)
if actionsQueue != nil {
actionsQueue.RegisterActor(tuf.AutoupdateSubsystemName, tufAutoupdater)
}
// in some cases, (e.g. rolling back a windows installation to a previous osquery version) it is possible that
// the installer leaves us in a situation where there is no osqueryd on disk.
// we can detect this and attempt to download the correct version into the TUF update library to run from that.
// This must be done as a blocking operation before the rungroups start, because the osquery runner will fail to
// launch and trigger a restart immediately
currentOsquerydBinaryPath := k.LatestOsquerydPath(ctx)
if _, err = os.Stat(currentOsquerydBinaryPath); os.IsNotExist(err) {
slogger.Log(ctx, slog.LevelInfo,
"detected missing osqueryd executable, will attempt to download",
)
startupSpan.AddEvent("osqueryd_startup_download_start")
// simulate control server request for immediate update, noting to bypass the initial delay window
actionReader := strings.NewReader(`{
"bypass_initial_delay": true,
"binaries_to_update": [
{ "name": "osqueryd" }
]
}`)
if err = tufAutoupdater.Do(actionReader); err != nil {
slogger.Log(ctx, slog.LevelError,
"failure triggering immediate osquery update",
"err", err,
)
}
startupSpan.AddEvent("osqueryd_startup_download_completed")
}
}
startupSpan.End()
if err := runGroup.Run(); err != nil {
return fmt.Errorf("run service: %w", err)
}
return nil
}
func writePidFile(path string) error {
if err := os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0600); err != nil {
return fmt.Errorf("writing pidfile: %w", err)
}
return nil
}
// runOsqueryVersionCheckAndAddToKnapsack execs the osqueryd binary in the background when we're running
// on to check the version and save it in the Knapsack. This is expected to be called
// from a goroutine, and thus does not return an error.
func runOsqueryVersionCheckAndAddToKnapsack(ctx context.Context, slogger *slog.Logger, k types.Knapsack, osquerydPath string) {
slogger = slogger.With("component", "osquery-version-check")
var output bytes.Buffer
osq, err := runsimple.NewOsqueryProcess(osquerydPath, runsimple.WithStdout(&output))
if err != nil {
slogger.Log(ctx, slog.LevelError,
"unable to create process",
"err", err,
)
return
}
// This has a somewhat long timeout, in case there's a notarization fetch
versionCtx, versionCancel := context.WithTimeout(ctx, 30*time.Second)
defer versionCancel()
osqErr := osq.RunVersion(versionCtx)
outTrimmed := strings.TrimSpace(output.String())
if osqErr != nil {
slogger.Log(ctx, slog.LevelError,
"could not check osqueryd version",
"output", outTrimmed,
"err", err,
"osqueryd_path", osquerydPath,
)
return
}
// log the version to the knappsack
k.SetCurrentRunningOsqueryVersion(outTrimmed)
slogger.Log(ctx, slog.LevelDebug,
"checked osqueryd version",
"osqueryd_version", outTrimmed,
"osqueryd_path", osquerydPath,
)
}