File: password_store.go

package info (click to toggle)
gopass 1.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 336 kB
  • sloc: makefile: 30
file content (383 lines) | stat: -rw-r--r-- 10,202 bytes parent folder | download
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//    Copyright (C) 2017 Alexandre Viau <alexandre@alexandreviau.net>
//
//    This file is part of gopass.
//
//    gopass is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    gopass is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with gopass.  If not, see <http://www.gnu.org/licenses/>.

package gopass

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	gopassio "github.com/aviau/gopass/internal/io"
)

//PasswordStore represents a password store.
type PasswordStore struct {
	Path    string //path of the store
	GitDir  string //The path of the git directory
	GPGBin  string //The GPG binary to use
	GPGID   string //The GPG ID used to encrypt the passwords
	UsesGit bool   //Whether or not the store uses git
}

// NewPasswordStore returns a new password store.
func NewPasswordStore(storePath string) *PasswordStore {
	s := PasswordStore{}
	s.Path = storePath
	s.UsesGit = true
	s.GitDir = path.Join(s.Path, ".git")

	// Find the GPG bin
	which := exec.Command("which", "gpg2")
	if err := which.Run(); err == nil {
		s.GPGBin = "gpg2"
	} else {
		s.GPGBin = "gpg"
	}

	//Read the .gpg-id file
	gpgIDPath := path.Join(s.Path, ".gpg-id")
	content, _ := ioutil.ReadFile(gpgIDPath)
	s.GPGID = strings.TrimSpace(string(content))

	return &s
}

//Init creates a Password Store at the Path
func (store *PasswordStore) Init(gpgID string) error {
	//Check if the password path already exists
	fi, err := os.Stat(store.Path)
	if err == nil {
		//Path exists, but is it a directory?
		if fi.Mode().IsDir() == false {
			return fmt.Errorf(
				"could not create password store. Path \"%s\" already exists and it is not a directory",
				store.Path)
		}
	} else {
		//Error during os.Stat
		if os.IsNotExist(err) {
			//Path does not exist, create it
			if err := os.Mkdir(store.Path, 0700); err != nil {
				return err
			}
		} else {
			return err
		}
	}

	//Check if the .gpg-id file already exists.
	gpgIDFilePath := path.Join(store.Path, ".gpg-id")
	fi, err = os.Stat(gpgIDFilePath)
	if err == nil {
		//.gpg-id already exists
		return fmt.Errorf("there is already a .gpg-id file at \"%s\". Stopping init", gpgIDFilePath)
	}

	gpgIDFile, err := os.Create(path.Join(store.Path, ".gpg-id"))
	if err != nil {
		return err
	}
	defer gpgIDFile.Close()
	gpgIDFile.WriteString(gpgID + "\n")
	store.GPGID = gpgID

	if err := store.git("init"); err != nil {
		return err
	}

	return store.AddAndCommit("initial commit", ".gpg-id")
}

//InsertPassword inserts a new password or overwrites an existing one
func (store *PasswordStore) InsertPassword(pwname, pwtext string) error {
	containsPassword, passwordPath := store.ContainsPassword(pwname)

	//Check if password already exists
	var gitAction string
	if containsPassword {
		gitAction = "edited"
	} else {
		gitAction = "added"
	}

	gpg := exec.Command(
		store.GPGBin,
		"-e",
		"-r", store.GPGID,
		"--batch",
		"--use-agent",
		"--no-tty",
		"--yes",
		"-o", passwordPath)

	stdin, _ := gpg.StdinPipe()
	io.WriteString(stdin, pwtext)
	stdin.Close()
	output, err := gpg.CombinedOutput()

	if err != nil {
		return fmt.Errorf("gpg error: \"%s\"", string(output))
	}

	store.AddAndCommit(
		fmt.Sprintf("%s password \"%s\"", gitAction, pwname),
		passwordPath)

	return nil
}

//RemoveDirectory removes the directory at the given path
func (store *PasswordStore) RemoveDirectory(dirname string) error {
	containsDirectory, directoryPath := store.ContainsDirectory(dirname)

	if !containsDirectory {
		return fmt.Errorf("could not find directory at path \"%s\"", directoryPath)
	}

	if err := os.RemoveAll(directoryPath); err != nil {
		return err
	}

	store.AddAndCommit(
		fmt.Sprintf("removed directory \"%s\" from the store", dirname),
		directoryPath)

	return nil
}

//RemovePassword removes the password at the given path
func (store *PasswordStore) RemovePassword(pwname string) error {
	containsPassword, passwordPath := store.ContainsPassword(pwname)

	if !containsPassword {
		return fmt.Errorf("could not find password at path \"%s\"", passwordPath)
	}

	os.Remove(passwordPath)

	store.AddAndCommit(
		fmt.Sprintf("removed password \"%s\" from the store", pwname),
		passwordPath)

	return nil
}

//MoveDirectory moves a directory from source to dest
func (store *PasswordStore) MoveDirectory(source, dest string) error {
	containsDirectory, sourceDirectoryPath := store.ContainsDirectory(source)
	if !containsDirectory {
		return fmt.Errorf("could not find directory at path \"%s\"", sourceDirectoryPath)
	}

	destDirectoryPath := path.Join(store.Path, dest)

	if err := os.Rename(sourceDirectoryPath, destDirectoryPath); err != nil {
		return err
	}

	store.AddAndCommit(
		fmt.Sprintf("moved directory \"%s\" to \"%s\"", source, dest),
		sourceDirectoryPath,
		destDirectoryPath)

	return nil
}

//MovePassword moves a passsword or directory from source to dest.
func (store *PasswordStore) MovePassword(source, dest string) error {
	containsPassword, sourcePasswordPath := store.ContainsPassword(source)

	if !containsPassword {
		return fmt.Errorf("could not find password path \"%s\"", sourcePasswordPath)
	}

	// If the dest ends with a '/', then it is a directory.
	var destPasswordPath string
	if strings.HasSuffix(dest, "/") {
		_, file := filepath.Split(sourcePasswordPath)
		destPasswordPath = path.Join(store.Path, dest, file)
	} else {
		destPasswordPath = path.Join(store.Path, dest+".gpg")
	}

	if err := os.Rename(sourcePasswordPath, destPasswordPath); err != nil {
		return err
	}

	store.AddAndCommit(
		fmt.Sprintf("moved Password \"%s\" to \"%s\"", source, dest),
		sourcePasswordPath,
		destPasswordPath)

	return nil
}

//CopyPassword copies a password from source to dest
func (store *PasswordStore) CopyPassword(source, dest string) error {
	containsPassword, sourcePasswordPath := store.ContainsPassword(source)

	if !containsPassword {
		return fmt.Errorf("could not find password or at path \"%s\"", sourcePasswordPath)
	}

	// If the dest ends with a '/', then it is a directory.
	var destPasswordPath string
	if strings.HasSuffix(dest, "/") {
		_, file := filepath.Split(sourcePasswordPath)
		destPasswordPath = path.Join(store.Path, dest, file)
	} else {
		destPasswordPath = path.Join(store.Path, dest+".gpg")
	}

	if err := gopassio.CopyFileContents(sourcePasswordPath, destPasswordPath); err != nil {
		return err
	}

	store.AddAndCommit(
		fmt.Sprintf("copied Password \"%s\" to \"%s\"", source, dest),
		destPasswordPath)

	return nil
}

//CopyDirectory copies a directory from source to dest
func (store *PasswordStore) CopyDirectory(source, dest string) error {
	containsDirectory, sourceDirectoryPath := store.ContainsDirectory(source)

	if !containsDirectory {
		return fmt.Errorf("could not find directory at path \"%s\"", path.Join(store.Path, source))
	}

	destDirectoryPath := path.Join(store.Path, dest)
	if err := exec.Command("cp", "-r", sourceDirectoryPath, destDirectoryPath).Run(); err != nil {
		return err
	}

	store.AddAndCommit(
		fmt.Sprintf("copied directory \"%s\" to \"%s\"", source, dest),
		destDirectoryPath)

	return nil
}

//GetPassword returns a decrypted password
func (store *PasswordStore) GetPassword(pwname string) (string, error) {
	containsPassword, passwordPath := store.ContainsPassword(pwname)

	//Error if the password does not exist
	if containsPassword == false {
		return "", fmt.Errorf("could not find password \"%s\" at path \"%s\"", pwname, passwordPath)
	}

	//TODO: Use GPG lib instead
	show := exec.Command(store.GPGBin, "--quiet", "--batch", "--use-agent", "-d", passwordPath)
	output, err := show.CombinedOutput()

	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(output)), nil
}

//ContainsPassword returns whether or not the store contains a password with this name.
//it also conveniently returns the password path that was checked
func (store *PasswordStore) ContainsPassword(pwname string) (bool, string) {
	passwordPath := path.Join(store.Path, pwname+".gpg")

	if _, err := os.Stat(passwordPath); os.IsNotExist(err) {
		return false, passwordPath
	}

	return true, passwordPath
}

//ContainsDirectory returns whether or not the store contains a directory with this name.
//it also conveniently returns the directory path that was checked
func (store *PasswordStore) ContainsDirectory(dirname string) (bool, string) {
	directoryPath := path.Join(store.Path, dirname)

	if _, err := os.Stat(directoryPath); os.IsNotExist(err) {
		return false, directoryPath
	}

	return true, directoryPath
}

//GetPasswordsList returns a list of all the passwords
func (store *PasswordStore) GetPasswordsList() []string {
	var list []string

	var scan = func(path string, fileInfo os.FileInfo, inpErr error) (err error) {
		if strings.HasSuffix(path, ".gpg") {
			_, file := filepath.Split(path)
			password := strings.TrimSuffix(file, ".gpg")
			list = append(list, password)
		}
		return
	}

	filepath.Walk(store.Path, scan)

	return list
}

//AddAndCommit adds paths to the index and creates a commit
func (store *PasswordStore) AddAndCommit(message string, paths ...string) error {
	store.git("reset")

	for _, path := range paths {
		store.git("add", path)
	}

	store.git("commit", "-m", message)

	return nil
}

//git executes a git command
func (store *PasswordStore) git(args ...string) error {
	if !store.UsesGit {
		return nil
	}

	gitArgs := []string{
		"--git-dir=" + store.GitDir,
		"--work-tree=" + store.Path}

	gitArgs = append(gitArgs, args...)

	git := exec.Command("git", gitArgs...)

	//Should we do that?
	git.Stdout = os.Stdout
	git.Stderr = os.Stderr
	git.Stdin = os.Stdin

	if err := git.Run(); err != nil {
		fmt.Println(err.Error())
		return fmt.Errorf("git error: \"%s\"", err.Error())
	}

	return nil
}