Debian Codegraph @

pam_fscrypt/pam_fscrypt.go

raw
1 /*
2 * pam_fscrypt.go - Checks the validity of a login token key against PAM.
3 *
4 * Copyright 2017 Google Inc.
5 * Author: Joe Richey ([email protected])
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8 * use this file except in compliance with the License. You may obtain a copy of
9 * the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 * License for the specific language governing permissions and limitations under
17 * the License.
18 */
19
20 package main
21
22 /*
23 #cgo LDFLAGS: -lpam -fPIC
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include <security/pam_appl.h>
29 */
30 import "C"
31 import (
32 "fmt"
33 "log"
34 "log/syslog"
35 "os"
36 "strconv"
37 "unsafe"
38
39 "github.com/pkg/errors"
40
41 "github.com/google/fscrypt/actions"
42 "github.com/google/fscrypt/crypto"
43 "github.com/google/fscrypt/keyring"
44 "github.com/google/fscrypt/pam"
45 "github.com/google/fscrypt/security"
46 )
47
48 const (
49 moduleName = "pam_fscrypt"
50 // authtokLabel tags the AUTHTOK in the PAM data.
51 authtokLabel = "fscrypt_authtok"
52 // pidLabel tags the pid in the PAM data.
53 pidLabel = "fscrypt_pid"
54 // These flags are used to toggle behavior of the PAM module.
55 debugFlag = "debug"
56
57 // This option is accepted for compatibility with existing config files,
58 // but now we lock policies by default and this option is a no-op.
59 lockPoliciesFlag = "lock_policies"
60
61 // Only unlock directories, don't lock them.
62 unlockOnlyFlag = "unlock_only"
63
64 // This option is accepted for compatibility with existing config files,
65 // but it no longer does anything. pam_fscrypt now drops caches if and
66 // only if it is needed. (Usually it is not needed anymore, as the
67 // FS_IOC_REMOVE_ENCRYPTION_KEY ioctl handles this automatically.)
68 dropCachesFlag = "drop_caches"
69 )
70
71 var (
72 // PamFuncs for our 4 provided methods
73 authenticateFunc = PamFunc{"Authenticate", Authenticate}
74 openSessionFunc = PamFunc{"OpenSession", OpenSession}
75 closeSessionFunc = PamFunc{"CloseSession", CloseSession}
76 chauthtokFunc = PamFunc{"Chauthtok", Chauthtok}
77 )
78
79 // Authenticate copies the AUTHTOK (if necessary) into the PAM data so it can be
80 // used in pam_sm_open_session.
81 func Authenticate(handle *pam.Handle, _ map[string]bool) error {
82 if err := handle.StartAsPamUser(); err != nil {
83 return err
84 }
85 defer handle.StopAsPamUser()
86
87 // Save the PID in the PAM data so that the Session hook can try to
88 // detect the unsupported situation where the process was forked.
89 if err := handle.SetString(pidLabel, strconv.Itoa(os.Getpid())); err != nil {
90 return errors.Wrap(err, "could not save pid in PAM data")
91 }
92
93 // If this user doesn't have a login protector, no unlocking is needed.
94 if _, err := loginProtector(handle); err != nil {
95 log.Printf("no protector, no need for AUTHTOK: %s", err)
96 return nil
97 }
98
99 log.Print("copying AUTHTOK for use in the session open")
100 authtok, err := handle.GetItem(pam.Authtok)
101 if err != nil {
102 return errors.Wrap(err, "could not get AUTHTOK")
103 }
104 err = handle.SetSecret(authtokLabel, authtok)
105 return errors.Wrap(err, "could not set AUTHTOK data")
106 }
107
108 func beginProvisioningOp(handle *pam.Handle, policy *actions.Policy) error {
109 if policy.NeedsRootToProvision() {
110 return handle.StopAsPamUser()
111 }
112 return nil
113 }
114
115 func endProvisioningOp(handle *pam.Handle, policy *actions.Policy) error {
116 if policy.NeedsRootToProvision() {
117 return handle.StartAsPamUser()
118 }
119 return nil
120 }
121
122 // Set up the PAM user's keyring if needed by any encryption policies.
123 func setupUserKeyringIfNeeded(handle *pam.Handle, policies []*actions.Policy) error {
124 needed := false
125 for _, policy := range policies {
126 if policy.NeedsUserKeyring() {
127 needed = true
128 break
129 }
130 }
131 if !needed {
132 return nil
133 }
134 err := handle.StopAsPamUser()
135 if err != nil {
136 return err
137 }
138 _, err = keyring.UserKeyringID(handle.PamUser, true)
139 if err != nil {
140 log.Printf("Setting up keyrings in PAM: %v", err)
141 }
142 return handle.StartAsPamUser()
143 }
144
145 // The Go runtime doesn't support being forked, as it is multithreaded but
146 // fork() deletes all threads except one. Some programs, such as xrdp, misuse
147 // libpam by fork()-ing the process between pam_authenticate() and
148 // pam_open_session(). Try to detect such unsupported cases and bail out early
149 // rather than deadlocking the Go runtime, which would prevent the user from
150 // logging in entirely. This isn't guaranteed to work, as we are already
151 // running Go code here, so we may have already deadlocked. But in practice the
152 // deadlock doesn't occur until hashing the login passphrase is attempted.
153 func isUnsupportedFork(handle *pam.Handle) bool {
154 pidString, err := handle.GetString(pidLabel)
155 if err != nil {
156 return false
157 }
158 expectedPid, err := strconv.Atoi(pidString)
159 if err != nil {
160 log.Printf("%s parse error: %v", pidLabel, err)
161 return false
162 }
163 if os.Getpid() == expectedPid {
164 return false
165 }
166 handle.InfoMessage(fmt.Sprintf("%s couldn't automatically unlock directories, see syslog", moduleName))
167 if logger, err := syslog.New(syslog.LOG_WARNING, moduleName); err == nil {
168 fmt.Fprintf(logger,
169 "not unlocking directories because %s forked the process between authenticating the user and opening the session, which is incompatible with %s. See https://github.com/google/fscrypt/issues/350",
170 handle.GetServiceName(), moduleName)
171 logger.Close()
172 }
173 return true
174 }
175
176 // OpenSession provisions any policies protected with the login protector.
177 func OpenSession(handle *pam.Handle, _ map[string]bool) error {
178 // We will always clear the AUTHTOK data
179 defer handle.ClearData(authtokLabel)
180 // Increment the count as we add a session
181 if _, err := AdjustCount(handle, +1); err != nil {
182 return err
183 }
184
185 if err := handle.StartAsPamUser(); err != nil {
186 return err
187 }
188 defer handle.StopAsPamUser()
189
190 // If there are no polices for the login protector, no unlocking needed.
191 protector, err := loginProtector(handle)
192 if err != nil {
193 log.Printf("no protector to unlock: %s", err)
194 return nil
195 }
196 policies := policiesUsingProtector(protector, false)
197 if len(policies) == 0 {
198 log.Print("no policies to unlock")
199 return nil
200 }
201
202 if isUnsupportedFork(handle) {
203 return nil
204 }
205
206 if err = setupUserKeyringIfNeeded(handle, policies); err != nil {
207 return errors.Wrapf(err, "setting up user keyring")
208 }
209
210 log.Printf("unlocking %d policies protected with AUTHTOK", len(policies))
211 keyFn := func(_ actions.ProtectorInfo, retry bool) (*crypto.Key, error) {
212 if retry {
213 // Login passphrase and login protector have diverged.
214 // We could prompt the user for the old passphrase and
215 // rewrap, but we currently don't.
216 return nil, pam.ErrPassphrase
217 }
218
219 authtok, err := handle.GetSecret(authtokLabel)
220 if err != nil {
221 // pam_sm_authenticate was not run before the session is
222 // opened. This can happen when a user does something
223 // like "sudo su <user>". We could prompt for the
224 // login passphrase here, but we currently don't.
225 return nil, errors.Wrap(err, "AUTHTOK data missing")
226 }
227
228 return crypto.NewKeyFromCString(authtok)
229 }
230 if err := protector.Unlock(keyFn); err != nil {
231 return errors.Wrapf(err, "unlocking protector %s", protector.Descriptor())
232 }
233 defer protector.Lock()
234
235 // We don't stop provisioning polices on error, we try all of them.
236 for _, policy := range policies {
237 if err := policy.UnlockWithProtector(protector); err != nil {
238 log.Printf("unlocking policy %s: %s", policy.Descriptor(), err)
239 continue
240 }
241 defer policy.Lock()
242
243 if err := beginProvisioningOp(handle, policy); err != nil {
244 return err
245 }
246 provisionErr := policy.Provision()
247 if err := endProvisioningOp(handle, policy); err != nil {
248 return err
249 }
250 if provisionErr != nil {
251 log.Printf("provisioning policy %s: %s", policy.Descriptor(), provisionErr)
252 continue
253 }
254 log.Printf("policy %s provisioned by %v", policy.Descriptor(),
255 handle.PamUser.Username)
256 }
257 return nil
258 }
259
260 // CloseSession can deprovision all keys provisioned at the start of the
261 // session. It can also clear the cache so these changes take effect.
262 func CloseSession(handle *pam.Handle, args map[string]bool) error {
263 // Only do stuff on session close when we are the last session
264 if count, err := AdjustCount(handle, -1); err != nil || count != 0 {
265 log.Printf("count is %d and we are not locking", count)
266 return err
267 }
268
269 if args[lockPoliciesFlag] {
270 log.Print("ignoring deprecated 'lock_policies' option (now the default)")
271 }
272
273 if args[dropCachesFlag] {
274 log.Print("ignoring deprecated 'drop_caches' option (now auto-detected)")
275 }
276
277 // Don't automatically drop privileges, since we may need them to
278 // deprovision policies or to drop caches.
279
280 if !args[unlockOnlyFlag] {
281 log.Print("locking policies protected with login protector")
282 needDropCaches, errLock := lockLoginPolicies(handle)
283
284 var errCache error
285 if needDropCaches {
286 log.Print("dropping appropriate filesystem caches at session close")
287 errCache = security.DropFilesystemCache()
288 }
289 if errLock != nil {
290 return errLock
291 }
292 return errCache
293 }
294 return nil
295 }
296
297 // lockLoginPolicies deprovisions all policy keys that are protected by the
298 // user's login protector. It returns true if dropping filesystem caches will
299 // be needed afterwards to completely lock the relevant directories.
300 func lockLoginPolicies(handle *pam.Handle) (bool, error) {
301 needDropCaches := false
302
303 if err := handle.StartAsPamUser(); err != nil {
304 return needDropCaches, err
305 }
306 defer handle.StopAsPamUser()
307
308 // If there are no polices for the login protector, no locking needed.
309 protector, err := loginProtector(handle)
310 if err != nil {
311 log.Printf("nothing to lock: %s", err)
312 return needDropCaches, nil
313 }
314 policies := policiesUsingProtector(protector, true)
315 if len(policies) == 0 {
316 log.Print("no policies to lock")
317 return needDropCaches, nil
318 }
319
320 if err = setupUserKeyringIfNeeded(handle, policies); err != nil {
321 return needDropCaches, errors.Wrapf(err, "setting up user keyring")
322 }
323
324 // We will try to deprovision all of the policies.
325 for _, policy := range policies {
326 if policy.NeedsUserKeyring() {
327 needDropCaches = true
328 }
329 if err := beginProvisioningOp(handle, policy); err != nil {
330 return needDropCaches, err
331 }
332 deprovisionErr := policy.Deprovision(false)
333 if err := endProvisioningOp(handle, policy); err != nil {
334 return needDropCaches, err
335 }
336 if deprovisionErr != nil {
337 log.Printf("deprovisioning policy %s: %s", policy.Descriptor(), deprovisionErr)
338 continue
339 }
340 log.Printf("policy %s deprovisioned by %v", policy.Descriptor(), handle.PamUser.Username)
341 }
342 return needDropCaches, nil
343 }
344
345 var noOldAuthTokMessage string = `
346 pam_fscrypt: cannot update login protector for '%s' because old passphrase
347 was not given. This is expected when changing a user's passphrase as root.
348 You'll need to manually update the protector's passphrase using:
349
350 fscrypt metadata change-passphrase --protector=%s:%s
351 `
352
353 // Chauthtok rewraps the login protector when the passphrase changes.
354 func Chauthtok(handle *pam.Handle, _ map[string]bool) error {
355 if err := handle.StartAsPamUser(); err != nil {
356 return err
357 }
358 defer handle.StopAsPamUser()
359
360 protector, err := loginProtector(handle)
361 if err != nil {
362 log.Printf("no login protector to rewrap: %s", err)
363 return nil
364 }
365
366 oldKeyFn := func(_ actions.ProtectorInfo, retry bool) (*crypto.Key, error) {
367 if retry {
368 // If the OLDAUTHTOK disagrees with the login protector,
369 // we do nothing, as the protector will (probably) still
370 // disagree after the login passphrase changes.
371 return nil, pam.ErrPassphrase
372 }
373 authtok, err := handle.GetItem(pam.Oldauthtok)
374 if err != nil {
375 handle.InfoMessage(fmt.Sprintf(noOldAuthTokMessage,
376 handle.PamUser.Username,
377 protector.Context.Mount.Path, protector.Descriptor()))
378 return nil, errors.Wrap(err, "could not get OLDAUTHTOK")
379 }
380 return crypto.NewKeyFromCString(authtok)
381 }
382
383 newKeyFn := func(_ actions.ProtectorInfo, _ bool) (*crypto.Key, error) {
384 authtok, err := handle.GetItem(pam.Authtok)
385 if err != nil {
386 return nil, errors.Wrap(err, "could not get AUTHTOK")
387 }
388 return crypto.NewKeyFromCString(authtok)
389 }
390
391 log.Print("rewrapping login protector")
392 if err = protector.Unlock(oldKeyFn); err != nil {
393 return err
394 }
395 defer protector.Lock()
396
397 return protector.Rewrap(newKeyFn)
398 }
399
400 //export pam_sm_authenticate
401 func pam_sm_authenticate(pamh unsafe.Pointer, flags, argc C.int, argv **C.char) C.int {
402 return authenticateFunc.Run(pamh, argc, argv)
403 }
404
405 // pam_sm_setcred needed because we use pam_sm_authenticate.
406 //
407 //export pam_sm_setcred
408 func pam_sm_setcred(pamh unsafe.Pointer, flags, argc C.int, argv **C.char) C.int {
409 return C.PAM_SUCCESS
410 }
411
412 //export pam_sm_open_session
413 func pam_sm_open_session(pamh unsafe.Pointer, flags, argc C.int, argv **C.char) C.int {
414 return openSessionFunc.Run(pamh, argc, argv)
415 }
416
417 //export pam_sm_close_session
418 func pam_sm_close_session(pamh unsafe.Pointer, flags, argc C.int, argv **C.char) C.int {
419 return closeSessionFunc.Run(pamh, argc, argv)
420 }
421
422 //export pam_sm_chauthtok
423 func pam_sm_chauthtok(pamh unsafe.Pointer, flags, argc C.int, argv **C.char) C.int {
424 // Only do rewrapping if we have both AUTHTOKs and a login protector.
425 if pam.Flag(flags)&pam.PrelimCheck != 0 {
426 return C.PAM_SUCCESS
427 }
428 return chauthtokFunc.Run(pamh, argc, argv)
429 }
430
431 // main() is needed to make a shared library compile
432 func main() {}