2pass 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+ require "yaml"
5
+
6
+ module TwoPass
7
+ # The hub's list of approved devices (~/.2pass/devices.yml).
8
+ #
9
+ # Entries are never deleted: a revoked device stays listed so its key can't be
10
+ # silently re-approved and so audit entries keep resolving to a name.
11
+ # Approvals expire by default; an expired device must be renewed.
12
+ class DeviceRegistry
13
+ DEFAULT_EXPIRY_DAYS = 90
14
+
15
+ def self.default_path
16
+ File.join(TwoPass.shared_dir || TwoPass::VAULT_DIR, "devices.yml")
17
+ end
18
+
19
+ def initialize(path: self.class.default_path)
20
+ @path = path
21
+ end
22
+
23
+ def devices
24
+ return [] unless File.file?(@path)
25
+
26
+ Array((YAML.safe_load_file(@path, aliases: false) || {})["devices"])
27
+ end
28
+
29
+ def approve(identity, name: nil, expires_in_days: DEFAULT_EXPIRY_DAYS, now: Time.now)
30
+ name ||= identity.name
31
+ Device.validate_name!(name)
32
+ all = devices
33
+ fingerprint = identity.fingerprint
34
+
35
+ if (existing = all.find { |d| d["fingerprint"] == fingerprint })
36
+ if existing["revoked_at"]
37
+ raise Device::Error, "This key was revoked (device #{existing['name']}). " \
38
+ "Generate a new identity on the device before pairing again."
39
+ end
40
+ raise Device::Error, "This key is already approved as #{existing['name']}. Use: 2pass device renew #{existing['name']}"
41
+ end
42
+
43
+ if all.any? { |d| d["name"] == name }
44
+ raise Device::Error, "A device named #{name} already exists. Pick another name with --name."
45
+ end
46
+
47
+ entry = {
48
+ "name" => name,
49
+ "fingerprint" => fingerprint,
50
+ "sign_public_key" => Device.b64(identity.sign_public_key),
51
+ "box_public_key" => Device.b64(identity.box_public_key),
52
+ "approved_at" => iso(now),
53
+ "expires_at" => expiry(now, expires_in_days),
54
+ "revoked_at" => nil
55
+ }
56
+ save(all << entry)
57
+ entry
58
+ end
59
+
60
+ def revoke(name, now: Time.now)
61
+ update(name) do |device|
62
+ raise Device::Error, "Device #{name} is already revoked" if device["revoked_at"]
63
+
64
+ device["revoked_at"] = iso(now)
65
+ end
66
+ end
67
+
68
+ def renew(name, expires_in_days: DEFAULT_EXPIRY_DAYS, now: Time.now)
69
+ update(name) do |device|
70
+ raise Device::Error, "Device #{name} is revoked and cannot be renewed" if device["revoked_at"]
71
+
72
+ device["expires_at"] = expiry(now, expires_in_days)
73
+ end
74
+ end
75
+
76
+ # The lookup the hub will use to authenticate a request (phase 3).
77
+ def find_active(fingerprint, now: Time.now)
78
+ devices.find { |d| d["fingerprint"] == fingerprint && status(d, now: now) == "active" }
79
+ end
80
+
81
+ def status(device, now: Time.now)
82
+ return "revoked" if device["revoked_at"]
83
+ return "expired" if device["expires_at"] && Time.iso8601(device["expires_at"]) <= now
84
+
85
+ "active"
86
+ end
87
+
88
+ def table(now: Time.now)
89
+ rows = devices.map do |d|
90
+ [
91
+ d["name"],
92
+ Device.pairing_code(d["fingerprint"]),
93
+ status(d, now: now),
94
+ d["approved_at"],
95
+ d["expires_at"] || "never"
96
+ ]
97
+ end
98
+ return "No approved devices." if rows.empty?
99
+
100
+ Terminal::Table.new(headings: ["Device", "Pairing code", "Status", "Approved", "Expires"], rows: rows).to_s
101
+ end
102
+
103
+ private
104
+
105
+ def update(name)
106
+ all = devices
107
+ device = all.find { |d| d["name"] == name }
108
+ raise Device::Error, "Unknown device: #{name}" unless device
109
+
110
+ yield device
111
+ save(all)
112
+ device
113
+ end
114
+
115
+ def save(all)
116
+ FileUtils.mkdir_p(File.dirname(@path))
117
+ Encryption.write_atomic(@path, YAML.dump("devices" => all))
118
+ end
119
+
120
+ def expiry(now, days)
121
+ return nil if days.nil?
122
+ raise Device::Error, "Expiry must be a positive number of days" unless days.is_a?(Integer) && days.positive?
123
+
124
+ iso(now + days * 86_400)
125
+ end
126
+
127
+ def iso(time)
128
+ time.utc.iso8601
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,277 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "open3"
6
+ require "openssl"
7
+ require "yaml"
8
+
9
+ module TwoPass
10
+ # At-rest encryption for vault files.
11
+ #
12
+ # A single 32-byte master key is generated once per machine (the future hub)
13
+ # and kept in a key store (macOS Keychain or a 0600 file). Vault files are
14
+ # encrypted with AES-256-GCM under a key derived from the master key. The
15
+ # header (vault name, env, format version) is authenticated as AAD, so a file
16
+ # cannot be swapped for another vault's file or downgraded without detection.
17
+ module Encryption
18
+ FORMAT = "2pass-vault"
19
+ FORMAT_VERSION = 1
20
+ CIPHER = "aes-256-gcm"
21
+ KEY_BYTES = 32
22
+ NONCE_BYTES = 12
23
+ FILE_SUFFIX = ".enc"
24
+ KEY_SLOTS = {
25
+ master: {filename: "master.key", account: "master-key", label: "master key"},
26
+ device: {filename: "device.key", account: "device-key", label: "device key"}
27
+ }.freeze
28
+ VAULT_KEY_INFO = "2pass vault encryption v1"
29
+
30
+ class Error < StandardError; end
31
+
32
+ class << self
33
+ def config_path
34
+ File.join(TwoPass::VAULT_DIR, "config.yml")
35
+ end
36
+
37
+ def config
38
+ return {} unless File.file?(config_path)
39
+
40
+ YAML.safe_load_file(config_path, aliases: false) || {}
41
+ end
42
+
43
+ def save_config(new_config)
44
+ FileUtils.mkdir_p(TwoPass::VAULT_DIR)
45
+ write_atomic(config_path, YAML.dump(new_config))
46
+ end
47
+
48
+ def enabled?
49
+ !config.dig("encryption", "key_store").nil?
50
+ end
51
+
52
+ def default_key_store
53
+ RUBY_PLATFORM.include?("darwin") ? "keychain" : "file"
54
+ end
55
+
56
+ # Generates a master key, stores it, and records the store in config.yml.
57
+ def init(key_store: default_key_store)
58
+ if enabled?
59
+ raise Error, "Encryption is already configured (#{config_path}). Refusing to replace the master key."
60
+ end
61
+
62
+ store = key_store_for(key_store)
63
+ store.write(OpenSSL::Random.random_bytes(KEY_BYTES))
64
+
65
+ save_config(config.merge("encryption" => {"key_store" => key_store}))
66
+
67
+ store
68
+ end
69
+
70
+ def master_key
71
+ key_store = config.dig("encryption", "key_store")
72
+ unless key_store
73
+ raise Error, "This vault is encrypted but no master key is configured on this machine (#{config_path})."
74
+ end
75
+
76
+ key = key_store_for(key_store).read
77
+ unless key.bytesize == KEY_BYTES
78
+ raise Error, "Master key has an invalid length"
79
+ end
80
+
81
+ key
82
+ end
83
+
84
+ def encrypt(plaintext, vault:, env:, key: master_key)
85
+ header = header_for(vault, env)
86
+ cipher = OpenSSL::Cipher.new(CIPHER).encrypt
87
+ cipher.key = vault_key(key)
88
+ nonce = cipher.random_iv
89
+ cipher.auth_data = aad(header)
90
+ ciphertext = cipher.update(plaintext) + cipher.final
91
+
92
+ JSON.pretty_generate(
93
+ header.merge(
94
+ "nonce" => b64(nonce),
95
+ "tag" => b64(cipher.auth_tag),
96
+ "ciphertext" => b64(ciphertext)
97
+ )
98
+ ) + "\n"
99
+ end
100
+
101
+ def decrypt(document, vault:, env:, key: master_key)
102
+ envelope = JSON.parse(document)
103
+ header = envelope.slice("format", "version", "cipher", "vault", "env")
104
+
105
+ unless header["format"] == FORMAT && header["version"] == FORMAT_VERSION && header["cipher"] == CIPHER
106
+ raise Error, "Unsupported encrypted vault format"
107
+ end
108
+
109
+ expected = header_for(vault, env)
110
+ unless header["vault"] == expected["vault"] && header["env"] == expected["env"]
111
+ raise Error, "Encrypted vault file belongs to #{describe(header['vault'], header['env'])}, " \
112
+ "not #{describe(expected['vault'], expected['env'])}"
113
+ end
114
+
115
+ cipher = OpenSSL::Cipher.new(CIPHER).decrypt
116
+ cipher.key = vault_key(key)
117
+ cipher.iv = unb64(envelope.fetch("nonce"))
118
+ cipher.auth_tag = unb64(envelope.fetch("tag"))
119
+ cipher.auth_data = aad(header)
120
+ cipher.update(unb64(envelope.fetch("ciphertext"))) + cipher.final
121
+ rescue JSON::ParserError, KeyError, ArgumentError
122
+ raise Error, "Encrypted vault file is malformed"
123
+ rescue OpenSSL::Cipher::CipherError
124
+ raise Error, "Unable to decrypt vault: wrong master key, or the file was modified"
125
+ end
126
+
127
+ # Writes via a temp file + rename so a crash never leaves a truncated
128
+ # vault. Follows a symlink so linked vaults keep their link.
129
+ def write_atomic(path, content)
130
+ target = File.symlink?(path) ? File.expand_path(File.readlink(path), File.dirname(path)) : path
131
+ tmp = "#{target}.tmp-#{Process.pid}-#{OpenSSL::Random.random_bytes(4).unpack1('H*')}"
132
+ File.open(tmp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |f|
133
+ f.write(content)
134
+ f.fsync
135
+ end
136
+ File.rename(tmp, target)
137
+ ensure
138
+ FileUtils.rm_f(tmp) if tmp && File.exist?(tmp)
139
+ end
140
+
141
+ # purpose :master is the vault master key (hub only); :device is this
142
+ # machine's private identity key (every machine). Same backends.
143
+ def key_store_for(name, purpose: :master)
144
+ slot = KEY_SLOTS.fetch(purpose)
145
+ case name.to_s
146
+ when "keychain" then KeychainKeyStore.new(account: slot[:account], label: slot[:label])
147
+ when "file" then FileKeyStore.new(filename: slot[:filename], label: slot[:label])
148
+ else raise Error, "Unknown key store: #{name} (expected keychain or file)"
149
+ end
150
+ end
151
+
152
+ private
153
+
154
+ def header_for(vault, env)
155
+ {
156
+ "format" => FORMAT,
157
+ "version" => FORMAT_VERSION,
158
+ "cipher" => CIPHER,
159
+ "vault" => vault.to_s,
160
+ "env" => env&.to_s
161
+ }
162
+ end
163
+
164
+ def aad(header)
165
+ JSON.generate(header.values_at("format", "version", "cipher", "vault", "env"))
166
+ end
167
+
168
+ def vault_key(master_key)
169
+ OpenSSL::KDF.hkdf(master_key, salt: "", info: VAULT_KEY_INFO, length: KEY_BYTES, hash: "SHA256")
170
+ end
171
+
172
+ def describe(vault, env)
173
+ env ? "#{vault} (#{env})" : vault.to_s
174
+ end
175
+
176
+ def b64(bytes)
177
+ [bytes].pack("m0")
178
+ end
179
+
180
+ def unb64(string)
181
+ string.unpack1("m0")
182
+ end
183
+ end
184
+
185
+ # Key stored as a 0600 file next to the vaults. Fallback for non-macOS
186
+ # machines; protect it with full-disk encryption.
187
+ class FileKeyStore
188
+ def initialize(filename: "master.key", label: "master key")
189
+ @filename = filename
190
+ @label = label
191
+ end
192
+
193
+ def path
194
+ File.join(TwoPass::VAULT_DIR, @filename)
195
+ end
196
+
197
+ def description
198
+ "file #{path}"
199
+ end
200
+
201
+ def write(key)
202
+ FileUtils.mkdir_p(TwoPass::VAULT_DIR)
203
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |f|
204
+ f.write([key].pack("m0"))
205
+ end
206
+ rescue Errno::EEXIST
207
+ raise Error, "A #{@label} file already exists at #{path}"
208
+ end
209
+
210
+ def read
211
+ unless File.file?(path)
212
+ raise Error, "#{@label.capitalize} file not found: #{path}"
213
+ end
214
+
215
+ mode = File.stat(path).mode & 0o777
216
+ if mode & 0o077 != 0
217
+ raise Error, "#{@label.capitalize} file #{path} is accessible by other users (mode #{format('%o', mode)}). Run: chmod 600 #{path}"
218
+ end
219
+
220
+ File.read(path).strip.unpack1("m0")
221
+ rescue ArgumentError
222
+ raise Error, "#{@label.capitalize} file is malformed: #{path}"
223
+ end
224
+ end
225
+
226
+ # Key stored as a generic password in the login Keychain.
227
+ class KeychainKeyStore
228
+ SERVICE = "2pass"
229
+ ACCOUNT = "master-key"
230
+
231
+ def initialize(service: SERVICE, account: ACCOUNT, label: "master key")
232
+ @service = service
233
+ @account = account
234
+ @label = label
235
+ end
236
+
237
+ def description
238
+ "macOS Keychain (service #{@service}, account #{@account})"
239
+ end
240
+
241
+ def write(key)
242
+ if read_raw
243
+ raise Error, "A #{@label} already exists in the Keychain (service #{@service}, account #{@account})"
244
+ end
245
+
246
+ # Fed through `security -i` on stdin so the key never shows up in argv.
247
+ command = "add-generic-password -s #{@service} -a #{@account} -w #{[key].pack("m0")}\n"
248
+ _out, err, status = Open3.capture3("security", "-i", stdin_data: command)
249
+ unless status.success? && err.strip.empty? && read_raw
250
+ raise Error, "Unable to store #{@label} in the Keychain: #{err.strip}"
251
+ end
252
+ end
253
+
254
+ def read
255
+ raw = read_raw
256
+ raise Error, "#{@label.capitalize} not found in the Keychain (service #{@service}, account #{@account})" unless raw
257
+
258
+ raw.unpack1("m0")
259
+ rescue ArgumentError
260
+ raise Error, "#{@label.capitalize} in the Keychain is malformed"
261
+ end
262
+
263
+ def delete
264
+ Open3.capture3("security", "delete-generic-password", "-s", @service, "-a", @account)
265
+ end
266
+
267
+ private
268
+
269
+ def read_raw
270
+ out, _err, status = Open3.capture3("security", "find-generic-password", "-s", @service, "-a", @account, "-w")
271
+ status.success? ? out.strip : nil
272
+ rescue Errno::ENOENT
273
+ raise Error, "The `security` command is unavailable; use the file key store on this platform"
274
+ end
275
+ end
276
+ end
277
+ end