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.
data/bin/2pass CHANGED
@@ -11,13 +11,66 @@ def help_message
11
11
  2pass list <vault_name> [env] --json - List the content of the specified vault as JSON. env is optional
12
12
  2pass list <vault_name> [env] --dotenv - List the content of the specified vault as key=value pairs. env is optional
13
13
  2pass link <vault_name> <target_path> [env] - Create a symlink for an existing vault. Useful when the vault is stored in a synced place (iCloud, Dropbox, etc.). env is optional
14
+ 2pass key init [--key-store keychain|file] - Create a master key; new vaults are then encrypted at rest (default store: keychain on macOS, file elsewhere)
15
+ 2pass migrate encrypt <vault_name> [env] [--keep-plaintext]
16
+ - Encrypt an existing plaintext vault, then remove the local plaintext entry
17
+ 2pass device init [--name NAME] [--key-store keychain|file]
18
+ - Create this machine's device identity (key pair)
19
+ 2pass device id - Show this device's name, pairing code and pairing token
20
+ 2pass device approve <token> [--name NAME] [--expires-in DAYS|never] [--grant VAULT[:ENV]]... [--yes]
21
+ - Hub: approve a device after comparing its pairing code (default expiry: 90 days),
22
+ and add it to the broker policy (asks which vaults it may read unless --grant/--yes)
23
+ 2pass device list - Hub: list approved, expired and revoked devices
24
+ 2pass policy grant <device> <vault[:env]>... - Primary: give a device read access (get/list, all secrets) to vaults
25
+ 2pass policy show [device] - Primary: show what each device is granted
26
+ 2pass device revoke <name> - Hub: revoke a device
27
+ 2pass device renew <name> [--expires-in DAYS|never]
28
+ - Hub: extend a device approval
29
+ 2pass serve --stdio [--policy path] - Hub: answer one signed device request on stdin (use as the SSH forced command)
30
+ 2pass bundle export <device> [--expires-in DAYS] [--to DIR]
31
+ - Primary: seal the secrets granted to <device> (default 14 days); prints it, or writes it into DIR
32
+ 2pass bundle import [FILE] - Device: install a bundle from FILE or stdin (e.g. pbpaste | 2pass bundle import);
33
+ the first bundle from a primary asks to confirm its pairing code
34
+ 2pass bundle import --from DIR - Device: install the newest bundle for this device found in DIR
35
+ 2pass bundle source DIR - Device: check DIR (e.g. a Syncthing folder) for newer bundles before each get/list
36
+ 2pass bundle status - Device: show what the installed bundle contains (ids only) and when it expires
37
+ 2pass hub share <dir> - Primary: keep vaults, approved devices and the broker policy in a synced folder (e.g. iCloud Drive)
38
+ 2pass hub trust <hub_token> [--ssh 2pass-hub | --command "cmd"] [--name NAME] [--yes]
39
+ - Device: trust a primary (repeat for each); without --ssh/--command it is trusted for bundles only
40
+ 2pass hub list - Device: list trusted hubs
41
+ 2pass hub remove <name> - Device: stop trusting a hub
42
+ 2pass hub ping - Device: check each trusted hub accepts this device
43
+ 2pass use <vault_name> <action> [env] - Device: run a policy-defined action on the hub; secrets stay on the hub
44
+ 2pass cache clear - Device: delete cached hub answers
45
+ 2pass approvals - Hub: list requests waiting for approval
46
+ 2pass approve <id> [--for MINUTES] - Hub: approve a request (reused for the grant's approval_ttl unless --for)
47
+ 2pass deny <id> - Hub: deny a request
48
+
49
+ Device options for get, list and use:
50
+ --agent NAME act as agent NAME on this device (or set TWOPASS_AGENT); the hub sees <device>/<agent>
51
+ --purpose NAME purpose sent to the hub (default: cli)
52
+ --wait SECONDS how long to wait for an approval on the hub (default: 120, 0 to fail fast)
53
+ --no-cache ignore cached answers and ask the hub
54
+ 2pass broker [--policy path] - Handle one JSON broker request from stdin with per-call policy authorization
14
55
  2pass update - Update 2pass to the latest RubyGems release
15
56
  2pass -h - Display this help message
16
57
  HELP
17
58
  end
18
59
 
60
+ # A bundle pasted as an argument starts with "-----BEGIN", which the option
61
+ # parser would take for an option. Pull it out first, whether it arrives as
62
+ # one quoted argument or split into words by the shell.
63
+ inline_bundle = nil
64
+ if (start = ARGV.index { |arg| arg.start_with?("-----BEGIN") })
65
+ finish = (start...ARGV.length).find { |i| ARGV[i].include?(TwoPass::Bundle::ARMOR_END) }
66
+ finish ||= (start...ARGV.length).find { |i| ARGV[i] == "-----END" }&.then { |i| [i + 2, ARGV.length - 1].min }
67
+ finish ||= ARGV.length - 1
68
+ inline_bundle = ARGV[start..finish].join(" ")
69
+ ARGV.slice!(start..finish)
70
+ end
71
+
19
72
  options = {}
20
- OptionParser.new do |opts|
73
+ parser = OptionParser.new do |opts|
21
74
  opts.banner = "Usage: 2pass [options]"
22
75
 
23
76
  opts.on("-h", "--help", "Display this help message") do
@@ -32,7 +85,65 @@ OptionParser.new do |opts|
32
85
  opts.on("--dotenv", "Use key=value output format") do
33
86
  options[:format] = :dotenv
34
87
  end
35
- end.parse!
88
+ opts.on("--policy PATH", "Use broker policy file") do |path|
89
+ options[:policy_path] = path
90
+ end
91
+ opts.on("--key-store STORE", "Master key store: keychain or file") do |store|
92
+ options[:key_store] = store
93
+ end
94
+ opts.on("--name NAME", "Device name") do |name|
95
+ options[:name] = name
96
+ end
97
+ opts.on("--expires-in DAYS", "Device approval lifetime in days, or 'never'") do |days|
98
+ options[:expires_in] = days
99
+ end
100
+ opts.on("--yes", "Skip the pairing code confirmation prompt") do
101
+ options[:yes] = true
102
+ end
103
+ opts.on("--ssh HOST", "Reach the hub over SSH (host or ~/.ssh/config alias, e.g. 2pass-hub)") do |host|
104
+ options[:ssh] = host
105
+ end
106
+ opts.on("--command CMD", "Command that reaches the hub's `2pass serve --stdio`") do |cmd|
107
+ options[:command] = cmd
108
+ end
109
+ opts.on("--purpose PURPOSE", "Purpose sent to the hub with get/list (default: cli)") do |purpose|
110
+ options[:purpose] = purpose
111
+ end
112
+ opts.on("--agent NAME", "Act as an agent of this device") do |agent|
113
+ options[:agent] = agent
114
+ end
115
+ opts.on("--wait SECONDS", Integer, "Seconds to wait for an approval on the hub") do |seconds|
116
+ options[:wait] = seconds
117
+ end
118
+ opts.on("--no-cache", "Ignore cached hub answers") do
119
+ options[:no_cache] = true
120
+ end
121
+ opts.on("--for MINUTES", Integer, "Approval duration in minutes") do |minutes|
122
+ options[:for_minutes] = minutes
123
+ end
124
+ opts.on("--grant VAULT[:ENV]", "Vault to grant read access to (repeatable)") do |spec|
125
+ (options[:grants] ||= []) << spec
126
+ end
127
+ opts.on("--to DIR", "Folder to write a bundle into") do |dir|
128
+ options[:to] = dir
129
+ end
130
+ opts.on("--from DIR", "Folder to import a bundle from") do |dir|
131
+ options[:from] = dir
132
+ end
133
+ opts.on("--stdio", "Serve one request over stdin/stdout") do
134
+ options[:stdio] = true
135
+ end
136
+ opts.on("--keep-plaintext", "Keep the plaintext vault after migrate encrypt") do
137
+ options[:keep_plaintext] = true
138
+ end
139
+ end
140
+
141
+ begin
142
+ parser.parse!
143
+ rescue OptionParser::ParseError => e
144
+ $stderr.puts "#{e.message}. Run `2pass -h` for usage."
145
+ exit(1)
146
+ end
36
147
 
37
148
  if options[:help]
38
149
  help_message
@@ -51,6 +162,12 @@ end
51
162
 
52
163
  command, *args = ARGV
53
164
 
165
+ remote_options = {
166
+ agent: options[:agent] || TwoPass::Remote.agent_from_env,
167
+ wait: options[:wait],
168
+ no_cache: options[:no_cache]
169
+ }.compact
170
+
54
171
  begin
55
172
  case command&.to_sym
56
173
  when :get
@@ -59,7 +176,7 @@ begin
59
176
  exit(1)
60
177
  end
61
178
  vault_name, id, env = args[0], args[1], args[2]
62
- puts TwoPass.get_secret(vault_name, id, env: env)
179
+ puts TwoPass.get_secret(vault_name, id, env: env, purpose: options[:purpose], **remote_options)
63
180
  when :add
64
181
  if args.length < 3 || args.length > 4
65
182
  help_message
@@ -74,11 +191,11 @@ begin
74
191
  end
75
192
  vault_name, env = args[0], args[1]
76
193
  if options[:format] == :json
77
- puts TwoPass.list_content(vault_name, env: env, format: :json)
194
+ puts TwoPass.list_content(vault_name, env: env, format: :json, purpose: options[:purpose], **remote_options)
78
195
  elsif options[:format] == :dotenv
79
- puts TwoPass.list_content(vault_name, env: env, format: :dotenv)
196
+ puts TwoPass.list_content(vault_name, env: env, format: :dotenv, purpose: options[:purpose], **remote_options)
80
197
  else
81
- puts TwoPass.list_content(vault_name, env: env)
198
+ puts TwoPass.list_content(vault_name, env: env, purpose: options[:purpose], **remote_options)
82
199
  end
83
200
  exit(0)
84
201
  when :link
@@ -88,6 +205,214 @@ begin
88
205
  end
89
206
  vault_name, target_path, env = args[0], args[1], args[2]
90
207
  TwoPass.create_symlink(vault_name, target_path, env: env)
208
+ when :key
209
+ unless args == ["init"]
210
+ help_message
211
+ exit(1)
212
+ end
213
+ puts TwoPass.init_encryption(key_store: options[:key_store])
214
+ when :migrate
215
+ if args.first != "encrypt" || args.length < 2 || args.length > 3
216
+ help_message
217
+ exit(1)
218
+ end
219
+ vault_name, env = args[1], args[2]
220
+ puts TwoPass.encrypt_vault(vault_name, env: env, keep_plaintext: options[:keep_plaintext] || false)
221
+ when :device
222
+ subcommand, *rest = args
223
+ case [subcommand, rest.length]
224
+ when ["init", 0]
225
+ puts TwoPass.init_device(name: options[:name], key_store: options[:key_store])
226
+ when ["id", 0]
227
+ puts TwoPass::Device.describe_local
228
+ when ["approve", 1]
229
+ confirm = lambda do |code, name|
230
+ next true if options[:yes]
231
+
232
+ $stderr.puts "Pairing code for #{name}: #{code}"
233
+ $stderr.print "Does it match the code shown by `2pass device id` on that device? [y/N] "
234
+ $stdin.gets.to_s.strip.downcase.start_with?("y")
235
+ end
236
+ choose = lambda do |name, targets|
237
+ next [] if options[:yes] || !$stdin.tty? || targets.empty?
238
+
239
+ $stderr.puts "#{name} is new in the broker policy. Vaults on this machine:"
240
+ targets.each_with_index { |t, i| $stderr.puts " #{i + 1}. #{t}" }
241
+ $stderr.print "Give #{name} read access to which? (numbers like 1,3; empty for none) "
242
+ picks = $stdin.gets.to_s.split(/[\s,]+/).reject(&:empty?)
243
+ picks.map do |pick|
244
+ index = Integer(pick, 10) - 1
245
+ raise "No vault numbered #{pick}" unless index.between?(0, targets.size - 1)
246
+
247
+ targets[index]
248
+ end
249
+ end
250
+ puts TwoPass.approve_device(rest[0], name: options[:name], expires_in: options[:expires_in],
251
+ confirm: confirm, grants: options[:grants] || [], choose: choose)
252
+ when ["list", 0]
253
+ puts TwoPass::DeviceRegistry.new.table
254
+ when ["revoke", 1]
255
+ puts TwoPass.revoke_device(rest[0])
256
+ when ["renew", 1]
257
+ puts TwoPass.renew_device(rest[0], expires_in: options[:expires_in])
258
+ else
259
+ help_message
260
+ exit(1)
261
+ end
262
+ when :serve
263
+ if args.any?
264
+ help_message
265
+ exit(1)
266
+ end
267
+ server = TwoPass::Server.new(
268
+ identity: TwoPass::Device.local_identity,
269
+ policy_path: options[:policy_path] || TwoPass::Broker.default_policy_path
270
+ )
271
+ $stdout.write(server.handle_json($stdin.read(TwoPass::Server::MAX_REQUEST_BYTES + 1).to_s))
272
+ when :policy
273
+ subcommand, *rest = args
274
+ if subcommand == "grant" && rest.length >= 2
275
+ puts TwoPass.grant_access(rest[0], rest[1..])
276
+ elsif subcommand == "show" && rest.length <= 1
277
+ puts TwoPass::Policy.new.describe(rest[0])
278
+ else
279
+ help_message
280
+ exit(1)
281
+ end
282
+ when :bundle
283
+ subcommand, *rest = args
284
+ case [subcommand, rest.length]
285
+ when ["export", 1]
286
+ days = options[:expires_in] ? Integer(options[:expires_in], 10) : TwoPass::Bundle::DEFAULT_EXPIRY_DAYS
287
+ result = TwoPass::Bundle.export(rest[0], expires_in_days: days, to: options[:to])
288
+ if result.path
289
+ puts result.summary
290
+ else
291
+ $stdout.write(result.armored)
292
+ $stderr.puts result.summary
293
+ end
294
+ when ["import", 0], ["import", 1]
295
+ # stdin may be the bundle itself (pbpaste | 2pass bundle import), so the
296
+ # question about a new primary is asked on the terminal.
297
+ confirm_signer = lambda do |signer|
298
+ next true if options[:yes]
299
+
300
+ # Only ask when someone can see the question (stderr is a terminal);
301
+ # scripts and CI that capture output get a refusal, never a hang.
302
+ tty = $stderr.tty? ? (File.open("/dev/tty", "r+") rescue nil) : nil
303
+ unless tty
304
+ $stderr.puts "This bundle comes from #{signer.name}, which this device doesn't trust yet. " \
305
+ "Run the import in a terminal to confirm its pairing code."
306
+ next false
307
+ end
308
+ tty.puts "This bundle comes from #{signer.name}, which this device doesn't trust yet."
309
+ tty.puts "Pairing code: #{signer.pairing_code}"
310
+ tty.print "Does it match the code shown by `2pass device id` on #{signer.name}? [y/N] "
311
+ tty.gets.to_s.strip.downcase.start_with?("y").tap { tty.close }
312
+ end
313
+ puts(if options[:from]
314
+ TwoPass::Bundle.import_from(options[:from], confirm_signer: confirm_signer)
315
+ else
316
+ text = if inline_bundle
317
+ unless inline_bundle.include?(TwoPass::Bundle::ARMOR_END)
318
+ raise "Only the first line of the bundle reached 2pass: the shell runs each pasted line " \
319
+ "as a separate command. Run `2pass bundle import` and paste the bundle when asked, " \
320
+ "or copy it and run `pbpaste | 2pass bundle import`."
321
+ end
322
+ inline_bundle
323
+ elsif rest[0] && rest[0] != "-"
324
+ File.read(rest[0])
325
+ elsif $stdin.tty?
326
+ # Pasted by hand: read until the END line, no Ctrl-D needed.
327
+ $stderr.puts "Paste the bundle (from #{TwoPass::Bundle::ARMOR_BEGIN} to #{TwoPass::Bundle::ARMOR_END}):"
328
+ lines = []
329
+ while (line = $stdin.gets)
330
+ lines << line
331
+ break if line.include?(TwoPass::Bundle::ARMOR_END)
332
+ end
333
+ lines.join
334
+ else
335
+ $stdin.read
336
+ end
337
+ TwoPass::Bundle.import(text, confirm_signer: confirm_signer)
338
+ end)
339
+ when ["source", 1]
340
+ puts TwoPass::Bundle.set_source(rest[0])
341
+ when ["status", 0]
342
+ puts TwoPass::Bundle.status
343
+ else
344
+ help_message
345
+ exit(1)
346
+ end
347
+ when :hub
348
+ subcommand, *rest = args
349
+ case [subcommand, rest.length]
350
+ when ["trust", 1]
351
+ confirm = lambda do |code, name|
352
+ next true if options[:yes]
353
+
354
+ $stderr.puts "Hub pairing code for #{name}: #{code}"
355
+ $stderr.print "Does it match the code shown by `2pass device id` on the hub? [y/N] "
356
+ $stdin.gets.to_s.strip.downcase.start_with?("y")
357
+ end
358
+ puts TwoPass::Remote.trust(rest[0], ssh: options[:ssh], command: options[:command], name: options[:name], confirm: confirm)
359
+ when ["list", 0], ["show", 0]
360
+ puts TwoPass::Remote.describe
361
+ when ["remove", 1]
362
+ puts TwoPass::Remote.remove(rest[0])
363
+ when ["share", 1]
364
+ puts TwoPass.share_state(rest[0])
365
+ when ["ping", 0]
366
+ puts TwoPass::Remote.ping
367
+ else
368
+ help_message
369
+ exit(1)
370
+ end
371
+ when :use
372
+ if args.length < 2 || args.length > 3
373
+ help_message
374
+ exit(1)
375
+ end
376
+ vault_name, action, env = args
377
+ response = TwoPass.use_action(vault_name, action, env: env, purpose: options[:purpose], **remote_options)
378
+ $stdout.write(response["stdout"].to_s)
379
+ $stderr.write(response["stderr"].to_s)
380
+ exit(response["status"].is_a?(Integer) ? response["status"] : (response["success"] ? 0 : 1))
381
+ when :cache
382
+ unless args == ["clear"]
383
+ help_message
384
+ exit(1)
385
+ end
386
+ puts TwoPass::Remote.clear_cache
387
+ when :approvals
388
+ if args.any?
389
+ help_message
390
+ exit(1)
391
+ end
392
+ puts TwoPass::Approvals.new.table
393
+ when :approve, :deny
394
+ if args.length != 1
395
+ help_message
396
+ exit(1)
397
+ end
398
+ approvals = TwoPass::Approvals.new
399
+ if command.to_sym == :approve
400
+ entry = approvals.approve(args[0], seconds: options[:for_minutes] && options[:for_minutes] * 60)
401
+ puts "Approved #{args[0]} for #{entry['scope']['principal']} until #{Time.at(entry['approved_until']).utc.iso8601}."
402
+ else
403
+ approvals.deny(args[0])
404
+ puts "Denied #{args[0]}."
405
+ end
406
+ when :broker
407
+ if args.any?
408
+ help_message
409
+ exit(1)
410
+ end
411
+ response = TwoPass::Broker
412
+ .new(policy_path: options[:policy_path] || TwoPass::Broker.default_policy_path)
413
+ .handle_json($stdin.read)
414
+ puts JSON.pretty_generate(response)
415
+ exit(response[:ok] ? 0 : 1)
91
416
  when :update
92
417
  if args.any?
93
418
  help_message
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+ require "time"
6
+
7
+ module TwoPass
8
+ # Human approvals for grants marked `require_approval: true`.
9
+ #
10
+ # A request that needs approval creates (or reuses) a pending entry for its
11
+ # scope: who (principal), what (operation + secret id / action / "*"),
12
+ # where (vault, env) and why (purpose). Once approved on the hub, the same
13
+ # scope is allowed until `approved_until`, so callers aren't asked again on
14
+ # every call. Pending and denied entries lapse after PENDING_TTL.
15
+ class Approvals
16
+ DEFAULT_APPROVAL_TTL = 600
17
+ PENDING_TTL = 600
18
+ RETENTION = 86_400
19
+ SCOPE_FIELDS = %w[principal operation vault env target purpose].freeze
20
+
21
+ def self.default_path
22
+ File.join(TwoPass::VAULT_DIR, "approvals.json")
23
+ end
24
+
25
+ def initialize(path: self.class.default_path)
26
+ @path = path
27
+ end
28
+
29
+ def self.scope(principal:, operation:, vault:, env:, target:, purpose:)
30
+ {
31
+ "principal" => principal, "operation" => operation, "vault" => vault,
32
+ "env" => env, "target" => target, "purpose" => purpose
33
+ }
34
+ end
35
+
36
+ # Seconds left on an approval covering this scope, or nil.
37
+ def approved_remaining(scope, now: Time.now)
38
+ entry = entries.find do |e|
39
+ e["status"] == "approved" && same_scope?(e, scope) && e["approved_until"].to_i > now.to_i
40
+ end
41
+ entry && entry["approved_until"].to_i - now.to_i
42
+ end
43
+
44
+ # Returns the live pending/denied entry for the scope, creating a pending
45
+ # one if there is none.
46
+ def request(scope, ttl:, now: Time.now)
47
+ update(now) do |list|
48
+ live = list.find do |e|
49
+ same_scope?(e, scope) && %w[pending denied].include?(e["status"]) && e["created_at"] > now.to_i - PENDING_TTL
50
+ end
51
+ next live if live
52
+
53
+ entry = {
54
+ "id" => OpenSSL::Random.random_bytes(4).unpack1("H*"),
55
+ "scope" => scope.slice(*SCOPE_FIELDS),
56
+ "status" => "pending",
57
+ "ttl" => ttl,
58
+ "created_at" => now.to_i
59
+ }
60
+ list << entry
61
+ entry
62
+ end
63
+ end
64
+
65
+ def approve(id, seconds: nil, now: Time.now)
66
+ decide(id, now) do |entry|
67
+ entry["status"] = "approved"
68
+ entry["approved_until"] = now.to_i + (seconds || entry["ttl"] || DEFAULT_APPROVAL_TTL)
69
+ end
70
+ end
71
+
72
+ def deny(id, now: Time.now)
73
+ decide(id, now) { |entry| entry["status"] = "denied" }
74
+ end
75
+
76
+ def pending(now: Time.now)
77
+ entries.select { |e| e["status"] == "pending" && e["created_at"] > now.to_i - PENDING_TTL }
78
+ end
79
+
80
+ def table(now: Time.now)
81
+ rows = pending(now: now).map do |e|
82
+ s = e["scope"]
83
+ target = s["target"] == "*" ? "(all allowed)" : s["target"]
84
+ [e["id"], s["principal"], s["operation"], [s["vault"], s["env"]].compact.join(" / "), target, s["purpose"],
85
+ Time.at(e["created_at"]).utc.iso8601]
86
+ end
87
+ return "No pending approvals." if rows.empty?
88
+
89
+ Terminal::Table.new(headings: %w[ID Who Operation Vault Secret/action Purpose Requested], rows: rows).to_s
90
+ end
91
+
92
+ private
93
+
94
+ def entries
95
+ return [] unless File.file?(@path)
96
+
97
+ Array(JSON.parse(File.read(@path))["entries"])
98
+ rescue JSON::ParserError
99
+ []
100
+ end
101
+
102
+ def update(now)
103
+ LockedJsonFile.update(@path) do |data|
104
+ list = Array(data["entries"])
105
+ list.reject! { |e| e["created_at"].to_i < now.to_i - RETENTION && e["approved_until"].to_i < now.to_i }
106
+ result = yield list
107
+ data["entries"] = list
108
+ result
109
+ end
110
+ end
111
+
112
+ def decide(id, now)
113
+ update(now) do |list|
114
+ entry = list.find { |e| e["id"] == id }
115
+ raise "Unknown approval request: #{id}" unless entry
116
+ raise "Approval request #{id} is no longer pending" unless entry["status"] == "pending"
117
+ raise "Approval request #{id} has expired; ask the caller to retry" if entry["created_at"] <= now.to_i - PENDING_TTL
118
+
119
+ yield entry
120
+ entry
121
+ end
122
+ end
123
+
124
+ def same_scope?(entry, scope)
125
+ entry["scope"] == scope.slice(*SCOPE_FIELDS)
126
+ end
127
+ end
128
+ end