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,323 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+
6
+ module TwoPass
7
+ # Signed + encrypted messages between a device and the hub.
8
+ #
9
+ # Request (device -> hub)
10
+ # - The device creates an ephemeral X25519 key and derives a key with the
11
+ # hub's static X25519 key (HKDF-SHA256, salted with both public keys).
12
+ # - The body is AES-256-GCM encrypted; the header (sender, recipient,
13
+ # ephemeral key, request id, timestamp) is the AAD.
14
+ # - The device signs header + ciphertext with its Ed25519 key.
15
+ # The hub checks: recipient is itself, sender is an active approved device,
16
+ # signature, timestamp within MAX_SKEW, request id never seen (replay).
17
+ #
18
+ # Response (hub -> device)
19
+ # - Encrypted to the request's *ephemeral* key with a fresh hub ephemeral
20
+ # key, so a recorded exchange can't be decrypted later even if long-term
21
+ # keys leak (forward secrecy), and only the requester can read it.
22
+ # - Signed by the hub; the device checks it against the pinned hub key and
23
+ # that in_reply_to matches its request id.
24
+ module Envelope
25
+ VERSION = 1
26
+ MAX_SKEW = 60
27
+ REQUEST_FIELDS = %w[v type from to eph id ts].freeze
28
+ RESPONSE_FIELDS = %w[v type from to eph in_reply_to ts].freeze
29
+ BUNDLE_FIELDS = %w[v type from to eph issued_at expires_at].freeze
30
+ SIGNATURE_CONTEXT = "2pass envelope v1\0"
31
+ REQUEST_KEY_INFO = "2pass request key v1"
32
+ RESPONSE_KEY_INFO = "2pass response key v1"
33
+ BUNDLE_KEY_INFO = "2pass bundle key v1"
34
+
35
+ # Rejections raised while opening a request. The code is safe to return to
36
+ # an unauthenticated caller.
37
+ class Rejected < StandardError
38
+ attr_reader :code
39
+
40
+ def initialize(code, message)
41
+ @code = code
42
+ super(message)
43
+ end
44
+ end
45
+
46
+ class Error < StandardError; end
47
+
48
+ PendingRequest = Data.define(:id, :ephemeral_key)
49
+ OpenedRequest = Data.define(:id, :device, :client_ephemeral_public, :body)
50
+
51
+ class << self
52
+ # Client side. Returns [envelope_json, PendingRequest].
53
+ def seal_request(body, identity:, hub:, now: Time.now)
54
+ ephemeral = OpenSSL::PKey.generate_key("X25519")
55
+ ephemeral_public = ephemeral.raw_public_key
56
+ header = {
57
+ "v" => VERSION,
58
+ "type" => "request",
59
+ "from" => identity.public_identity.fingerprint,
60
+ "to" => hub.fingerprint,
61
+ "eph" => Device.b64(ephemeral_public),
62
+ "id" => OpenSSL::Random.random_bytes(16).unpack1("H*"),
63
+ "ts" => now.to_i
64
+ }
65
+ key = derive_key(
66
+ dh(ephemeral, hub.box_public_key),
67
+ salt: ephemeral_public + hub.box_public_key,
68
+ info: REQUEST_KEY_INFO
69
+ )
70
+ envelope = seal(header, REQUEST_FIELDS, body, key) { |input| identity.sign(input) }
71
+ [JSON.generate(envelope), PendingRequest.new(id: header["id"], ephemeral_key: ephemeral)]
72
+ end
73
+
74
+ # Hub side. Verifies everything before decrypting; raises Rejected.
75
+ def open_request(envelope, hub_identity:, registry:, replay_cache:, now: Time.now)
76
+ header = envelope.slice(*REQUEST_FIELDS)
77
+ unless header["v"] == VERSION && header["type"] == "request"
78
+ raise Rejected.new("invalid_request", "Unsupported request format")
79
+ end
80
+ unless header["to"] == hub_identity.public_identity.fingerprint
81
+ raise Rejected.new("wrong_hub", "Request is addressed to a different hub")
82
+ end
83
+
84
+ device = registry.find_active(header["from"].to_s, now: now)
85
+ unless device
86
+ raise Rejected.new("unauthenticated", "Device is not approved, its approval expired, or it was revoked")
87
+ end
88
+
89
+ verify!(envelope, header, REQUEST_FIELDS, Device.unb64(device["sign_public_key"])) ||
90
+ raise(Rejected.new("unauthenticated", "Request signature is invalid"))
91
+
92
+ unless header["ts"].is_a?(Integer) && (now.to_i - header["ts"]).abs <= MAX_SKEW
93
+ raise Rejected.new("stale_request", "Request timestamp is outside the allowed window; check the device clock")
94
+ end
95
+ unless header["id"].is_a?(String) && header["id"].match?(/\A\h{32}\z/)
96
+ raise Rejected.new("invalid_request", "Invalid request id")
97
+ end
98
+ unless replay_cache.check_and_store(header["id"], now: now)
99
+ raise Rejected.new("replayed_request", "Request was already processed")
100
+ end
101
+
102
+ client_ephemeral_public = public_key_bytes(header["eph"])
103
+ key = derive_key(
104
+ hub_identity.derive(client_ephemeral_public),
105
+ salt: client_ephemeral_public + hub_identity.public_identity.box_public_key,
106
+ info: REQUEST_KEY_INFO
107
+ )
108
+ body = JSON.parse(decrypt(envelope, header, REQUEST_FIELDS, key))
109
+ raise Rejected.new("invalid_request", "Request body must be an object") unless body.is_a?(Hash)
110
+
111
+ OpenedRequest.new(id: header["id"], device: device, client_ephemeral_public: client_ephemeral_public, body: body)
112
+ rescue Error, JSON::ParserError, OpenSSL::PKey::PKeyError, ArgumentError, TypeError
113
+ raise Rejected.new("invalid_request", "Request could not be decrypted")
114
+ end
115
+
116
+ # Hub side.
117
+ def seal_response(body, hub_identity:, request:, now: Time.now)
118
+ ephemeral = OpenSSL::PKey.generate_key("X25519")
119
+ ephemeral_public = ephemeral.raw_public_key
120
+ header = {
121
+ "v" => VERSION,
122
+ "type" => "response",
123
+ "from" => hub_identity.public_identity.fingerprint,
124
+ "to" => request.device["fingerprint"],
125
+ "eph" => Device.b64(ephemeral_public),
126
+ "in_reply_to" => request.id,
127
+ "ts" => now.to_i
128
+ }
129
+ key = derive_key(
130
+ dh(ephemeral, request.client_ephemeral_public),
131
+ salt: ephemeral_public + request.client_ephemeral_public,
132
+ info: RESPONSE_KEY_INFO
133
+ )
134
+ JSON.generate(seal(header, RESPONSE_FIELDS, body, key) { |input| hub_identity.sign(input) })
135
+ end
136
+
137
+ # Client side. Returns the decrypted body; raises Error.
138
+ def open_response(envelope, identity:, hub:, pending:)
139
+ header = envelope.slice(*RESPONSE_FIELDS)
140
+ unless header["v"] == VERSION && header["type"] == "response"
141
+ raise Error, "Unexpected response format"
142
+ end
143
+ unless header["from"] == hub.fingerprint && header["to"] == identity.public_identity.fingerprint
144
+ raise Error, "Response is not from the trusted hub or not addressed to this device"
145
+ end
146
+ raise Error, "Response does not match the request" unless header["in_reply_to"] == pending.id
147
+ raise Error, "Response signature is invalid" unless verify!(envelope, header, RESPONSE_FIELDS, hub.sign_public_key)
148
+
149
+ hub_ephemeral_public = public_key_bytes(header["eph"])
150
+ key = derive_key(
151
+ dh(pending.ephemeral_key, hub_ephemeral_public),
152
+ salt: hub_ephemeral_public + pending.ephemeral_key.raw_public_key,
153
+ info: RESPONSE_KEY_INFO
154
+ )
155
+ JSON.parse(decrypt(envelope, header, RESPONSE_FIELDS, key))
156
+ rescue JSON::ParserError, OpenSSL::PKey::PKeyError, ArgumentError, TypeError
157
+ raise Error, "Response could not be decrypted"
158
+ end
159
+
160
+ # Primary side: secrets for one device, encrypted to its static X25519
161
+ # key (with a fresh ephemeral key) and signed by the primary.
162
+ def seal_bundle(body, identity:, recipient:, issued_at:, expires_at:)
163
+ ephemeral = OpenSSL::PKey.generate_key("X25519")
164
+ ephemeral_public = ephemeral.raw_public_key
165
+ header = {
166
+ "v" => VERSION,
167
+ "type" => "bundle",
168
+ "from" => identity.public_identity.fingerprint,
169
+ "to" => recipient.fingerprint,
170
+ "eph" => Device.b64(ephemeral_public),
171
+ "issued_at" => issued_at,
172
+ "expires_at" => expires_at
173
+ }
174
+ key = derive_key(
175
+ dh(ephemeral, recipient.box_public_key),
176
+ salt: ephemeral_public + recipient.box_public_key,
177
+ info: BUNDLE_KEY_INFO
178
+ )
179
+ envelope = seal(header, BUNDLE_FIELDS, body, key) { |input| identity.sign(input) }
180
+ # The signer's public keys, so a device can trust the primary on first
181
+ # import. Bound to the signed "from" fingerprint; the name is a label.
182
+ signer = identity.public_identity
183
+ envelope["signer"] = {
184
+ "name" => signer.name,
185
+ "sign" => Device.b64(signer.sign_public_key),
186
+ "box" => Device.b64(signer.box_public_key)
187
+ }
188
+ JSON.generate(envelope)
189
+ end
190
+
191
+ # Device side. Returns [header, body]; raises Error. `trusted` is the
192
+ # list of primaries (PublicIdentity) this device accepts bundles from.
193
+ # For a primary not in that list, `confirm_signer` (if given) is called
194
+ # with its identity, only after the bundle's signature checked out; when
195
+ # it returns true the header carries "new_signer" for the caller to pin.
196
+ def open_bundle(envelope, identity:, trusted:, confirm_signer: nil)
197
+ header = envelope.slice(*BUNDLE_FIELDS)
198
+ raise Error, "Not a 2pass bundle" unless header["v"] == VERSION && header["type"] == "bundle"
199
+ unless header["to"] == identity.public_identity.fingerprint
200
+ raise Error, "This bundle was made for another device"
201
+ end
202
+
203
+ signer = trusted.find { |hub| hub.fingerprint == header["from"] }
204
+ new_signer = nil
205
+ if signer.nil? && confirm_signer && (candidate = embedded_signer(envelope, header["from"]))
206
+ raise Error, "Bundle signature is invalid" unless verify!(envelope, header, BUNDLE_FIELDS, candidate.sign_public_key)
207
+ raise Error, "Bundle not imported: the primary's pairing code was not confirmed" unless confirm_signer.call(candidate)
208
+
209
+ signer = new_signer = candidate
210
+ end
211
+ unless signer
212
+ raise Error, "This bundle was not made by a trusted primary. Import it in a terminal to confirm " \
213
+ "the primary's pairing code, or run: 2pass hub trust <primary-token>"
214
+ end
215
+ raise Error, "Bundle signature is invalid" unless verify!(envelope, header, BUNDLE_FIELDS, signer.sign_public_key)
216
+ unless header["issued_at"].is_a?(Integer) && header["expires_at"].is_a?(Integer)
217
+ raise Error, "Bundle has invalid dates"
218
+ end
219
+
220
+ ephemeral_public = public_key_bytes(header["eph"])
221
+ key = derive_key(
222
+ identity.derive(ephemeral_public),
223
+ salt: ephemeral_public + identity.public_identity.box_public_key,
224
+ info: BUNDLE_KEY_INFO
225
+ )
226
+ body = JSON.parse(decrypt(envelope, header, BUNDLE_FIELDS, key))
227
+ raise Error, "Bundle content is invalid" unless body.is_a?(Hash)
228
+
229
+ [header.merge("signer" => signer.name, "new_signer" => new_signer).compact, body]
230
+ rescue JSON::ParserError, OpenSSL::PKey::PKeyError, ArgumentError, TypeError
231
+ raise Error, "Bundle could not be decrypted"
232
+ end
233
+
234
+ # The signer identity a bundle carries, if its keys match the signed
235
+ # sender fingerprint.
236
+ def embedded_signer(envelope, fingerprint)
237
+ data = envelope["signer"]
238
+ return nil unless data.is_a?(Hash)
239
+
240
+ name = data["name"].to_s
241
+ name = "primary" unless Device::NAME_PATTERN.match?(name)
242
+ candidate = Device::PublicIdentity.new(
243
+ name: name,
244
+ sign_public_key: Device.unb64(data["sign"]),
245
+ box_public_key: Device.unb64(data["box"])
246
+ )
247
+ return nil unless candidate.sign_public_key.bytesize == 32 && candidate.box_public_key.bytesize == 32
248
+
249
+ candidate.fingerprint == fingerprint ? candidate : nil
250
+ end
251
+
252
+ def dh(private_key, peer_public_bytes)
253
+ shared = private_key.derive(OpenSSL::PKey.new_raw_public_key("X25519", peer_public_bytes))
254
+ # Reject low-order peer keys (all-zero shared secret).
255
+ raise Error, "Invalid key exchange" if shared.bytes.all?(&:zero?)
256
+
257
+ shared
258
+ end
259
+
260
+ private
261
+
262
+ def seal(header, fields, body, key)
263
+ cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
264
+ cipher.key = key
265
+ nonce = cipher.random_iv
266
+ cipher.auth_data = canonical(header, fields)
267
+ ciphertext = cipher.update(JSON.generate(body)) + cipher.final
268
+ tag = cipher.auth_tag
269
+ signature = yield signing_input(header, fields, nonce, ciphertext, tag)
270
+
271
+ header.merge(
272
+ "nonce" => Device.b64(nonce),
273
+ "ciphertext" => Device.b64(ciphertext),
274
+ "tag" => Device.b64(tag),
275
+ "sig" => Device.b64(signature)
276
+ )
277
+ end
278
+
279
+ def decrypt(envelope, header, fields, key)
280
+ cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
281
+ cipher.key = key
282
+ cipher.iv = Device.unb64(envelope.fetch("nonce"))
283
+ cipher.auth_tag = Device.unb64(envelope.fetch("tag"))
284
+ cipher.auth_data = canonical(header, fields)
285
+ cipher.update(Device.unb64(envelope.fetch("ciphertext"))) + cipher.final
286
+ rescue OpenSSL::Cipher::CipherError, KeyError
287
+ raise Error, "Decryption failed"
288
+ end
289
+
290
+ def verify!(envelope, header, fields, sign_public_key)
291
+ input = signing_input(
292
+ header, fields,
293
+ Device.unb64(envelope["nonce"]),
294
+ Device.unb64(envelope["ciphertext"]),
295
+ Device.unb64(envelope["tag"])
296
+ )
297
+ OpenSSL::PKey.new_raw_public_key("ED25519", sign_public_key).verify(nil, Device.unb64(envelope["sig"]), input)
298
+ rescue OpenSSL::PKey::PKeyError, ArgumentError, TypeError
299
+ false
300
+ end
301
+
302
+ def signing_input(header, fields, nonce, ciphertext, tag)
303
+ SIGNATURE_CONTEXT + canonical(header, fields) +
304
+ [nonce.bytesize, ciphertext.bytesize, tag.bytesize].pack("N3") + nonce + ciphertext + tag
305
+ end
306
+
307
+ def canonical(header, fields)
308
+ JSON.generate(fields.map { |field| [field, header[field]] })
309
+ end
310
+
311
+ def derive_key(shared, salt:, info:)
312
+ OpenSSL::KDF.hkdf(shared, salt: salt, info: info, length: 32, hash: "SHA256")
313
+ end
314
+
315
+ def public_key_bytes(b64)
316
+ bytes = Device.unb64(b64)
317
+ raise Error, "Invalid ephemeral key" unless bytes.bytesize == 32
318
+
319
+ bytes
320
+ end
321
+ end
322
+ end
323
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+
6
+ module TwoPass
7
+ # Read-modify-write of a small JSON object under an exclusive flock. The hub
8
+ # runs one `serve` process per request, so shared state (replay cache,
9
+ # approvals) must be updated atomically across processes.
10
+ module LockedJsonFile
11
+ def self.update(path)
12
+ FileUtils.mkdir_p(File.dirname(path))
13
+ File.open(path, File::RDWR | File::CREAT, 0o600) do |file|
14
+ file.flock(File::LOCK_EX)
15
+ content = file.read
16
+ data = begin
17
+ parsed = content.empty? ? {} : JSON.parse(content)
18
+ parsed.is_a?(Hash) ? parsed : {}
19
+ rescue JSON::ParserError
20
+ {}
21
+ end
22
+
23
+ result = yield data
24
+
25
+ file.rewind
26
+ file.truncate(0)
27
+ file.write(JSON.generate(data))
28
+ file.flush
29
+ result
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "yaml"
5
+
6
+ module TwoPass
7
+ # Edits broker-policy.yml for the common case: giving a device read access
8
+ # (get/list, all ids, any purpose) to whole vault/env pairs. Anything finer
9
+ # (specific ids, purposes, actions, approvals) is edited by hand.
10
+ #
11
+ # Rewriting YAML drops comments, so the previous file is kept as .bak.
12
+ class Policy
13
+ # Built fresh each time: shared arrays would make YAML.dump emit aliases,
14
+ # which the broker refuses to load (aliases: false).
15
+ def self.default_grant
16
+ {"ids" => "*", "operations" => %w[get list], "purposes" => ["*"], "allow_reveal" => true}
17
+ end
18
+ VAULT_FILE = /\A(?<name>.+?)\.yml(?:\.enc)?\z/
19
+ NOT_VAULTS = %w[config devices broker-policy].freeze
20
+
21
+ Target = Data.define(:vault, :env) do
22
+ def to_s = env ? "#{vault}:#{env}" : vault
23
+ end
24
+
25
+ def initialize(path: Broker.default_policy_path)
26
+ @path = path
27
+ end
28
+
29
+ def self.parse_target(spec)
30
+ vault, env, extra = spec.to_s.split(":")
31
+ if vault.to_s.empty? || extra || spec.to_s.end_with?(":")
32
+ raise ArgumentError, "Invalid vault #{spec.inspect}: use <vault> or <vault>:<env>"
33
+ end
34
+
35
+ Target.new(vault: vault, env: env)
36
+ end
37
+
38
+ # Vault/env pairs present on this machine (~/.2pass and the shared folder).
39
+ def self.available_targets
40
+ [TwoPass::VAULT_DIR, TwoPass.shared_dir].compact.uniq.flat_map do |dir|
41
+ Dir.children(dir).filter_map do |file|
42
+ match = VAULT_FILE.match(file)
43
+ next unless match && File.exist?(File.join(dir, file))
44
+
45
+ vault, env = match[:name].split(".", 2)
46
+ next if NOT_VAULTS.include?(vault) && env.nil?
47
+
48
+ Target.new(vault: vault, env: env)
49
+ end
50
+ rescue Errno::ENOENT
51
+ []
52
+ end.uniq.sort_by { |t| [t.vault, t.env.to_s] }
53
+ end
54
+
55
+ def actor?(actor)
56
+ actors.key?(actor)
57
+ end
58
+
59
+ def grants(actor)
60
+ Array(actors.dig(actor, "grants"))
61
+ end
62
+
63
+ # Adds read grants for `targets`, creating the actor if needed. Returns the
64
+ # targets actually added (already-granted ones are skipped).
65
+ def grant(actor, targets)
66
+ available = self.class.available_targets
67
+ unknown = targets.reject { |t| available.include?(t) }
68
+ raise "Vault not found on this machine: #{unknown.join(', ')}" if unknown.any?
69
+
70
+ data = load
71
+ entry = (data["actors"][actor] ||= {"grants" => []})
72
+ entry["grants"] ||= []
73
+ added = targets.uniq.reject { |t| entry["grants"].any? { |g| covers?(g, t) } }
74
+ added.each do |t|
75
+ entry["grants"] << {"vault" => t.vault, "env" => t.env}.compact.merge(self.class.default_grant)
76
+ end
77
+ save(data) if added.any? || !actors.key?(actor)
78
+ added
79
+ end
80
+
81
+ def describe(actor = nil)
82
+ names = actor ? [actor] : actors.keys.sort
83
+ rows = names.flat_map do |name|
84
+ list = grants(name)
85
+ next [[name, "(no grants)", "", "", ""]] if list.empty?
86
+
87
+ list.map do |g|
88
+ ids = g["ids"] == "*" ? "all" : Array(g["ids"]).join(", ")
89
+ extra = []
90
+ extra << "needs approval" if g["require_approval"] == true
91
+ extra << "actions: #{g['actions'].keys.join(', ')}" if g["actions"].is_a?(Hash) && g["actions"].any?
92
+ [name, Target.new(vault: g["vault"].to_s, env: g["env"]).to_s, ids,
93
+ Array(g["operations"]).join(", ") + (g["allow_reveal"] == true ? "" : " (no reveal)"), extra.join("; ")]
94
+ end
95
+ end
96
+ return "No actors in #{@path}." if rows.empty?
97
+
98
+ Terminal::Table.new(headings: ["Actor", "Vault", "Secrets", "Operations", "Notes"], rows: rows).to_s
99
+ end
100
+
101
+ private
102
+
103
+ def actors
104
+ load["actors"]
105
+ end
106
+
107
+ def load
108
+ data = File.file?(@path) ? (YAML.safe_load_file(@path, aliases: false) || {}) : {}
109
+ raise "#{@path} must be a YAML mapping" unless data.is_a?(Hash)
110
+
111
+ data["actors"] ||= {}
112
+ data
113
+ end
114
+
115
+ def save(data)
116
+ FileUtils.mkdir_p(File.dirname(@path))
117
+ FileUtils.cp(@path, "#{@path}.bak") if File.file?(@path)
118
+ Encryption.write_atomic(@path, YAML.dump(data))
119
+ end
120
+
121
+ # An existing grant already gives full read access to this vault/env.
122
+ def covers?(grant, target)
123
+ grant["vault"].to_s == target.vault && (grant["env"].to_s.empty? ? nil : grant["env"].to_s) == target.env &&
124
+ grant["ids"] == "*" && grant["allow_reveal"] == true && grant["require_approval"] != true &&
125
+ (Array(grant["operations"]) & %w[get list *]).any?
126
+ end
127
+ end
128
+ end