aboutsummaryrefslogtreecommitdiff
path: root/cmd/fscrypt/keys.go
blob: ec02148b2ec36254fb48e330d8aeea94f99dac09 (plain)
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
/*
 * keys.go - Functions and readers for getting passphrases and raw keys via
 * the command line. Includes ability to hide the entered passphrase, or use a
 * raw key as input.
 *
 * Copyright 2017 Google Inc.
 * Author: Joe Richey (joerichey@google.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/pkg/errors"
	"golang.org/x/crypto/ssh/terminal"

	"github.com/google/fscrypt/actions"
	"github.com/google/fscrypt/cmd"
	"github.com/google/fscrypt/crypto"
	"github.com/google/fscrypt/metadata"
	"github.com/google/fscrypt/pam"
	"github.com/google/fscrypt/util"
)

// The file descriptor for standard input
const stdinFd = 0

// actions.KeyFuncs for getting or creating cryptographic keys
var (
	// getting an existing key
	existingKeyFn = makeKeyFunc(true, false, "")
	// getting an existing key when changing passphrases
	oldExistingKeyFn = makeKeyFunc(true, false, "old ")
	// creating a new key
	createKeyFn = makeKeyFunc(false, true, "")
	// creating a new key when changing passphrases
	newCreateKeyFn = makeKeyFunc(false, true, "new ")
)

// passphraseReader is an io.Reader intended for terminal passphrase input. The
// struct is empty as the reader needs to maintain no internal state.
type passphraseReader struct{}

// Read gets input from the terminal until a newline is encountered. This read
// should be called with the maximum buffer size for the passphrase.
func (p passphraseReader) Read(buf []byte) (int, error) {
	// We read one byte at a time to handle backspaces
	position := 0
	for {
		if position == len(buf) {
			return position, ErrMaxPassphrase
		}
		if _, err := io.ReadFull(os.Stdin, buf[position:position+1]); err != nil {
			return position, err
		}
		switch buf[position] {
		case '\r', '\n':
			return position, io.EOF
		case 3, 4:
			return position, cmd.ErrCanceled
		case 8, 127:
			if position > 0 {
				position--
			}
		default:
			position++
		}
	}
}

// getPassphraseKey puts the terminal into raw mode for the entry of the user's
// passphrase into a key. If we are not reading from a terminal, just read into
// the passphrase into the key normally.
func getPassphraseKey(prompt string) (*crypto.Key, error) {
	fmt.Fprint(cmd.Output, prompt)

	// Only disable echo if stdin is actually a terminal.
	if terminal.IsTerminal(stdinFd) {
		state, err := terminal.MakeRaw(stdinFd)
		if err != nil {
			return nil, err
		}
		defer func() {
			terminal.Restore(stdinFd, state)
			fmt.Println() // To align input
		}()
	}

	return crypto.NewKeyFromReader(passphraseReader{})
}

// makeKeyFunc creates an actions.KeyFunc. This function customizes the KeyFunc
// to whether or not it supports retrying, whether it confirms the passphrase,
// and custom prefix for printing (if any).
func makeKeyFunc(supportRetry, shouldConfirm bool, prefix string) actions.KeyFunc {
	return func(info actions.ProtectorInfo, retry bool) (*crypto.Key, error) {
		log.Printf("KeyFunc(%s, %v)", formatInfo(info), retry)
		if retry {
			if !supportRetry {
				panic("this KeyFunc does not support retrying")
			}
			// Don't retry for non-interactive sessions
			if cmd.QuietFlag.Value {
				return nil, ErrWrongKey
			}
			fmt.Println("Incorrect Passphrase")
		}

		switch info.Source() {
		case metadata.SourceType_pam_passphrase:
			username := util.GetUser(int(info.UID())).Username
			prompt := fmt.Sprintf("Enter %s%s: ", prefix, formatInfo(info))
			key, err := getPassphraseKey(prompt)
			if err != nil {
				return nil, err
			}

			// To confirm, check that the passphrase is the user's
			// login passphrase.
			if shouldConfirm {
				err = pam.IsUserLoginToken(username, key, cmd.QuietFlag.Value)
				if err != nil {
					key.Wipe()
					return nil, err
				}
			}
			return key, nil

		case metadata.SourceType_custom_passphrase:
			prompt := fmt.Sprintf("Enter %s%s: ", prefix, formatInfo(info))
			key, err := getPassphraseKey(prompt)
			if err != nil {
				return nil, err
			}

			// To confirm, make sure the user types the same
			// passphrase in again.
			if shouldConfirm && !cmd.QuietFlag.Value {
				key2, err := getPassphraseKey("Confirm passphrase: ")
				if err != nil {
					key.Wipe()
					return nil, err
				}
				defer key2.Wipe()

				if !key.Equals(key2) {
					key.Wipe()
					return nil, ErrPassphraseMismatch
				}
			}
			return key, nil

		case metadata.SourceType_raw_key:
			// Only use prefixes with passphrase protectors.
			if prefix != "" {
				return nil, ErrNotPassphrase
			}
			prompt := fmt.Sprintf("Enter path to %s: ", formatInfo(info))
			// Raw keys use a file containing the key data.
			file, err := promptForKeyFile(prompt)
			if err != nil {
				return nil, err
			}
			defer file.Close()

			fileInfo, err := file.Stat()
			if err != nil {
				return nil, err
			}

			if fileInfo.Size() != metadata.InternalKeyLen {
				return nil, errors.Wrap(ErrKeyFileLength, file.Name())
			}
			return crypto.NewFixedLengthKeyFromReader(file, metadata.InternalKeyLen)

		default:
			return nil, ErrInvalidSource
		}
	}
}