forked from snapcore/snapd
/
helpers.go
258 lines (229 loc) · 7.63 KB
/
helpers.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 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 backend
import (
"archive/zip"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil/sys"
)
func zipMember(f *os.File, member string) (r io.ReadCloser, sz int64, err error) {
// rewind the file
// (shouldn't be needed, but doesn't hurt too much)
if _, err := f.Seek(0, 0); err != nil {
return nil, -1, err
}
fi, err := f.Stat()
if err != nil {
return nil, -1, err
}
arch, err := zip.NewReader(f, fi.Size())
if err != nil {
return nil, -1, err
}
for _, fh := range arch.File {
if fh.Name == member {
r, err = fh.Open()
return r, int64(fh.UncompressedSize64), err
}
}
return nil, -1, fmt.Errorf("missing archive member %q", member)
}
func userArchiveName(usr *user.User) string {
return filepath.Join(userArchivePrefix, usr.Username+userArchiveSuffix)
}
func isUserArchive(entry string) bool {
return strings.HasPrefix(entry, userArchivePrefix) && strings.HasSuffix(entry, userArchiveSuffix)
}
func entryUsername(entry string) string {
// this _will_ panic if !isUserArchive(entry)
return entry[len(userArchivePrefix) : len(entry)-len(userArchiveSuffix)]
}
type bySnap []*client.Snapshot
func (a bySnap) Len() int { return len(a) }
func (a bySnap) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a bySnap) Less(i, j int) bool { return a[i].Snap < a[j].Snap }
type byID []client.SnapshotSet
func (a byID) Len() int { return len(a) }
func (a byID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byID) Less(i, j int) bool { return a[i].ID < a[j].ID }
var (
userLookup = user.Lookup
userLookupId = user.LookupId
)
func isUnknownUser(err error) bool {
switch err.(type) {
case user.UnknownUserError, user.UnknownUserIdError:
return true
default:
return false
}
}
func usersForUsernamesImpl(usernames []string) ([]*user.User, error) {
if len(usernames) == 0 {
return allUsers()
}
users := make([]*user.User, 0, len(usernames))
for _, username := range usernames {
usr, err := userLookup(username)
if err != nil {
// Treat all non-nil errors as user.Unknown{User,Group}Error's, as
// currently Go's handling of returned errno from get{pw,gr}nam_r
// in the cgo implementation of user.Lookup is lacking, and thus
// user.Unknown{User,Group}Error is returned only when errno is 0
// and the list of users/groups is empty, but as per the man page
// for get{pw,gr}nam_r, there are many other errno's that typical
// systems could return to indicate that the user/group wasn't
// found, however unfortunately the POSIX standard does not actually
// dictate what errno should be used to indicate "user/group not
// found", and so even if Go is more robust, it may not ever be
// fully robust. See from the man page:
//
// > It [POSIX.1-2001] does not call "not found" an error, hence
// > does not specify what value errno might have in this situation.
// > But that makes it impossible to recognize errors.
//
// See upstream Go issue: https://github.com/golang/go/issues/40334
u, e := userLookupId(username)
if e != nil {
// return first error, as it's usually clearer
return nil, err
}
usr = u
}
users = append(users, usr)
}
return users, nil
}
func allUsers() ([]*user.User, error) {
ds, err := filepath.Glob(dirs.SnapDataHomeGlob)
if err != nil {
// can't happen?
return nil, err
}
users := make([]*user.User, 1, len(ds)+1)
root, err := user.LookupId("0")
if err != nil {
return nil, err
}
users[0] = root
seen := make(map[uint32]bool, len(ds)+1)
seen[0] = true
var st syscall.Stat_t
for _, d := range ds {
err := syscall.Stat(d, &st)
if err != nil {
continue
}
if seen[st.Uid] {
continue
}
seen[st.Uid] = true
usr, err := userLookupId(strconv.FormatUint(uint64(st.Uid), 10))
if err != nil {
// Treat all non-nil errors as user.Unknown{User,Group}Error's, as
// currently Go's handling of returned errno from get{pw,gr}nam_r
// in the cgo implementation of user.Lookup is lacking, and thus
// user.Unknown{User,Group}Error is returned only when errno is 0
// and the list of users/groups is empty, but as per the man page
// for get{pw,gr}nam_r, there are many other errno's that typical
// systems could return to indicate that the user/group wasn't
// found, however unfortunately the POSIX standard does not actually
// dictate what errno should be used to indicate "user/group not
// found", and so even if Go is more robust, it may not ever be
// fully robust. See from the man page:
//
// > It [POSIX.1-2001] does not call "not found" an error, hence
// > does not specify what value errno might have in this situation.
// > But that makes it impossible to recognize errors.
//
// See upstream Go issue: https://github.com/golang/go/issues/40334
continue
} else {
users = append(users, usr)
}
}
return users, nil
}
var (
sysGeteuid = sys.Geteuid
execLookPath = exec.LookPath
)
func pickUserWrapper() string {
// runuser and sudo happen to work the same way in this case. The main
// reason to prefer runuser over sudo is that runuser is part of
// util-linux, which is considered essential, whereas sudo is an addon
// which could be removed. However util-linux < 2.23 does not have
// runuser, and we support some distros that ship things older than that
// (e.g. Ubuntu 14.04)
for _, cmd := range []string{"runuser", "sudo"} {
if lp, err := execLookPath(cmd); err == nil {
return lp
}
}
return ""
}
var userWrapper = pickUserWrapper()
// tarAsUser returns an exec.Cmd that will, if the current effective user id is
// 0 and username is not "root", and if either runuser(1) or sudo(8) are found
// on the PATH, run tar as the given user.
//
// If the effective user id is not 0, or username is "root", exec.Command is
// used directly; changing the user id would fail (in the first case) or be a
// no-op (in the second).
//
// If neither runuser nor sudo are found on the path, exec.Command is also used
// directly. This will result in tar running as root in this situation (so it
// will fail if on NFS; I don't think there's an attack vector though).
func tarAsUser(username string, args ...string) *exec.Cmd {
if sysGeteuid() == 0 && username != "root" {
if userWrapper != "" {
uwArgs := make([]string, len(args)+5)
uwArgs[0] = userWrapper
uwArgs[1] = "-u"
uwArgs[2] = username
uwArgs[3] = "--"
uwArgs[4] = "tar"
copy(uwArgs[5:], args)
return &exec.Cmd{
Path: userWrapper,
Args: uwArgs,
}
}
// TODO: use warnings instead
logger.Noticef("No user wrapper found; running tar for user data as root. Please make sure 'sudo' or 'runuser' (from util-linux) is on $PATH to avoid this.")
}
return exec.Command("tar", args...)
}
func MockUserLookup(newLookup func(string) (*user.User, error)) func() {
oldLookup := userLookup
userLookup = newLookup
return func() {
userLookup = oldLookup
}
}