Debian Codegraph @

keyring/user_keyring.go

raw
1 /*
2 * user_keyring.go - Add/remove encryption policy keys to/from user keyrings.
3 * This is the deprecated mechanism; see fs_keyring.go for the new mechanism.
4 *
5 * Copyright 2017 Google Inc.
6 * Author: Joe Richey ([email protected])
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 * use this file except in compliance with the License. You may obtain a copy of
10 * the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 * License for the specific language governing permissions and limitations under
18 * the License.
19 */
20
21 package keyring
22
23 import (
24 "os/user"
25 "runtime"
26 "unsafe"
27
28 "github.com/pkg/errors"
29 "golang.org/x/sys/unix"
30
31 "fmt"
32 "log"
33
34 "github.com/google/fscrypt/crypto"
35 "github.com/google/fscrypt/security"
36 "github.com/google/fscrypt/util"
37 )
38
39 // ErrAccessUserKeyring indicates that a user's keyring cannot be
40 // accessed.
41 type ErrAccessUserKeyring struct {
42 TargetUser *user.User
43 UnderlyingError error
44 }
45
46 func (err *ErrAccessUserKeyring) Error() string {
47 return fmt.Sprintf("could not access user keyring for %q: %s",
48 err.TargetUser.Username, err.UnderlyingError)
49 }
50
51 // ErrSessionUserKeyring indicates that a user's keyring is not linked
52 // into the session keyring.
53 type ErrSessionUserKeyring struct {
54 TargetUser *user.User
55 }
56
57 func (err *ErrSessionUserKeyring) Error() string {
58 return fmt.Sprintf("user keyring for %q is not linked into the session keyring",
59 err.TargetUser.Username)
60 }
61
62 // KeyType is always logon as required by filesystem encryption.
63 const KeyType = "logon"
64
65 // userAddKey puts the provided policy key into the user keyring for the
66 // specified user with the provided description, and type logon.
67 func userAddKey(key *crypto.Key, description string, targetUser *user.User) error {
68 runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
69 defer runtime.UnlockOSThread()
70
71 // Create our payload (containing an FscryptKey)
72 payload, err := crypto.NewBlankKey(int(unsafe.Sizeof(unix.FscryptKey{})))
73 if err != nil {
74 return err
75 }
76 defer payload.Wipe()
77
78 // Cast the payload to an FscryptKey so we can initialize the fields.
79 fscryptKey := (*unix.FscryptKey)(payload.UnsafePtr())
80 // Mode is ignored by the kernel
81 fscryptKey.Mode = 0
82 fscryptKey.Size = uint32(key.Len())
83 copy(fscryptKey.Raw[:], key.Data())
84
85 keyringID, err := UserKeyringID(targetUser, true)
86 if err != nil {
87 return err
88 }
89 keyID, err := unix.AddKey(KeyType, description, payload.Data(), keyringID)
90 log.Printf("KeyctlAddKey(%s, %s, <data>, %d) = %d, %v",
91 KeyType, description, keyringID, keyID, err)
92 if err != nil {
93 return errors.Wrapf(err,
94 "error adding key with description %s to user keyring for %q",
95 description, targetUser.Username)
96 }
97 return nil
98 }
99
100 // userRemoveKey tries to remove a policy key from the user keyring with the
101 // provided description. An error is returned if the key does not exist.
102 func userRemoveKey(description string, targetUser *user.User) error {
103 runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
104 defer runtime.UnlockOSThread()
105
106 keyID, keyringID, err := userFindKey(description, targetUser)
107 if err != nil {
108 return ErrKeyNotPresent
109 }
110
111 _, err = unix.KeyctlInt(unix.KEYCTL_UNLINK, keyID, keyringID, 0, 0)
112 log.Printf("KeyctlUnlink(%d, %d) = %v", keyID, keyringID, err)
113 if err != nil {
114 return errors.Wrapf(err,
115 "error removing key with description %s from user keyring for %q",
116 description, targetUser.Username)
117 }
118 return nil
119 }
120
121 // userFindKey tries to locate a key with the provided description in the user
122 // keyring for the target user. The key ID and keyring ID are returned if we can
123 // find the key. An error is returned if the key does not exist.
124 func userFindKey(description string, targetUser *user.User) (int, int, error) {
125 runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
126 defer runtime.UnlockOSThread()
127
128 keyringID, err := UserKeyringID(targetUser, false)
129 if err != nil {
130 return 0, 0, err
131 }
132
133 keyID, err := unix.KeyctlSearch(keyringID, KeyType, description, 0)
134 log.Printf("KeyctlSearch(%d, %s, %s) = %d, %v", keyringID, KeyType, description, keyID, err)
135 if err != nil {
136 return 0, 0, errors.Wrapf(err,
137 "error searching for key %s in user keyring for %q",
138 description, targetUser.Username)
139 }
140 return keyID, keyringID, err
141 }
142
143 // UserKeyringID returns the key id of the target user's user keyring. We also
144 // ensure that the keyring will be accessible by linking it into the thread
145 // keyring and linking it into the root user keyring (permissions allowing). If
146 // checkSession is true, an error is returned if a normal user requests their
147 // user keyring, but it is not in the current session keyring.
148 func UserKeyringID(targetUser *user.User, checkSession bool) (int, error) {
149 runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
150 defer runtime.UnlockOSThread()
151
152 uid := util.AtoiOrPanic(targetUser.Uid)
153 targetKeyring, err := userKeyringIDLookup(uid)
154 if err != nil {
155 return 0, &ErrAccessUserKeyring{targetUser, err}
156 }
157
158 if !util.IsUserRoot() {
159 // Make sure the returned keyring will be accessible by checking
160 // that it is in the session keyring.
161 if checkSession && !isUserKeyringInSession(uid) {
162 return 0, &ErrSessionUserKeyring{targetUser}
163 }
164 return targetKeyring, nil
165 }
166
167 // Make sure the returned keyring will be accessible by linking it into
168 // the root user's user keyring (which will not be garbage collected).
169 rootKeyring, err := userKeyringIDLookup(0)
170 if err != nil {
171 return 0, errors.Wrapf(err, "error looking up root's user keyring")
172 }
173
174 if rootKeyring != targetKeyring {
175 if err = keyringLink(targetKeyring, rootKeyring); err != nil {
176 return 0, errors.Wrapf(err,
177 "error linking user keyring for %q into root's user keyring",
178 targetUser.Username)
179 }
180 }
181 return targetKeyring, nil
182 }
183
184 func userKeyringIDLookup(uid int) (keyringID int, err error) {
185
186 // Our goals here are to:
187 // - Find the user keyring (for the provided uid)
188 // - Link it into the current thread keyring (so we can use it)
189 // - Make no permanent changes to the process privileges
190 // Complicating this are the facts that:
191 // - The value of KEY_SPEC_USER_KEYRING is determined by the ruid
192 // - Keyring linking permissions use the euid
193 // So we have to change both the ruid and euid to make this work,
194 // setting the suid to 0 so that we can later switch back.
195 ruid, euid, suid := security.GetUids()
196 if ruid != uid || euid != uid {
197 if err = security.SetUids(uid, uid, 0); err != nil {
198 return
199 }
200 defer func() {
201 resetErr := security.SetUids(ruid, euid, suid)
202 if resetErr != nil {
203 err = resetErr
204 }
205 }()
206 }
207
208 // We get the value of KEY_SPEC_USER_KEYRING. Note that this will also
209 // trigger the creation of the uid keyring if it does not yet exist.
210 keyringID, err = unix.KeyctlGetKeyringID(unix.KEY_SPEC_USER_KEYRING, true)
211 log.Printf("keyringID(_uid.%d) = %d, %v", uid, keyringID, err)
212 if err != nil {
213 return 0, err
214 }
215
216 // We still want to use this keyring after our privileges are reset. So
217 // we link it into the thread keyring, preventing a loss of access.
218 //
219 // We must be under LockOSThread() for this to work reliably. Note that
220 // we can't just use the process keyring, since it doesn't work reliably
221 // in Go programs, due to the Go runtime creating threads before the
222 // program starts and has a chance to create the process keyring.
223 if err = keyringLink(keyringID, unix.KEY_SPEC_THREAD_KEYRING); err != nil {
224 return 0, err
225 }
226
227 return keyringID, nil
228 }
229
230 // isUserKeyringInSession tells us if the user's uid keyring is in the current
231 // session keyring.
232 func isUserKeyringInSession(uid int) bool {
233 // We cannot use unix.KEY_SPEC_SESSION_KEYRING directly as that might
234 // create a session keyring if one does not exist.
235 sessionKeyring, err := unix.KeyctlGetKeyringID(unix.KEY_SPEC_SESSION_KEYRING, false)
236 log.Printf("keyringID(session) = %d, %v", sessionKeyring, err)
237 if err != nil {
238 return false
239 }
240
241 description := fmt.Sprintf("_uid.%d", uid)
242 id, err := unix.KeyctlSearch(sessionKeyring, "keyring", description, 0)
243 log.Printf("KeyctlSearch(%d, keyring, %s) = %d, %v", sessionKeyring, description, id, err)
244 return err == nil
245 }
246
247 func keyringLink(keyID int, keyringID int) error {
248 _, err := unix.KeyctlInt(unix.KEYCTL_LINK, keyID, keyringID, 0, 0)
249 log.Printf("KeyctlLink(%d, %d) = %v", keyID, keyringID, err)
250 return err
251 }