forked from snapcore/snapd
/
cmd_run.go
1179 lines (1051 loc) · 37 KB
/
cmd_run.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/godbus/dbus"
"github.com/jessevdk/go-flags"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dbusutil"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/strace"
"github.com/snapcore/snapd/sandbox/cgroup"
"github.com/snapcore/snapd/sandbox/selinux"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapenv"
"github.com/snapcore/snapd/strutil/shlex"
"github.com/snapcore/snapd/timeutil"
"github.com/snapcore/snapd/x11"
)
var (
syscallExec = syscall.Exec
userCurrent = user.Current
osGetenv = os.Getenv
timeNow = time.Now
selinuxIsEnabled = selinux.IsEnabled
selinuxVerifyPathContext = selinux.VerifyPathContext
selinuxRestoreContext = selinux.RestoreContext
)
type cmdRun struct {
clientMixin
Command string `long:"command" hidden:"yes"`
HookName string `long:"hook" hidden:"yes"`
Revision string `short:"r" default:"unset" hidden:"yes"`
Shell bool `long:"shell" `
// This options is both a selector (use or don't use strace) and it
// can also carry extra options for strace. This is why there is
// "default" and "optional-value" to distinguish this.
Strace string `long:"strace" optional:"true" optional-value:"with-strace" default:"no-strace" default-mask:"-"`
Gdb bool `long:"gdb"`
Gdbserver string `long:"experimental-gdbserver" default:"no-gdbserver" optional-value:":0" optional:"true"`
TraceExec bool `long:"trace-exec"`
// not a real option, used to check if cmdRun is initialized by
// the parser
ParserRan int `long:"parser-ran" default:"1" hidden:"yes"`
Timer string `long:"timer" hidden:"yes"`
}
func init() {
addCommand("run",
i18n.G("Run the given snap command"),
i18n.G(`
The run command executes the given snap command with the right confinement
and environment.
`),
func() flags.Commander {
return &cmdRun{}
}, map[string]string{
// TRANSLATORS: This should not start with a lowercase letter.
"command": i18n.G("Alternative command to run"),
// TRANSLATORS: This should not start with a lowercase letter.
"hook": i18n.G("Hook to run"),
// TRANSLATORS: This should not start with a lowercase letter.
"r": i18n.G("Use a specific snap revision when running hook"),
// TRANSLATORS: This should not start with a lowercase letter.
"shell": i18n.G("Run a shell instead of the command (useful for debugging)"),
// TRANSLATORS: This should not start with a lowercase letter.
"strace": i18n.G("Run the command under strace (useful for debugging). Extra strace options can be specified as well here. Pass --raw to strace early snap helpers."),
// TRANSLATORS: This should not start with a lowercase letter.
"gdb": i18n.G("Run the command with gdb"),
// TRANSLATORS: This should not start with a lowercase letter.
"experimental-gdbserver": i18n.G("Run the command with gdbserver (experimental)"),
// TRANSLATORS: This should not start with a lowercase letter.
"timer": i18n.G("Run as a timer service with given schedule"),
// TRANSLATORS: This should not start with a lowercase letter.
"trace-exec": i18n.G("Display exec calls timing data"),
"parser-ran": "",
}, nil)
}
// isStopping returns true if the system is shutting down.
func isStopping() (bool, error) {
// Make sure, just in case, that systemd doesn't localize the output string.
env, err := osutil.OSEnvironment()
if err != nil {
return false, err
}
env["LC_MESSAGES"] = "C"
// Check if systemd is stopping (shutting down or rebooting).
cmd := exec.Command("systemctl", "is-system-running")
cmd.Env = env.ForExec()
stdout, err := cmd.Output()
// systemctl is-system-running returns non-zero for outcomes other than "running"
// As such, ignore any ExitError and just process the stdout buffer.
if _, ok := err.(*exec.ExitError); ok {
return string(stdout) == "stopping\n", nil
}
return false, err
}
func maybeWaitForSecurityProfileRegeneration(cli *client.Client) error {
// check if the security profiles key has changed, if so, we need
// to wait for snapd to re-generate all profiles
mismatch, err := interfaces.SystemKeyMismatch()
if err == nil && !mismatch {
return nil
}
// something went wrong with the system-key compare, try to
// reach snapd before continuing
if err != nil {
logger.Debugf("SystemKeyMismatch returned an error: %v", err)
}
// We have a mismatch but maybe it is only because systemd is shutting down
// and core or snapd were already unmounted and we failed to re-execute.
// For context see: https://bugs.launchpad.net/snapd/+bug/1871652
stopping, err := isStopping()
if err != nil {
logger.Debugf("cannot check if system is stopping: %s", err)
}
if stopping {
logger.Debugf("ignoring system key mismatch during system shutdown/reboot")
return nil
}
// We have a mismatch, try to connect to snapd, once we can
// connect we just continue because that usually means that
// a new snapd is ready and has generated profiles.
//
// There is a corner case if an upgrade leaves the old snapd
// running and we connect to the old snapd. Handling this
// correctly is tricky because our "snap run" pipeline may
// depend on profiles written by the new snapd. So for now we
// just continue and hope for the best. The real fix for this
// is to fix the packaging so that snapd is stopped, upgraded
// and started.
//
// connect timeout for client is 5s on each try, so 12*5s = 60s
timeout := 12
if timeoutEnv := os.Getenv("SNAPD_DEBUG_SYSTEM_KEY_RETRY"); timeoutEnv != "" {
if i, err := strconv.Atoi(timeoutEnv); err == nil {
timeout = i
}
}
logger.Debugf("system key mismatch detected, waiting for snapd to start responding...")
for i := 0; i < timeout; i++ {
// TODO: we could also check cli.Maintenance() here too in case snapd is
// down semi-permanently for a refresh, but what message do we show to
// the user or what do we do if we know snapd is down for maintenance?
if _, err := cli.SysInfo(); err == nil {
return nil
}
// sleep a little bit for good measure
time.Sleep(1 * time.Second)
}
return fmt.Errorf("timeout waiting for snap system profiles to get updated")
}
func (x *cmdRun) Execute(args []string) error {
if len(args) == 0 {
return fmt.Errorf(i18n.G("need the application to run as argument"))
}
snapApp := args[0]
args = args[1:]
// Catch some invalid parameter combinations, provide helpful errors
optionsSet := 0
for _, param := range []string{x.HookName, x.Command, x.Timer} {
if param != "" {
optionsSet++
}
}
if optionsSet > 1 {
return fmt.Errorf("you can only use one of --hook, --command, and --timer")
}
if x.Revision != "unset" && x.Revision != "" && x.HookName == "" {
return fmt.Errorf(i18n.G("-r can only be used with --hook"))
}
if x.HookName != "" && len(args) > 0 {
// TRANSLATORS: %q is the hook name; %s a space-separated list of extra arguments
return fmt.Errorf(i18n.G("too many arguments for hook %q: %s"), x.HookName, strings.Join(args, " "))
}
if err := maybeWaitForSecurityProfileRegeneration(x.client); err != nil {
return err
}
// Now actually handle the dispatching
if x.HookName != "" {
return x.snapRunHook(snapApp)
}
if x.Command == "complete" {
snapApp, args = antialias(snapApp, args)
}
if x.Timer != "" {
return x.snapRunTimer(snapApp, x.Timer, args)
}
return x.snapRunApp(snapApp, args)
}
// antialias changes snapApp and args if snapApp is actually an alias
// for something else. If not, or if the args aren't what's expected
// for completion, it returns them unchanged.
func antialias(snapApp string, args []string) (string, []string) {
if len(args) < 7 {
// NOTE if len(args) < 7, Something is Wrong (at least WRT complete.sh and etelpmoc.sh)
return snapApp, args
}
actualApp, err := resolveApp(snapApp)
if err != nil || actualApp == snapApp {
// no alias! woop.
return snapApp, args
}
compPoint, err := strconv.Atoi(args[2])
if err != nil {
// args[2] is not COMP_POINT
return snapApp, args
}
if compPoint <= len(snapApp) {
// COMP_POINT is inside $0
return snapApp, args
}
if compPoint > len(args[5]) {
// COMP_POINT is bigger than $#
return snapApp, args
}
if args[6] != snapApp {
// args[6] is not COMP_WORDS[0]
return snapApp, args
}
// it _should_ be COMP_LINE followed by one of
// COMP_WORDBREAKS, but that's hard to do
re, err := regexp.Compile(`^` + regexp.QuoteMeta(snapApp) + `\b`)
if err != nil || !re.MatchString(args[5]) {
// (weird regexp error, or) args[5] is not COMP_LINE
return snapApp, args
}
argsOut := make([]string, len(args))
copy(argsOut, args)
argsOut[2] = strconv.Itoa(compPoint - len(snapApp) + len(actualApp))
argsOut[5] = re.ReplaceAllLiteralString(args[5], actualApp)
argsOut[6] = actualApp
return actualApp, argsOut
}
func getSnapInfo(snapName string, revision snap.Revision) (info *snap.Info, err error) {
if revision.Unset() {
info, err = snap.ReadCurrentInfo(snapName)
} else {
info, err = snap.ReadInfo(snapName, &snap.SideInfo{
Revision: revision,
})
}
return info, err
}
func createOrUpdateUserDataSymlink(info *snap.Info, usr *user.User) error {
// 'current' symlink for user data (SNAP_USER_DATA)
userData := info.UserDataDir(usr.HomeDir)
wantedSymlinkValue := filepath.Base(userData)
currentActiveSymlink := filepath.Join(userData, "..", "current")
var err error
var currentSymlinkValue string
for i := 0; i < 5; i++ {
currentSymlinkValue, err = os.Readlink(currentActiveSymlink)
// Failure other than non-existing symlink is fatal
if err != nil && !os.IsNotExist(err) {
// TRANSLATORS: %v the error message
return fmt.Errorf(i18n.G("cannot read symlink: %v"), err)
}
if currentSymlinkValue == wantedSymlinkValue {
break
}
if err == nil {
// We may be racing with other instances of snap-run that try to do the same thing
// If the symlink is already removed then we can ignore this error.
err = os.Remove(currentActiveSymlink)
if err != nil && !os.IsNotExist(err) {
// abort with error
break
}
}
err = os.Symlink(wantedSymlinkValue, currentActiveSymlink)
// Error other than symlink already exists will abort and be propagated
if err == nil || !os.IsExist(err) {
break
}
// If we arrived here it means the symlink couldn't be created because it got created
// in the meantime by another instance, so we will try again.
}
if err != nil {
return fmt.Errorf(i18n.G("cannot update the 'current' symlink of %q: %v"), currentActiveSymlink, err)
}
return nil
}
func createUserDataDirs(info *snap.Info) error {
// Adjust umask so that the created directories have the permissions we
// expect and are unaffected by the initial umask. While go runtime creates
// threads at will behind the scenes, the setting of umask applies to the
// entire process so it doesn't need any special handling to lock the
// executing goroutine to a single thread.
oldUmask := syscall.Umask(0)
defer syscall.Umask(oldUmask)
usr, err := userCurrent()
if err != nil {
return fmt.Errorf(i18n.G("cannot get the current user: %v"), err)
}
// see snapenv.User
instanceUserData := info.UserDataDir(usr.HomeDir)
instanceCommonUserData := info.UserCommonDataDir(usr.HomeDir)
createDirs := []string{instanceUserData, instanceCommonUserData}
if info.InstanceKey != "" {
// parallel instance snaps get additional mapping in their mount
// namespace, namely /home/joe/snap/foo_bar ->
// /home/joe/snap/foo, make sure that the mount point exists and
// is owned by the user
snapUserDir := snap.UserSnapDir(usr.HomeDir, info.SnapName())
createDirs = append(createDirs, snapUserDir)
}
for _, d := range createDirs {
if err := os.MkdirAll(d, 0755); err != nil {
// TRANSLATORS: %q is the directory whose creation failed, %v the error message
return fmt.Errorf(i18n.G("cannot create %q: %v"), d, err)
}
}
if err := createOrUpdateUserDataSymlink(info, usr); err != nil {
return err
}
return maybeRestoreSecurityContext(usr)
}
// maybeRestoreSecurityContext attempts to restore security context of ~/snap on
// systems where it's applicable
func maybeRestoreSecurityContext(usr *user.User) error {
snapUserHome := filepath.Join(usr.HomeDir, dirs.UserHomeSnapDir)
enabled, err := selinuxIsEnabled()
if err != nil {
return fmt.Errorf("cannot determine SELinux status: %v", err)
}
if !enabled {
logger.Debugf("SELinux not enabled")
return nil
}
match, err := selinuxVerifyPathContext(snapUserHome)
if err != nil {
return fmt.Errorf("failed to verify SELinux context of %v: %v", snapUserHome, err)
}
if match {
return nil
}
logger.Noticef("restoring default SELinux context of %v", snapUserHome)
if err := selinuxRestoreContext(snapUserHome, selinux.RestoreMode{Recursive: true}); err != nil {
return fmt.Errorf("cannot restore SELinux context of %v: %v", snapUserHome, err)
}
return nil
}
func (x *cmdRun) useStrace() bool {
// make sure the go-flag parser ran and assigned default values
return x.ParserRan == 1 && x.Strace != "no-strace"
}
func (x *cmdRun) straceOpts() (opts []string, raw bool, err error) {
if x.Strace == "with-strace" {
return nil, false, nil
}
split, err := shlex.Split(x.Strace)
if err != nil {
return nil, false, err
}
opts = make([]string, 0, len(split))
for _, opt := range split {
if opt == "--raw" {
raw = true
continue
}
opts = append(opts, opt)
}
return opts, raw, nil
}
func (x *cmdRun) snapRunApp(snapApp string, args []string) error {
snapName, appName := snap.SplitSnapApp(snapApp)
info, err := getSnapInfo(snapName, snap.R(0))
if err != nil {
return err
}
app := info.Apps[appName]
if app == nil {
return fmt.Errorf(i18n.G("cannot find app %q in %q"), appName, snapName)
}
return x.runSnapConfine(info, app.SecurityTag(), snapApp, "", args)
}
func (x *cmdRun) snapRunHook(snapName string) error {
revision, err := snap.ParseRevision(x.Revision)
if err != nil {
return err
}
info, err := getSnapInfo(snapName, revision)
if err != nil {
return err
}
hook := info.Hooks[x.HookName]
if hook == nil {
return fmt.Errorf(i18n.G("cannot find hook %q in %q"), x.HookName, snapName)
}
return x.runSnapConfine(info, hook.SecurityTag(), snapName, hook.Name, nil)
}
func (x *cmdRun) snapRunTimer(snapApp, timer string, args []string) error {
schedule, err := timeutil.ParseSchedule(timer)
if err != nil {
return fmt.Errorf("invalid timer format: %v", err)
}
now := timeNow()
if !timeutil.Includes(schedule, now) {
fmt.Fprintf(Stderr, "%s: attempted to run %q timer outside of scheduled time %q\n", now.Format(time.RFC3339), snapApp, timer)
return nil
}
return x.snapRunApp(snapApp, args)
}
var osReadlink = os.Readlink
// snapdHelperPath return the path of a helper like "snap-confine" or
// "snap-exec" based on if snapd is re-execed or not
func snapdHelperPath(toolName string) (string, error) {
exe, err := osReadlink("/proc/self/exe")
if err != nil {
return "", fmt.Errorf("cannot read /proc/self/exe: %v", err)
}
// no re-exec
if !strings.HasPrefix(exe, dirs.SnapMountDir) {
return filepath.Join(dirs.DistroLibExecDir, toolName), nil
}
// The logic below only works if the last two path components
// are /usr/bin
// FIXME: use a snap warning?
if !strings.HasSuffix(exe, "/usr/bin/"+filepath.Base(exe)) {
logger.Noticef("(internal error): unexpected exe input in snapdHelperPath: %v", exe)
return filepath.Join(dirs.DistroLibExecDir, toolName), nil
}
// snapBase will be "/snap/{core,snapd}/$rev/" because
// the snap binary is always at $root/usr/bin/snap
snapBase := filepath.Clean(filepath.Join(filepath.Dir(exe), "..", ".."))
// Run snap-confine from the core/snapd snap. The tools in
// core/snapd snap are statically linked, or mostly
// statically, with the exception of libraries such as libudev
// and libc.
return filepath.Join(snapBase, dirs.CoreLibExecDir, toolName), nil
}
func migrateXauthority(info *snap.Info) (string, error) {
u, err := userCurrent()
if err != nil {
return "", fmt.Errorf(i18n.G("cannot get the current user: %s"), err)
}
// If our target directory (XDG_RUNTIME_DIR) doesn't exist we
// don't attempt to create it.
baseTargetDir := filepath.Join(dirs.XdgRuntimeDirBase, u.Uid)
if !osutil.FileExists(baseTargetDir) {
return "", nil
}
xauthPath := osGetenv("XAUTHORITY")
if len(xauthPath) == 0 || !osutil.FileExists(xauthPath) {
// Nothing to do for us. Most likely running outside of any
// graphical X11 session.
return "", nil
}
fin, err := os.Open(xauthPath)
if err != nil {
return "", err
}
defer fin.Close()
// Abs() also calls Clean(); see https://golang.org/pkg/path/filepath/#Abs
xauthPathAbs, err := filepath.Abs(fin.Name())
if err != nil {
return "", nil
}
// Remove all symlinks from path
xauthPathCan, err := filepath.EvalSymlinks(xauthPathAbs)
if err != nil {
return "", nil
}
// Ensure the XAUTHORITY env is not abused by checking that
// it point to exactly the file we just opened (no symlinks,
// no funny "../.." etc)
if fin.Name() != xauthPathCan {
logger.Noticef("WARNING: XAUTHORITY environment value is not a clean path: %q", xauthPathCan)
return "", nil
}
// Only do the migration from /tmp since the real /tmp is not visible for snaps
if !strings.HasPrefix(fin.Name(), "/tmp/") {
return "", nil
}
// We are performing a Stat() here to make sure that the user can't
// steal another user's Xauthority file. Note that while Stat() uses
// fstat() on the file descriptor created during Open(), the file might
// have changed ownership between the Open() and the Stat(). That's ok
// because we aren't trying to block access that the user already has:
// if the user has the privileges to chown another user's Xauthority
// file, we won't block that since the user can just steal it without
// having to use snap run. This code is just to ensure that a user who
// doesn't have those privileges can't steal the file via snap run
// (also note that the (potentially untrusted) snap isn't running yet).
fi, err := fin.Stat()
if err != nil {
return "", err
}
sys := fi.Sys()
if sys == nil {
return "", fmt.Errorf(i18n.G("cannot validate owner of file %s"), fin.Name())
}
// cheap comparison as the current uid is only available as a string
// but it is better to convert the uid from the stat result to a
// string than a string into a number.
if fmt.Sprintf("%d", sys.(*syscall.Stat_t).Uid) != u.Uid {
return "", fmt.Errorf(i18n.G("Xauthority file isn't owned by the current user %s"), u.Uid)
}
targetPath := filepath.Join(baseTargetDir, ".Xauthority")
// Only validate Xauthority file again when both files don't match
// otherwise we can continue using the existing Xauthority file.
// This is ok to do here because we aren't trying to protect against
// the user changing the Xauthority file in XDG_RUNTIME_DIR outside
// of snapd.
if osutil.FileExists(targetPath) {
var fout *os.File
if fout, err = os.Open(targetPath); err != nil {
return "", err
}
if osutil.StreamsEqual(fin, fout) {
fout.Close()
return targetPath, nil
}
fout.Close()
if err := os.Remove(targetPath); err != nil {
return "", err
}
// Ensure we're validating the Xauthority file from the beginning
if _, err := fin.Seek(int64(os.SEEK_SET), 0); err != nil {
return "", err
}
}
// To guard against setting XAUTHORITY to non-xauth files, check
// that we have a valid Xauthority. Specifically, the file must be
// parseable as an Xauthority file and not be empty.
if err := x11.ValidateXauthority(fin); err != nil {
return "", err
}
// Read data from the beginning of the file
if _, err = fin.Seek(int64(os.SEEK_SET), 0); err != nil {
return "", err
}
fout, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return "", err
}
defer fout.Close()
// Read and write validated Xauthority file to its right location
if _, err = io.Copy(fout, fin); err != nil {
if err := os.Remove(targetPath); err != nil {
logger.Noticef("WARNING: cannot remove file at %s: %s", targetPath, err)
}
return "", fmt.Errorf(i18n.G("cannot write new Xauthority file at %s: %s"), targetPath, err)
}
return targetPath, nil
}
func activateXdgDocumentPortal(info *snap.Info, snapApp, hook string) error {
// Don't do anything for apps or hooks that don't plug the
// desktop interface
//
// NOTE: This check is imperfect because we don't really know
// if the interface is connected or not but this is an
// acceptable compromise for not having to communicate with
// snapd in snap run. In a typical desktop session the
// document portal can be in use by many applications, not
// just by snaps, so this is at most, pre-emptively using some
// extra memory.
var plugs map[string]*snap.PlugInfo
if hook != "" {
plugs = info.Hooks[hook].Plugs
} else {
_, appName := snap.SplitSnapApp(snapApp)
plugs = info.Apps[appName].Plugs
}
plugsDesktop := false
for _, plug := range plugs {
if plug.Interface == "desktop" {
plugsDesktop = true
break
}
}
if !plugsDesktop {
return nil
}
u, err := userCurrent()
if err != nil {
return fmt.Errorf(i18n.G("cannot get the current user: %s"), err)
}
xdgRuntimeDir := filepath.Join(dirs.XdgRuntimeDirBase, u.Uid)
// If $XDG_RUNTIME_DIR/doc appears to be a mount point, assume
// that the document portal is up and running.
expectedMountPoint := filepath.Join(xdgRuntimeDir, "doc")
if mounted, err := osutil.IsMounted(expectedMountPoint); err != nil {
logger.Noticef("Could not check document portal mount state: %s", err)
} else if mounted {
return nil
}
// If there is no session bus, our job is done. We check this
// manually to avoid dbus.SessionBus() auto-launching a new
// bus.
busAddress := osGetenv("DBUS_SESSION_BUS_ADDRESS")
if len(busAddress) == 0 {
return nil
}
// We've previously tried to start the document portal and
// were told the service is unknown: don't bother connecting
// to the session bus again.
//
// As the file is in $XDG_RUNTIME_DIR, it will be cleared over
// full logout/login or reboot cycles.
portalsUnavailableFile := filepath.Join(xdgRuntimeDir, ".portals-unavailable")
if osutil.FileExists(portalsUnavailableFile) {
return nil
}
conn, err := dbusutil.SessionBus()
if err != nil {
return err
}
portal := conn.Object("org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents")
var mountPoint []byte
if err := portal.Call("org.freedesktop.portal.Documents.GetMountPoint", 0).Store(&mountPoint); err != nil {
// It is not considered an error if
// xdg-document-portal is not available on the system.
if dbusErr, ok := err.(dbus.Error); ok && dbusErr.Name == "org.freedesktop.DBus.Error.ServiceUnknown" {
// We ignore errors here: if writing the file
// fails, we'll just try connecting to D-Bus
// again next time.
if err = ioutil.WriteFile(portalsUnavailableFile, []byte(""), 0644); err != nil {
logger.Noticef("WARNING: cannot write file at %s: %s", portalsUnavailableFile, err)
}
return nil
}
return err
}
// Sanity check to make sure the document portal is exposed
// where we think it is.
actualMountPoint := strings.TrimRight(string(mountPoint), "\x00")
if actualMountPoint != expectedMountPoint {
return fmt.Errorf(i18n.G("Expected portal at %#v, got %#v"), expectedMountPoint, actualMountPoint)
}
return nil
}
type envForExecFunc func(extra map[string]string) []string
var gdbServerWelcomeFmt = `
Welcome to "snap run --gdbserver".
You are right before your application is run.
Please open a different terminal and run:
gdb -ex="target remote %[1]s" -ex=continue -ex="signal SIGCONT"
(gdb) continue
or use your favorite gdb frontend and connect to %[1]s
`
func racyFindFreePort() (int, error) {
l, err := net.Listen("tcp", ":0")
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func (x *cmdRun) useGdbserver() bool {
// make sure the go-flag parser ran and assigned default values
return x.ParserRan == 1 && x.Gdbserver != "no-gdbserver"
}
func (x *cmdRun) runCmdUnderGdbserver(origCmd []string, envForExec envForExecFunc) error {
gcmd := exec.Command(origCmd[0], origCmd[1:]...)
gcmd.Stdin = os.Stdin
gcmd.Stdout = os.Stdout
gcmd.Stderr = os.Stderr
gcmd.Env = envForExec(map[string]string{"SNAP_CONFINE_RUN_UNDER_GDBSERVER": "1"})
if err := gcmd.Start(); err != nil {
return err
}
// wait for the child process executing gdb helper to raise SIGSTOP
// signalling readiness to attach a gdbserver process
var status syscall.WaitStatus
_, err := syscall.Wait4(gcmd.Process.Pid, &status, syscall.WSTOPPED, nil)
if err != nil {
return err
}
addr := x.Gdbserver
if addr == ":0" {
// XXX: run "gdbserver :0" instead and parse "Listening on port 45971"
// on stderr instead?
port, err := racyFindFreePort()
if err != nil {
return fmt.Errorf("cannot find free port: %v", err)
}
addr = fmt.Sprintf(":%v", port)
}
// XXX: should we provide a helper here instead? something like
// `snap run --attach-debugger` or similar? The downside
// is that attaching a gdb frontend is harder?
fmt.Fprintf(Stdout, fmt.Sprintf(gdbServerWelcomeFmt, addr))
// note that only gdbserver needs to run as root, the application
// keeps running as the user
gdbSrvCmd := exec.Command("sudo", "-E", "gdbserver", "--attach", addr, strconv.Itoa(gcmd.Process.Pid))
if output, err := gdbSrvCmd.CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
func (x *cmdRun) runCmdUnderGdb(origCmd []string, envForExec envForExecFunc) error {
// the resulting application process runs as root
cmd := []string{"sudo", "-E", "gdb", "-ex=run", "-ex=catch exec", "-ex=continue", "--args"}
cmd = append(cmd, origCmd...)
gcmd := exec.Command(cmd[0], cmd[1:]...)
gcmd.Stdin = os.Stdin
gcmd.Stdout = os.Stdout
gcmd.Stderr = os.Stderr
gcmd.Env = envForExec(map[string]string{"SNAP_CONFINE_RUN_UNDER_GDB": "1"})
return gcmd.Run()
}
func (x *cmdRun) runCmdWithTraceExec(origCmd []string, envForExec envForExecFunc) error {
// setup private tmp dir with strace fifo
straceTmp, err := ioutil.TempDir("", "exec-trace")
if err != nil {
return err
}
defer os.RemoveAll(straceTmp)
straceLog := filepath.Join(straceTmp, "strace.fifo")
if err := syscall.Mkfifo(straceLog, 0640); err != nil {
return err
}
// ensure we have one writer on the fifo so that if strace fails
// nothing blocks
fw, err := os.OpenFile(straceLog, os.O_RDWR, 0640)
if err != nil {
return err
}
defer fw.Close()
// read strace data from fifo async
var slg *strace.ExecveTiming
var straceErr error
doneCh := make(chan bool, 1)
go func() {
// FIXME: make this configurable?
nSlowest := 10
slg, straceErr = strace.TraceExecveTimings(straceLog, nSlowest)
close(doneCh)
}()
cmd, err := strace.TraceExecCommand(straceLog, origCmd...)
if err != nil {
return err
}
// run
cmd.Env = envForExec(nil)
cmd.Stdin = Stdin
cmd.Stdout = Stdout
cmd.Stderr = Stderr
err = cmd.Run()
// ensure we close the fifo here so that the strace.TraceExecCommand()
// helper gets a EOF from the fifo (i.e. all writers must be closed
// for this)
fw.Close()
// wait for strace reader
<-doneCh
if straceErr == nil {
slg.Display(Stderr)
} else {
logger.Noticef("cannot extract runtime data: %v", straceErr)
}
return err
}
func (x *cmdRun) runCmdUnderStrace(origCmd []string, envForExec envForExecFunc) error {
extraStraceOpts, raw, err := x.straceOpts()
if err != nil {
return err
}
cmd, err := strace.Command(extraStraceOpts, origCmd...)
if err != nil {
return err
}
// run with filter
cmd.Env = envForExec(nil)
cmd.Stdin = Stdin
cmd.Stdout = Stdout
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
filterDone := make(chan bool, 1)
go func() {
defer func() { filterDone <- true }()
if raw {
// Passing --strace='--raw' disables the filtering of
// early strace output. This is useful when tracking
// down issues with snap helpers such as snap-confine,
// snap-exec ...
io.Copy(Stderr, stderr)
return
}
r := bufio.NewReader(stderr)
// The first thing from strace if things work is
// "exeve(" - show everything until we see this to
// not swallow real strace errors.
for {
s, err := r.ReadString('\n')
if err != nil {
break
}
if strings.Contains(s, "execve(") {
break
}
fmt.Fprint(Stderr, s)
}
// The last thing that snap-exec does is to
// execve() something inside the snap dir so
// we know that from that point on the output
// will be interessting to the user.
//
// We need check both /snap (which is where snaps
// are located inside the mount namespace) and the
// distro snap mount dir (which is different on e.g.
// fedora/arch) to fully work with classic snaps.
needle1 := fmt.Sprintf(`execve("%s`, dirs.SnapMountDir)
needle2 := `execve("/snap`
for {
s, err := r.ReadString('\n')
if err != nil {
if err != io.EOF {
fmt.Fprintf(Stderr, "cannot read strace output: %s\n", err)
}
break
}
// Ensure we catch the execve but *not* the
// exec into
// /snap/core/current/usr/lib/snapd/snap-confine
// which is just `snap run` using the core version
// snap-confine.
if (strings.Contains(s, needle1) || strings.Contains(s, needle2)) && !strings.Contains(s, "usr/lib/snapd/snap-confine") {
fmt.Fprint(Stderr, s)
break
}
}
io.Copy(Stderr, r)
}()
if err := cmd.Start(); err != nil {
return err
}
<-filterDone
err = cmd.Wait()
return err
}
func (x *cmdRun) runSnapConfine(info *snap.Info, securityTag, snapApp, hook string, args []string) error {
snapConfine, err := snapdHelperPath("snap-confine")
if err != nil {
return err
}
if !osutil.FileExists(snapConfine) {
if hook != "" {
logger.Noticef("WARNING: skipping running hook %q of snap %q: missing snap-confine", hook, info.InstanceName())
return nil
}
return fmt.Errorf(i18n.G("missing snap-confine: try updating your core/snapd package"))
}
if err := createUserDataDirs(info); err != nil {
logger.Noticef("WARNING: cannot create user data directory: %s", err)
}
xauthPath, err := migrateXauthority(info)
if err != nil {
logger.Noticef("WARNING: cannot copy user Xauthority file: %s", err)
}