Debian Codegraph @

pam_fscrypt/run_fscrypt.go

raw
1 /*
2 * run_fscrypt.go - Helpers for running functions in the PAM module.
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 "io"
34 "log"
35 "log/syslog"
36 "os"
37 "os/user"
38 "path/filepath"
39 "runtime/debug"
40 "unsafe"
41
42 "golang.org/x/sys/unix"
43
44 "github.com/pkg/errors"
45
46 "github.com/google/fscrypt/actions"
47 "github.com/google/fscrypt/filesystem"
48 "github.com/google/fscrypt/metadata"
49 "github.com/google/fscrypt/pam"
50 "github.com/google/fscrypt/util"
51 )
52
53 const (
54 // countDirectory is in a tmpfs filesystem so it will reset on reboot.
55 countDirectory = "/run/fscrypt"
56 // count files should only be readable and writable by root
57 countDirectoryPermissions = 0700
58 countFilePermissions = 0600
59 countFileFormat = "%d\n"
60 // uidMin is the first UID that can be used for a regular user (as
61 // opposed to a system user or root). This value is fairly standard
62 // across Linux distros, but it can be adjusted if needed.
63 uidMin = 1000
64 )
65
66 // PamFunc is used to define the various actions in the PAM module.
67 type PamFunc struct {
68 // Name of the function being executed
69 name string
70 // Go implementation of this function
71 impl func(handle *pam.Handle, args map[string]bool) error
72 }
73
74 // isSystemUser checks if a user is a system user. pam_fscrypt should never
75 // need to do anything for system users since they should never have login
76 // protectors. Therefore, we detect them early to avoid wasting resources.
77 func isSystemUser(user *user.User) bool {
78 uid := util.AtoiOrPanic(user.Uid)
79 return uid < uidMin && uid != 0
80 }
81
82 // Run is used to convert between the Go functions and exported C funcs.
83 func (f *PamFunc) Run(pamh unsafe.Pointer, argc C.int, argv **C.char) (ret C.int) {
84 args := parseArgs(argc, argv)
85 errorWriter := setupLogging(args)
86
87 // Log any panics to the errorWriter
88 defer func() {
89 if r := recover(); r != nil {
90 ret = C.PAM_SERVICE_ERR
91 fmt.Fprintf(errorWriter,
92 "%s(%v) panicked: %s\nPlease open a bug.\n%s",
93 f.name, args, r, debug.Stack())
94 }
95 }()
96
97 log.Printf("%s(%v) starting", f.name, args)
98 handle, err := pam.NewHandle(pamh)
99 if err == nil {
100 if isSystemUser(handle.PamUser) {
101 log.Printf("invoked for system user %q (%s), doing nothing",
102 handle.PamUser.Username, handle.PamUser.Uid)
103 err = nil
104 } else {
105 err = f.impl(handle, args)
106 }
107 }
108 if err != nil {
109 fmt.Fprintf(errorWriter, "%s(%v) failed: %s", f.name, args, err)
110 return C.PAM_SERVICE_ERR
111 }
112 log.Printf("%s(%v) succeeded", f.name, args)
113 return C.PAM_SUCCESS
114 }
115
116 // parseArgs takes a list of C arguments into a PAM function and returns a map
117 // where a key has a value of true if it appears in the argument list.
118 func parseArgs(argc C.int, argv **C.char) map[string]bool {
119 args := make(map[string]bool)
120 if argc == 0 || argv == nil {
121 return args
122 }
123 for _, cString := range util.PointerSlice(unsafe.Pointer(argv))[:argc] {
124 args[C.GoString((*C.char)(cString))] = true
125 }
126 return args
127 }
128
129 // setupLogging directs turns off standard logging (or redirects it to debug
130 // syslog if the "debug" argument is passed) and returns a writer to the error
131 // syslog.
132 func setupLogging(args map[string]bool) io.Writer {
133 log.SetFlags(0) // Syslog already includes time data itself
134 log.SetOutput(io.Discard)
135 if args[debugFlag] {
136 debugWriter, err := syslog.New(syslog.LOG_DEBUG, moduleName)
137 if err == nil {
138 log.SetOutput(debugWriter)
139 }
140 }
141
142 errorWriter, err := syslog.New(syslog.LOG_ERR, moduleName)
143 if err != nil {
144 return io.Discard
145 }
146 return errorWriter
147 }
148
149 // loginProtector returns the login protector corresponding to the PAM_USER if
150 // one exists. This protector descriptor (if found) will be cached in the pam
151 // data, under descriptorLabel.
152 func loginProtector(handle *pam.Handle) (*actions.Protector, error) {
153 ctx, err := actions.NewContextFromMountpoint(actions.LoginProtectorMountpoint,
154 handle.PamUser)
155 if err != nil {
156 return nil, err
157 }
158 // Ensure that pam_fscrypt only processes metadata files owned by the
159 // user or root, even if the user is root themselves. (Normally, when
160 // fscrypt is run as root it is allowed to process all metadata files.
161 // This implements stricter behavior for pam_fscrypt.)
162 if !ctx.Config.GetAllowCrossUserMetadata() {
163 ctx.TrustedUser = handle.PamUser
164 }
165
166 // Find the user's PAM protector.
167 options, err := ctx.ProtectorOptions()
168 if err != nil {
169 return nil, err
170 }
171 uid := int64(util.AtoiOrPanic(handle.PamUser.Uid))
172 for _, option := range options {
173 if option.Source() == metadata.SourceType_pam_passphrase && option.UID() == uid {
174 return actions.GetProtectorFromOption(ctx, option)
175 }
176 }
177 return nil, errors.Errorf("no PAM protector for UID=%d on %q", uid, ctx.Mount.Path)
178 }
179
180 // policiesUsingProtector searches all the mountpoints for any policies
181 // protected with the specified protector. If provisioned is true, then only
182 // policies provisioned by the target user are returned; otherwise only policies
183 // *not* provisioned by the target user are returned.
184 func policiesUsingProtector(protector *actions.Protector, provisioned bool) []*actions.Policy {
185 mounts, err := filesystem.AllFilesystems()
186 if err != nil {
187 log.Print(err)
188 return nil
189 }
190
191 var policies []*actions.Policy
192 for _, mount := range mounts {
193 // Skip mountpoints that do not use the protector.
194 if _, _, err := mount.GetProtector(protector.Descriptor(),
195 protector.Context.TrustedUser); err != nil {
196 if _, ok := err.(*filesystem.ErrNotSetup); !ok {
197 log.Print(err)
198 }
199 continue
200 }
201 policyDescriptors, err := mount.ListPolicies(protector.Context.TrustedUser)
202 if err != nil {
203 log.Printf("listing policies: %s", err)
204 continue
205 }
206
207 // Clone context but modify the mountpoint
208 ctx := *protector.Context
209 ctx.Mount = mount
210 for _, policyDescriptor := range policyDescriptors {
211 policy, err := actions.GetPolicy(&ctx, policyDescriptor)
212 if err != nil {
213 log.Printf("reading policy: %s", err)
214 continue
215 }
216
217 if !policy.UsesProtector(protector) {
218 continue
219 }
220 if provisioned {
221 if !policy.IsProvisionedByTargetUser() {
222 log.Printf("policy %s not provisioned by %v",
223 policy.Descriptor(), ctx.TargetUser.Username)
224 continue
225 }
226 } else {
227 if policy.IsProvisionedByTargetUser() {
228 log.Printf("policy %s already provisioned by %v",
229 policy.Descriptor(), ctx.TargetUser.Username)
230 continue
231 }
232 }
233 policies = append(policies, policy)
234 }
235 }
236 return policies
237 }
238
239 // AdjustCount changes the session count for the pam user by the specified
240 // amount. If the count file does not exist, create it as if it had a count of
241 // zero. If the adjustment would bring the count below zero, the count is set to
242 // zero. The value of the new count is returned. Requires root privileges.
243 func AdjustCount(handle *pam.Handle, delta int) (int, error) {
244 // Make sure the directory exists
245 if err := os.MkdirAll(countDirectory, countDirectoryPermissions); err != nil {
246 return 0, err
247 }
248
249 path := filepath.Join(countDirectory, handle.PamUser.Uid+".count")
250 file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, countFilePermissions)
251 if err != nil {
252 return 0, err
253 }
254 if err = unix.Flock(int(file.Fd()), unix.LOCK_EX); err != nil {
255 return 0, err
256 }
257 defer file.Close()
258
259 newCount := util.MaxInt(getCount(file)+delta, 0)
260 if _, err = file.Seek(0, io.SeekStart); err != nil {
261 return 0, err
262 }
263 if _, err = fmt.Fprintf(file, countFileFormat, newCount); err != nil {
264 return 0, err
265 }
266
267 log.Printf("Session count for UID=%s updated to %d", handle.PamUser.Uid, newCount)
268 return newCount, nil
269 }
270
271 // Returns the count in the file (or zero if the count cannot be read).
272 func getCount(file *os.File) int {
273 var count int
274 if _, err := fmt.Fscanf(file, countFileFormat, &count); err != nil {
275 return 0
276 }
277 return count
278 }