Debian Codegraph @

actions/config.go

raw
1 /*
2 * config.go - Actions for creating a new config file, which includes new
3 * hashing costs and the config file's location.
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 actions
22
23 import (
24 "bytes"
25 "fmt"
26 "log"
27 "math"
28 "os"
29 "runtime"
30 "time"
31
32 "golang.org/x/sys/unix"
33 "google.golang.org/protobuf/proto"
34
35 "github.com/google/fscrypt/cgroup"
36 "github.com/google/fscrypt/crypto"
37 "github.com/google/fscrypt/filesystem"
38 "github.com/google/fscrypt/metadata"
39 "github.com/google/fscrypt/util"
40 )
41
42 // ConfigFileLocation is the location of fscrypt's global settings. This can be
43 // overridden by the user of this package.
44 var ConfigFileLocation = "/etc/fscrypt.conf"
45
46 // ErrBadConfig is an internal error that indicates that the config struct is invalid.
47 type ErrBadConfig struct {
48 Config *metadata.Config
49 UnderlyingError error
50 }
51
52 func (err *ErrBadConfig) Error() string {
53 return fmt.Sprintf(`internal error: config is invalid: %s
54
55 The invalid config is %s`, err.UnderlyingError, err.Config)
56 }
57
58 // ErrBadConfigFile indicates that the config file is invalid.
59 type ErrBadConfigFile struct {
60 Path string
61 UnderlyingError error
62 }
63
64 func (err *ErrBadConfigFile) Error() string {
65 return fmt.Sprintf("%q is invalid: %s", err.Path, err.UnderlyingError)
66 }
67
68 // ErrConfigFileExists indicates that the config file already exists.
69 type ErrConfigFileExists struct {
70 Path string
71 }
72
73 func (err *ErrConfigFileExists) Error() string {
74 return fmt.Sprintf("%q already exists", err.Path)
75 }
76
77 // ErrNoConfigFile indicates that the config file doesn't exist.
78 type ErrNoConfigFile struct {
79 Path string
80 }
81
82 func (err *ErrNoConfigFile) Error() string {
83 return fmt.Sprintf("%q doesn't exist", err.Path)
84 }
85
86 const (
87 // Permissions of the config file (global readable)
88 configPermissions = 0644
89 // Config file should be created for writing and not already exist
90 createFlags = os.O_CREATE | os.O_WRONLY | os.O_EXCL
91 // 128 MiB is a large enough amount of memory to make the password hash
92 // very difficult to brute force on specialized hardware, but small
93 // enough to work on most GNU/Linux systems.
94 maxMemoryBytes = 128 * 1024 * 1024
95 )
96
97 var (
98 timingPassphrase = []byte("I am a fake passphrase")
99 timingSalt = bytes.Repeat([]byte{42}, metadata.SaltLen)
100 )
101
102 // CreateConfigFile creates a new config file at the appropriate location with
103 // the appropriate hashing costs and encryption parameters. The hashing will be
104 // configured to take as long as the specified time target. In addition, the
105 // version of encryption policy to use may be overridden from the default of v1.
106 func CreateConfigFile(target time.Duration, policyVersion int64) error {
107 // Create the config file before computing the hashing costs, so we fail
108 // immediately if the program has insufficient permissions.
109 configFile, err := filesystem.OpenFileOverridingUmask(ConfigFileLocation,
110 createFlags, configPermissions)
111 switch {
112 case os.IsExist(err):
113 return &ErrConfigFileExists{ConfigFileLocation}
114 case err != nil:
115 return err
116 }
117 defer configFile.Close()
118
119 config := &metadata.Config{
120 Source: metadata.DefaultSource,
121 Options: metadata.DefaultOptions,
122 }
123
124 if policyVersion != 0 {
125 config.Options.PolicyVersion = policyVersion
126 }
127
128 if config.HashCosts, err = getHashingCosts(target); err != nil {
129 return err
130 }
131
132 log.Printf("Creating config at %q with %v\n", ConfigFileLocation, config)
133 return metadata.WriteConfig(config, configFile)
134 }
135
136 // getConfig returns the current configuration struct. Any fields not specified
137 // in the config file use the system defaults. An error is returned if the
138 // config file hasn't been setup with CreateConfigFile yet or the config
139 // contains invalid data.
140 func getConfig() (*metadata.Config, error) {
141 configFile, err := os.Open(ConfigFileLocation)
142 switch {
143 case os.IsNotExist(err):
144 return nil, &ErrNoConfigFile{ConfigFileLocation}
145 case err != nil:
146 return nil, err
147 }
148 defer configFile.Close()
149
150 log.Printf("Reading config from %q\n", ConfigFileLocation)
151 config, err := metadata.ReadConfig(configFile)
152 if err != nil {
153 return nil, &ErrBadConfigFile{ConfigFileLocation, err}
154 }
155
156 // Use system defaults if not specified
157 if config.Source == metadata.SourceType_default {
158 config.Source = metadata.DefaultSource
159 log.Printf("Falling back to source of %q", config.Source.String())
160 }
161 if config.Options.Padding == 0 {
162 config.Options.Padding = metadata.DefaultOptions.Padding
163 log.Printf("Falling back to padding of %d", config.Options.Padding)
164 }
165 if config.Options.Contents == metadata.EncryptionOptions_default {
166 config.Options.Contents = metadata.DefaultOptions.Contents
167 log.Printf("Falling back to contents mode of %q", config.Options.Contents)
168 }
169 if config.Options.Filenames == metadata.EncryptionOptions_default {
170 config.Options.Filenames = metadata.DefaultOptions.Filenames
171 log.Printf("Falling back to filenames mode of %q", config.Options.Filenames)
172 }
173 if config.Options.PolicyVersion == 0 {
174 config.Options.PolicyVersion = metadata.DefaultOptions.PolicyVersion
175 log.Printf("Falling back to policy version of %d", config.Options.PolicyVersion)
176 }
177
178 if err := config.CheckValidity(); err != nil {
179 return nil, &ErrBadConfigFile{ConfigFileLocation, err}
180 }
181
182 return config, nil
183 }
184
185 // getHashingCosts returns hashing costs so that hashing a password will take
186 // approximately the target time. This is done using the total amount of RAM,
187 // the number of CPUs present, and by running the passphrase hash many times.
188 func getHashingCosts(target time.Duration) (*metadata.HashingCosts, error) {
189 log.Printf("Finding hashing costs that take %v\n", target)
190
191 // Start out with the minimal possible costs that use all the available
192 // CPUs, respecting cgroup limits when present.
193 parallelism := int64(effectiveCPUCount())
194 // golang.org/x/crypto/argon2 only supports parallelism up to 255.
195 // For compatibility, don't use more than that amount.
196 if parallelism > metadata.MaxParallelism {
197 parallelism = metadata.MaxParallelism
198 }
199 costs := &metadata.HashingCosts{
200 Time: 1,
201 Memory: 8 * parallelism,
202 Parallelism: parallelism,
203 TruncationFixed: true,
204 }
205
206 // If even the minimal costs are not fast enough, just return the
207 // minimal costs and log a warning.
208 t, err := timeHashingCosts(costs)
209 if err != nil {
210 return nil, err
211 }
212 log.Printf("Min Costs={%v}\t-> %v\n", costs, t)
213
214 if t > target {
215 log.Printf("time exceeded the target of %v.\n", target)
216 return costs, nil
217 }
218
219 // Now we start doubling the costs until we reach the target.
220 memoryKiBLimit := memoryBytesLimit() / 1024
221 for {
222 // Store a copy of the previous costs
223 costsPrev := proto.Clone(costs).(*metadata.HashingCosts)
224 tPrev := t
225
226 // Double the memory up to the max, then double the time.
227 if costs.Memory < memoryKiBLimit {
228 costs.Memory = util.MinInt64(2*costs.Memory, memoryKiBLimit)
229 } else {
230 costs.Time *= 2
231 }
232
233 // If our hashing failed, return the last good set of costs.
234 if t, err = timeHashingCosts(costs); err != nil {
235 log.Printf("Hashing with costs={%v} failed: %v\n", costs, err)
236 return costsPrev, nil
237 }
238 log.Printf("Costs={%v}\t-> %v\n", costs, t)
239
240 // If we have reached the target time, we return a set of costs
241 // based on the linear interpolation between the last two times.
242 if t >= target {
243 f := float64(target-tPrev) / float64(t-tPrev)
244 return &metadata.HashingCosts{
245 Time: betweenCosts(costsPrev.Time, costs.Time, f),
246 Memory: betweenCosts(costsPrev.Memory, costs.Memory, f),
247 Parallelism: costs.Parallelism,
248 TruncationFixed: costs.TruncationFixed,
249 }, nil
250 }
251 }
252 }
253
254 // effectiveCPUCount returns the number of CPUs available to this process,
255 // taking cgroup limits into account. Falls back to runtime.NumCPU() when
256 // cgroup information is unavailable.
257 func effectiveCPUCount() int {
258 cg, err := cgroup.New()
259 if err != nil {
260 return runtime.NumCPU()
261 }
262 quota, err := cg.CPUQuota()
263 if err != nil || quota <= 0 {
264 return runtime.NumCPU()
265 }
266 cpus := int(math.Ceil(quota))
267 return min(cpus, runtime.NumCPU())
268 }
269
270 // memoryBytesLimit returns the maximum amount of memory we will use for
271 // passphrase hashing. This will never be more than a reasonable maximum (for
272 // compatibility) or an 8th the available RAM (considering cgroup limits).
273 func memoryBytesLimit() int64 {
274 // The sysinfo syscall only fails if given a bad address
275 var info unix.Sysinfo_t
276 err := unix.Sysinfo(&info)
277 util.NeverError(err)
278
279 totalRAMBytes := int64(info.Totalram)
280 if cg, err := cgroup.New(); err == nil {
281 if cgroupMem, err := cg.MemoryLimit(); err == nil && cgroupMem > 0 {
282 totalRAMBytes = util.MinInt64(totalRAMBytes, cgroupMem)
283 }
284 }
285 return util.MinInt64(totalRAMBytes/8, maxMemoryBytes)
286 }
287
288 // betweenCosts returns a cost between a and b. Specifically, it returns the
289 // floor of a + f*(b-a). This way, f=0 returns a and f=1 returns b.
290 func betweenCosts(a, b int64, f float64) int64 {
291 return a + int64(f*float64(b-a))
292 }
293
294 // timeHashingCosts runs the passphrase hash with the specified costs and
295 // returns the time it takes to hash the passphrase.
296 func timeHashingCosts(costs *metadata.HashingCosts) (time.Duration, error) {
297 passphrase, err := crypto.NewKeyFromReader(bytes.NewReader(timingPassphrase))
298 if err != nil {
299 return 0, err
300 }
301 defer passphrase.Wipe()
302
303 // Be sure to measure CPU time, not wall time (time.Now)
304 begin := cpuTimeInNanoseconds()
305 hash, err := crypto.PassphraseHash(passphrase, timingSalt, costs)
306 if err == nil {
307 hash.Wipe()
308 }
309 end := cpuTimeInNanoseconds()
310
311 // This uses a lot of memory, run the garbage collector
312 runtime.GC()
313
314 return time.Duration((end - begin) / costs.Parallelism), nil
315 }
316
317 // cpuTimeInNanoseconds returns the nanosecond count based on the process's CPU usage.
318 // This number has no absolute meaning, only relative meaning to other calls.
319 func cpuTimeInNanoseconds() int64 {
320 var ts unix.Timespec
321 err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts)
322 // ClockGettime fails if given a bad address or on a VERY old system.
323 util.NeverError(err)
324 return unix.TimespecToNsec(ts)
325 }