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.
- checksums.yaml +4 -4
- data/README.md +421 -7
- data/bin/2pass +331 -6
- data/lib/2pass/approvals.rb +128 -0
- data/lib/2pass/broker.rb +462 -0
- data/lib/2pass/bundle.rb +289 -0
- data/lib/2pass/device.rb +207 -0
- data/lib/2pass/device_cache.rb +85 -0
- data/lib/2pass/device_registry.rb +131 -0
- data/lib/2pass/encryption.rb +277 -0
- data/lib/2pass/envelope.rb +323 -0
- data/lib/2pass/locked_json_file.rb +33 -0
- data/lib/2pass/policy.rb +128 -0
- data/lib/2pass/remote.rb +387 -0
- data/lib/2pass/replay_cache.rb +27 -0
- data/lib/2pass/server.rb +84 -0
- data/lib/2pass/version.rb +1 -1
- data/lib/2pass.rb +296 -19
- metadata +15 -2
data/lib/2pass/bundle.rb
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "time"
|
|
5
|
+
|
|
6
|
+
module TwoPass
|
|
7
|
+
# Sealed bundles: a primary machine packs the secrets a device is granted,
|
|
8
|
+
# encrypts them to that device's key and signs them. The result is plain
|
|
9
|
+
# text that can travel over any channel (copy/paste, AirDrop, USB, a
|
|
10
|
+
# Syncthing folder): only the device can open it and nobody can alter it.
|
|
11
|
+
#
|
|
12
|
+
# No connection between machines is needed. The trade-off: a bundle can't be
|
|
13
|
+
# recalled once delivered; it stops being used when it expires.
|
|
14
|
+
module Bundle
|
|
15
|
+
ARMOR_BEGIN = "-----BEGIN 2PASS BUNDLE-----"
|
|
16
|
+
ARMOR_END = "-----END 2PASS BUNDLE-----"
|
|
17
|
+
FILE_SUFFIX = ".2pass-bundle"
|
|
18
|
+
DEFAULT_EXPIRY_DAYS = 14
|
|
19
|
+
|
|
20
|
+
class Error < StandardError; end
|
|
21
|
+
|
|
22
|
+
Export = Data.define(:armored, :path, :summary)
|
|
23
|
+
|
|
24
|
+
# Decrypted bundle content on the device.
|
|
25
|
+
class Contents
|
|
26
|
+
attr_reader :header
|
|
27
|
+
|
|
28
|
+
def initialize(header, body)
|
|
29
|
+
@header = header
|
|
30
|
+
@body = body
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def issued_at = Time.at(header["issued_at"]).utc
|
|
34
|
+
def expires_at = Time.at(header["expires_at"]).utc
|
|
35
|
+
|
|
36
|
+
def expired?(now = Time.now)
|
|
37
|
+
header["expires_at"] <= now.to_i
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def vaults
|
|
41
|
+
Array(@body["vaults"])
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def entries(vault, env)
|
|
45
|
+
found = vaults.find { |v| v["vault"] == vault.to_s && v["env"] == env&.to_s }
|
|
46
|
+
raise Error, "#{Bundle.describe(vault, env)} is not in this device's bundle" unless found
|
|
47
|
+
|
|
48
|
+
Array(found["entries"]).map { |e| {id: e["id"], value: e["value"]} }
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def value(vault, env, id)
|
|
52
|
+
entry = entries(vault, env).find { |e| e[:id] == id }
|
|
53
|
+
raise "Entry not found" unless entry
|
|
54
|
+
|
|
55
|
+
entry[:value]
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def summary
|
|
59
|
+
lines = vaults.map { |v| " #{Bundle.describe(v['vault'], v['env'])}: #{Array(v['entries']).map { |e| e['id'] }.join(', ')}" }
|
|
60
|
+
<<~TEXT.chomp
|
|
61
|
+
Bundle from #{header['signer']}, issued #{issued_at.iso8601}, expires #{expires_at.iso8601}
|
|
62
|
+
#{lines.join("\n")}
|
|
63
|
+
TEXT
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
class << self
|
|
68
|
+
# --- primary side --------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def export(device_name, expires_in_days: DEFAULT_EXPIRY_DAYS, to: nil, now: Time.now)
|
|
71
|
+
identity = Device.local_identity
|
|
72
|
+
registry = DeviceRegistry.new
|
|
73
|
+
device = registry.devices.find { |d| d["name"] == device_name }
|
|
74
|
+
raise Error, "Unknown device: #{device_name}. Approve it first: 2pass device approve <token>" unless device
|
|
75
|
+
|
|
76
|
+
status = registry.status(device, now: now)
|
|
77
|
+
raise Error, "Device #{device_name} is #{status}; it can't receive a bundle" unless status == "active"
|
|
78
|
+
unless expires_in_days.is_a?(Integer) && expires_in_days.positive?
|
|
79
|
+
raise Error, "Bundle expiry must be a positive number of days"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
contents = Broker.new.bundle_contents(device_name)
|
|
83
|
+
if contents[:vaults].empty?
|
|
84
|
+
raise Error, "Nothing to export: #{Broker.default_policy_path} grants #{device_name} no secrets " \
|
|
85
|
+
"with get/list and allow_reveal (grants that require approval are never bundled)"
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
expires_at = now.to_i + expires_in_days * 86_400
|
|
89
|
+
capped = false
|
|
90
|
+
if device["expires_at"] && Time.iso8601(device["expires_at"]).to_i < expires_at
|
|
91
|
+
expires_at = Time.iso8601(device["expires_at"]).to_i
|
|
92
|
+
capped = true
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
recipient = Device::PublicIdentity.new(
|
|
96
|
+
name: device_name,
|
|
97
|
+
sign_public_key: Device.unb64(device["sign_public_key"]),
|
|
98
|
+
box_public_key: Device.unb64(device["box_public_key"])
|
|
99
|
+
)
|
|
100
|
+
document = Envelope.seal_bundle(
|
|
101
|
+
{"device" => device_name, "vaults" => contents[:vaults]},
|
|
102
|
+
identity: identity, recipient: recipient, issued_at: now.to_i, expires_at: expires_at
|
|
103
|
+
)
|
|
104
|
+
armored = armor(document)
|
|
105
|
+
|
|
106
|
+
path = nil
|
|
107
|
+
if to
|
|
108
|
+
dir = File.expand_path(to)
|
|
109
|
+
raise Error, "Folder does not exist: #{dir}" unless File.directory?(dir)
|
|
110
|
+
|
|
111
|
+
path = File.join(dir, "#{device_name}.#{identity.name}#{FILE_SUFFIX}")
|
|
112
|
+
Encryption.write_atomic(path, armored)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
Export.new(armored: armored, path: path, summary: export_summary(device_name, contents, expires_at, capped, path))
|
|
116
|
+
rescue Broker::Error => e
|
|
117
|
+
raise Error, e.message
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# --- device side ---------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def store_path
|
|
123
|
+
File.join(TwoPass::VAULT_DIR, "bundle#{FILE_SUFFIX}")
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Verifies and stores a bundle. Refuses expired bundles and bundles not
|
|
127
|
+
# newer than the one already installed (no rollback to stale secrets).
|
|
128
|
+
# `confirm_signer` (interactive callers only) is asked about a primary
|
|
129
|
+
# this device doesn't trust yet; see Envelope.open_bundle.
|
|
130
|
+
def import(text, now: Time.now, confirm_signer: nil)
|
|
131
|
+
contents = open_text(text, confirm_signer: confirm_signer)
|
|
132
|
+
raise Error, "This bundle expired on #{contents.expires_at.iso8601}" if contents.expired?(now)
|
|
133
|
+
|
|
134
|
+
if (installed = current_unchecked) && contents.header["issued_at"] <= installed.header["issued_at"]
|
|
135
|
+
raise Error, "This bundle (issued #{contents.issued_at.iso8601}) is not newer than the installed one " \
|
|
136
|
+
"(issued #{installed.issued_at.iso8601})"
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
FileUtils.mkdir_p(TwoPass::VAULT_DIR)
|
|
140
|
+
pinned = contents.header["new_signer"] && Remote.pin_bundle_signer(contents.header["new_signer"])
|
|
141
|
+
Encryption.write_atomic(store_path, armor_normalize(text))
|
|
142
|
+
message = +"Imported. #{contents.summary}"
|
|
143
|
+
message << "\nNow trusting #{pinned} for bundles." if pinned
|
|
144
|
+
message
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# Imports the newest valid bundle for this device found in `dir`
|
|
148
|
+
# (e.g. a Syncthing folder). Returns a message.
|
|
149
|
+
def import_from(dir, now: Time.now, only_newer_files: false, confirm_signer: nil)
|
|
150
|
+
dir = File.expand_path(dir)
|
|
151
|
+
raise Error, "Folder does not exist: #{dir}" unless File.directory?(dir)
|
|
152
|
+
|
|
153
|
+
since = only_newer_files && File.file?(store_path) ? File.mtime(store_path) : nil
|
|
154
|
+
installed = current_unchecked
|
|
155
|
+
candidates = Dir[File.join(dir, "*#{FILE_SUFFIX}*")].filter_map do |path|
|
|
156
|
+
next if since && File.mtime(path) <= since
|
|
157
|
+
|
|
158
|
+
contents = open_text(File.read(path), confirm_signer: confirm_signer && ->(_signer) { true })
|
|
159
|
+
next if contents.expired?(now)
|
|
160
|
+
next if installed && contents.header["issued_at"] <= installed.header["issued_at"]
|
|
161
|
+
|
|
162
|
+
[contents, path]
|
|
163
|
+
rescue Error, SystemCallError
|
|
164
|
+
nil # another device's bundle, a damaged file, a sync temp file...
|
|
165
|
+
end
|
|
166
|
+
return "No newer bundle for this device in #{dir}." if candidates.empty?
|
|
167
|
+
|
|
168
|
+
_contents, path = candidates.max_by { |contents, _| contents.header["issued_at"] }
|
|
169
|
+
import(File.read(path), now: now, confirm_signer: confirm_signer)
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# Remembers a folder to check for newer bundles before each get/list.
|
|
173
|
+
def set_source(dir)
|
|
174
|
+
dir = File.expand_path(dir)
|
|
175
|
+
raise Error, "Folder does not exist: #{dir}" unless File.directory?(dir)
|
|
176
|
+
|
|
177
|
+
Encryption.save_config(Encryption.config.merge("bundle_source" => dir))
|
|
178
|
+
"get and list will pick up newer bundles from #{dir}."
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def auto_import(now: Time.now)
|
|
182
|
+
dir = Encryption.config["bundle_source"]
|
|
183
|
+
return unless dir && File.directory?(dir)
|
|
184
|
+
|
|
185
|
+
message = import_from(dir, now: now, only_newer_files: true)
|
|
186
|
+
$stderr.puts message if message.start_with?("Imported")
|
|
187
|
+
rescue Error => e
|
|
188
|
+
$stderr.puts "Warning: could not import a bundle from #{dir}: #{e.message}"
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def present?
|
|
192
|
+
File.file?(store_path)
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# The installed bundle, or an error explaining what to do.
|
|
196
|
+
def current!(now: Time.now)
|
|
197
|
+
auto_import(now: now)
|
|
198
|
+
contents = current_unchecked
|
|
199
|
+
unless contents
|
|
200
|
+
raise Error, "No bundle on this device. On a primary run: 2pass bundle export #{Device.local_identity.name}, " \
|
|
201
|
+
"then here: 2pass bundle import"
|
|
202
|
+
end
|
|
203
|
+
if contents.expired?(now)
|
|
204
|
+
raise Error, "The bundle on this device expired on #{contents.expires_at.iso8601}. " \
|
|
205
|
+
"Export a new one on a primary and import it here."
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
contents
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def status(now: Time.now)
|
|
212
|
+
contents = current_unchecked
|
|
213
|
+
return "No bundle on this device." unless contents
|
|
214
|
+
|
|
215
|
+
state = contents.expired?(now) ? "EXPIRED" : "valid"
|
|
216
|
+
source = Encryption.config["bundle_source"]
|
|
217
|
+
text = +"#{contents.summary}\nStatus: #{state}"
|
|
218
|
+
text << "\nAuto pickup from: #{source}" if source
|
|
219
|
+
text
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def describe(vault, env)
|
|
223
|
+
env ? "#{vault} (#{env})" : vault.to_s
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
private
|
|
227
|
+
|
|
228
|
+
def current_unchecked
|
|
229
|
+
return nil unless present?
|
|
230
|
+
|
|
231
|
+
open_text(File.read(store_path))
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def open_text(text, confirm_signer: nil)
|
|
235
|
+
envelope = JSON.parse(dearmor(text))
|
|
236
|
+
raise Error, "Not a 2pass bundle" unless envelope.is_a?(Hash)
|
|
237
|
+
|
|
238
|
+
trusted = Remote.trusted_identities
|
|
239
|
+
if trusted.empty? && confirm_signer.nil?
|
|
240
|
+
raise Error, "This device trusts no primary yet. Import a bundle in a terminal to confirm " \
|
|
241
|
+
"the primary's pairing code, or run: 2pass hub trust <primary-token>"
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
header, body = Envelope.open_bundle(
|
|
245
|
+
envelope, identity: Device.local_identity, trusted: trusted, confirm_signer: confirm_signer
|
|
246
|
+
)
|
|
247
|
+
Contents.new(header, body)
|
|
248
|
+
rescue JSON::ParserError, ArgumentError
|
|
249
|
+
raise Error, "Not a 2pass bundle"
|
|
250
|
+
rescue Envelope::Error => e
|
|
251
|
+
raise Error, e.message
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def armor(document)
|
|
255
|
+
body = [document].pack("m0").scan(/.{1,64}/).join("\n")
|
|
256
|
+
"#{ARMOR_BEGIN}\n#{body}\n#{ARMOR_END}\n"
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
def dearmor(text)
|
|
260
|
+
text = text.to_s
|
|
261
|
+
start = text.index(ARMOR_BEGIN)
|
|
262
|
+
finish = text.index(ARMOR_END)
|
|
263
|
+
raise Error, "Not a 2pass bundle (missing #{ARMOR_BEGIN})" unless start && finish && finish > start
|
|
264
|
+
|
|
265
|
+
# Anything that isn't base64 is dropped (line breaks, "> " email
|
|
266
|
+
# quoting...); the signature catches any real change.
|
|
267
|
+
text[(start + ARMOR_BEGIN.length)...finish].gsub(%r{[^A-Za-z0-9+/=]}, "").unpack1("m0")
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
def armor_normalize(text)
|
|
271
|
+
armor(dearmor(text))
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
def export_summary(device_name, contents, expires_at, capped, path)
|
|
275
|
+
lines = contents[:vaults].map do |v|
|
|
276
|
+
" #{describe(v['vault'], v['env'])}: #{v['entries'].map { |e| e['id'] }.join(', ')}"
|
|
277
|
+
end
|
|
278
|
+
text = +"Bundle for #{device_name}, expires #{Time.at(expires_at).utc.iso8601}"
|
|
279
|
+
text << " (capped at the device's approval expiry)" if capped
|
|
280
|
+
text << "\n#{lines.join("\n")}"
|
|
281
|
+
text << "\nSkipped #{contents[:skipped_gated]} grant(s) that require approval." if contents[:skipped_gated].positive?
|
|
282
|
+
text << "\nMissing vault(s): #{contents[:missing].join(', ')}" if contents[:missing].any?
|
|
283
|
+
text << "\nWrote #{path}" if path
|
|
284
|
+
text << "\nIf #{device_name} is lost, rotate the secrets listed above."
|
|
285
|
+
text
|
|
286
|
+
end
|
|
287
|
+
end
|
|
288
|
+
end
|
|
289
|
+
end
|
data/lib/2pass/device.rb
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "socket"
|
|
7
|
+
|
|
8
|
+
module TwoPass
|
|
9
|
+
# Device identity.
|
|
10
|
+
#
|
|
11
|
+
# Every machine (hub or client) owns one identity: an Ed25519 signing key
|
|
12
|
+
# (authenticates requests) and an X25519 key (lets the hub encrypt replies to
|
|
13
|
+
# this device). The private half never leaves the machine; it lives in the
|
|
14
|
+
# Keychain or a 0600 file, like the master key.
|
|
15
|
+
#
|
|
16
|
+
# A device *is* its public keys: the fingerprint is a hash of both, and the
|
|
17
|
+
# human-readable pairing code is derived from the fingerprint. Names are
|
|
18
|
+
# labels only. Pairing is safe when the code shown on the device is compared
|
|
19
|
+
# with the code shown by the hub before approval.
|
|
20
|
+
module Device
|
|
21
|
+
TOKEN_PREFIX = "2pass-device:"
|
|
22
|
+
TOKEN_VERSION = 1
|
|
23
|
+
TOKEN_SIGNATURE_CONTEXT = "2pass device token v1\0"
|
|
24
|
+
FINGERPRINT_CONTEXT = "2pass device fingerprint v1\0"
|
|
25
|
+
CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" # Crockford base32
|
|
26
|
+
CODE_BITS = 60
|
|
27
|
+
NAME_PATTERN = /\A[a-z0-9][a-z0-9._-]{0,62}\z/i
|
|
28
|
+
|
|
29
|
+
class Error < StandardError; end
|
|
30
|
+
|
|
31
|
+
PublicIdentity = Data.define(:name, :sign_public_key, :box_public_key) do
|
|
32
|
+
def fingerprint
|
|
33
|
+
Device.fingerprint(sign_public_key, box_public_key)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def pairing_code
|
|
37
|
+
Device.pairing_code(fingerprint)
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
class Identity
|
|
42
|
+
attr_reader :name
|
|
43
|
+
|
|
44
|
+
def self.generate(name)
|
|
45
|
+
new(name, OpenSSL::PKey.generate_key("ED25519"), OpenSSL::PKey.generate_key("X25519"))
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def self.from_bytes(name, bytes)
|
|
49
|
+
unless bytes.bytesize == 64
|
|
50
|
+
raise Error, "Device key has an invalid length"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
new(
|
|
54
|
+
name,
|
|
55
|
+
OpenSSL::PKey.new_raw_private_key("ED25519", bytes.byteslice(0, 32)),
|
|
56
|
+
OpenSSL::PKey.new_raw_private_key("X25519", bytes.byteslice(32, 32))
|
|
57
|
+
)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def initialize(name, sign_key, box_key)
|
|
61
|
+
@name = name
|
|
62
|
+
@sign_key = sign_key
|
|
63
|
+
@box_key = box_key
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def to_bytes
|
|
67
|
+
@sign_key.raw_private_key + @box_key.raw_private_key
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def public_identity
|
|
71
|
+
PublicIdentity.new(name: name, sign_public_key: @sign_key.raw_public_key, box_public_key: @box_key.raw_public_key)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def sign(message)
|
|
75
|
+
@sign_key.sign(nil, message)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# X25519 shared secret between this device's static key and a peer key.
|
|
79
|
+
def derive(peer_public_bytes)
|
|
80
|
+
Envelope.dh(@box_key, peer_public_bytes)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Self-signed, so the token proves possession of the signing key and
|
|
84
|
+
# binds both public keys together. It is not secret.
|
|
85
|
+
def pairing_token
|
|
86
|
+
pub = public_identity
|
|
87
|
+
payload = {
|
|
88
|
+
"v" => TOKEN_VERSION,
|
|
89
|
+
"name" => name,
|
|
90
|
+
"sign" => Device.b64(pub.sign_public_key),
|
|
91
|
+
"box" => Device.b64(pub.box_public_key)
|
|
92
|
+
}
|
|
93
|
+
signature = sign(Device.token_signing_input(payload))
|
|
94
|
+
TOKEN_PREFIX + Device.b64url(JSON.generate(payload.merge("sig" => Device.b64(signature))))
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
class << self
|
|
99
|
+
def default_name
|
|
100
|
+
Socket.gethostname.split(".").first.downcase.gsub(/[^a-z0-9._-]/, "-")
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def configured?
|
|
104
|
+
!Encryption.config.dig("identity", "key_store").nil?
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def init(name: nil, key_store: nil)
|
|
108
|
+
if configured?
|
|
109
|
+
raise Error, "This machine already has a device identity. Refusing to replace it."
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
name ||= default_name
|
|
113
|
+
validate_name!(name)
|
|
114
|
+
key_store ||= Encryption.default_key_store
|
|
115
|
+
|
|
116
|
+
identity = Identity.generate(name)
|
|
117
|
+
Encryption.key_store_for(key_store, purpose: :device).write(identity.to_bytes)
|
|
118
|
+
Encryption.save_config(Encryption.config.merge("identity" => {"name" => name, "key_store" => key_store}))
|
|
119
|
+
identity
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def local_identity
|
|
123
|
+
settings = Encryption.config["identity"]
|
|
124
|
+
unless settings && settings["key_store"]
|
|
125
|
+
raise Error, "This machine has no device identity yet. Run: 2pass device init"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
Identity.from_bytes(settings["name"], Encryption.key_store_for(settings["key_store"], purpose: :device).read)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def parse_token(token)
|
|
132
|
+
token = token.to_s.strip
|
|
133
|
+
raise Error, "Not a 2pass device token" unless token.start_with?(TOKEN_PREFIX)
|
|
134
|
+
|
|
135
|
+
data = JSON.parse(unb64url(token.delete_prefix(TOKEN_PREFIX)))
|
|
136
|
+
raise Error, "Unsupported device token version" unless data["v"] == TOKEN_VERSION
|
|
137
|
+
|
|
138
|
+
sign_public = unb64(data.fetch("sign"))
|
|
139
|
+
box_public = unb64(data.fetch("box"))
|
|
140
|
+
raise Error, "Device token has invalid keys" unless sign_public.bytesize == 32 && box_public.bytesize == 32
|
|
141
|
+
|
|
142
|
+
verifier = OpenSSL::PKey.new_raw_public_key("ED25519", sign_public)
|
|
143
|
+
payload = data.slice("v", "name", "sign", "box")
|
|
144
|
+
unless verifier.verify(nil, unb64(data.fetch("sig")), token_signing_input(payload))
|
|
145
|
+
raise Error, "Device token signature is invalid"
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
PublicIdentity.new(name: data["name"].to_s, sign_public_key: sign_public, box_public_key: box_public)
|
|
149
|
+
rescue JSON::ParserError, KeyError, ArgumentError, OpenSSL::PKey::PKeyError
|
|
150
|
+
raise Error, "Device token is malformed"
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def fingerprint(sign_public_key, box_public_key)
|
|
154
|
+
Digest::SHA256.hexdigest(FINGERPRINT_CONTEXT + sign_public_key + box_public_key)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# First 60 bits of the fingerprint as 12 Crockford base32 characters,
|
|
158
|
+
# e.g. "7F3K-92QX-M4TB".
|
|
159
|
+
def pairing_code(fingerprint)
|
|
160
|
+
value = fingerprint[0, 16].to_i(16) >> (64 - CODE_BITS)
|
|
161
|
+
chars = (CODE_BITS / 5).times.map { |i| CODE_ALPHABET[(value >> (CODE_BITS - 5 * (i + 1))) & 31] }
|
|
162
|
+
chars.each_slice(4).map(&:join).join("-")
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def describe_local
|
|
166
|
+
identity = local_identity
|
|
167
|
+
pub = identity.public_identity
|
|
168
|
+
<<~TEXT
|
|
169
|
+
Device: #{identity.name}
|
|
170
|
+
Pairing code: #{pub.pairing_code}
|
|
171
|
+
Fingerprint: #{pub.fingerprint}
|
|
172
|
+
|
|
173
|
+
Pairing token (give this to the hub; it is not secret):
|
|
174
|
+
#{identity.pairing_token}
|
|
175
|
+
TEXT
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def validate_name!(name)
|
|
179
|
+
unless NAME_PATTERN.match?(name.to_s)
|
|
180
|
+
raise Error, "Invalid device name #{name.inspect}: use letters, digits, '.', '_' or '-' (max 63)"
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def token_signing_input(payload)
|
|
185
|
+
TOKEN_SIGNATURE_CONTEXT + JSON.generate(payload.values_at("v", "name", "sign", "box"))
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def b64(bytes)
|
|
189
|
+
[bytes].pack("m0")
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def unb64(string)
|
|
193
|
+
string.to_s.unpack1("m0")
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
def b64url(bytes)
|
|
197
|
+
[bytes].pack("m0").tr("+/", "-_").delete("=")
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def unb64url(string)
|
|
201
|
+
padded = string.tr("-_", "+/")
|
|
202
|
+
padded += "=" * ((4 - padded.length % 4) % 4)
|
|
203
|
+
padded.unpack1("m0")
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "json"
|
|
5
|
+
require "openssl"
|
|
6
|
+
|
|
7
|
+
module TwoPass
|
|
8
|
+
# Short-lived cache of hub answers on a device (~/.2pass/cache/).
|
|
9
|
+
#
|
|
10
|
+
# The hub decides how long an answer may be cached (`cache_ttl` in the
|
|
11
|
+
# response, from the grant; capped by approvals and device expiry). Entries
|
|
12
|
+
# are AES-256-GCM encrypted under a key derived from this device's private
|
|
13
|
+
# key, and file names are HMACs of the request, so the directory reveals
|
|
14
|
+
# neither values nor which secrets were requested. The cache is wiped when
|
|
15
|
+
# the hub reports this device as no longer approved.
|
|
16
|
+
class DeviceCache
|
|
17
|
+
KEY_INFO = "2pass device cache v1"
|
|
18
|
+
|
|
19
|
+
def self.default_dir
|
|
20
|
+
File.join(TwoPass::VAULT_DIR, "cache")
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def initialize(identity:, dir: self.class.default_dir)
|
|
24
|
+
material = OpenSSL::KDF.hkdf(identity.to_bytes, salt: "", info: KEY_INFO, length: 64, hash: "SHA256")
|
|
25
|
+
@name_key = material.byteslice(0, 32)
|
|
26
|
+
@encryption_key = material.byteslice(32, 32)
|
|
27
|
+
@dir = dir
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def fetch(request, now: Time.now)
|
|
31
|
+
path = path_for(request)
|
|
32
|
+
return nil unless File.file?(path)
|
|
33
|
+
|
|
34
|
+
entry = JSON.parse(decrypt(File.binread(path), File.basename(path)))
|
|
35
|
+
if entry["expires_at"].to_i <= now.to_i
|
|
36
|
+
FileUtils.rm_f(path)
|
|
37
|
+
return nil
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
entry["response"]
|
|
41
|
+
rescue OpenSSL::Cipher::CipherError, JSON::ParserError, ArgumentError
|
|
42
|
+
FileUtils.rm_f(path)
|
|
43
|
+
nil
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def store(request, response, ttl:, now: Time.now)
|
|
47
|
+
return unless ttl.is_a?(Integer) && ttl.positive?
|
|
48
|
+
|
|
49
|
+
FileUtils.mkdir_p(@dir, mode: 0o700)
|
|
50
|
+
path = path_for(request)
|
|
51
|
+
entry = JSON.generate("expires_at" => now.to_i + ttl, "response" => response)
|
|
52
|
+
Encryption.write_atomic(path, encrypt(entry, File.basename(path)))
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def clear
|
|
56
|
+
FileUtils.rm_rf(@dir)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
private
|
|
60
|
+
|
|
61
|
+
def path_for(request)
|
|
62
|
+
File.join(@dir, OpenSSL::HMAC.hexdigest("SHA256", @name_key, JSON.generate(request.sort.to_h)))
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def encrypt(plaintext, name)
|
|
66
|
+
cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
|
|
67
|
+
cipher.key = @encryption_key
|
|
68
|
+
nonce = cipher.random_iv
|
|
69
|
+
cipher.auth_data = name
|
|
70
|
+
ciphertext = cipher.update(plaintext) + cipher.final
|
|
71
|
+
nonce + cipher.auth_tag + ciphertext
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def decrypt(blob, name)
|
|
75
|
+
raise ArgumentError, "truncated cache entry" if blob.bytesize < 28
|
|
76
|
+
|
|
77
|
+
cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
|
|
78
|
+
cipher.key = @encryption_key
|
|
79
|
+
cipher.iv = blob.byteslice(0, 12)
|
|
80
|
+
cipher.auth_tag = blob.byteslice(12, 16)
|
|
81
|
+
cipher.auth_data = name
|
|
82
|
+
cipher.update(blob.byteslice(28..)) + cipher.final
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|