melos 0.0.2 → 0.9.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.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +71 -11
  3. data/docs/roadmap.md +302 -0
  4. data/docs/validation.md +172 -0
  5. data/lib/melos/capabilities.rb +18 -0
  6. data/lib/melos/client.rb +255 -0
  7. data/lib/melos/credential/x509.rb +91 -0
  8. data/lib/melos/crypto.rb +109 -15
  9. data/lib/melos/epoch_secrets.rb +166 -0
  10. data/lib/melos/errors.rb +18 -0
  11. data/lib/melos/external_sender.rb +78 -0
  12. data/lib/melos/group/validation.rb +310 -0
  13. data/lib/melos/group.rb +1087 -0
  14. data/lib/melos/key_package_bundle.rb +67 -0
  15. data/lib/melos/persistence.rb +45 -0
  16. data/lib/melos/private_tree.rb +70 -0
  17. data/lib/melos/ratchet_tree.rb +407 -0
  18. data/lib/melos/secret_tree.rb +130 -88
  19. data/lib/melos/struct/base.rb +46 -20
  20. data/lib/melos/struct/structs.rb +205 -87
  21. data/lib/melos/tree.rb +4 -120
  22. data/lib/melos/vec.rb +20 -35
  23. data/lib/melos/version.rb +1 -1
  24. data/lib/melos.rb +13 -2
  25. metadata +18 -22
  26. data/lib/melos/key_schedule.rb +0 -62
  27. data/lib/melos/struct/ratchet_tree.rb +0 -324
  28. data/test_vectors/crypto-basics.json +0 -303
  29. data/test_vectors/deserialization.json +0 -58
  30. data/test_vectors/key-schedule.json +0 -926
  31. data/test_vectors/message-protection.json +0 -142
  32. data/test_vectors/messages.json +0 -5702
  33. data/test_vectors/passive-client-handling-commit.json +0 -2683
  34. data/test_vectors/passive-client-random.json +0 -2657
  35. data/test_vectors/passive-client-welcome.json +0 -814
  36. data/test_vectors/psk_secret.json +0 -2382
  37. data/test_vectors/secret-tree.json +0 -4846
  38. data/test_vectors/transcript-hashes.json +0 -58
  39. data/test_vectors/tree-math.json +0 -8276
  40. data/test_vectors/tree-operations.json +0 -47
  41. data/test_vectors/tree-validation.json +0 -11839
  42. data/test_vectors/treekem.json +0 -14877
  43. data/test_vectors/welcome.json +0 -51
@@ -0,0 +1,255 @@
1
+ require 'securerandom'
2
+ require_relative 'crypto'
3
+ require_relative 'key_package_bundle'
4
+ require_relative 'group'
5
+ require_relative 'external_sender'
6
+ require_relative 'struct/structs'
7
+
8
+ # A client (RFC 9420 Section 5.3): a long-lived identity, i.e. a signature key pair and a
9
+ # credential, plus what a client keeps across groups: the external PSKs it knows (8.4) and the
10
+ # KeyPackages it has published and may still be welcomed into a group with (10), and the
11
+ # resumption PSKs of groups it has replaced (8.6), for groups that resume them.
12
+ class Melos::Client
13
+ attr_reader :cipher_suite, :credential, :external_psks, :key_packages, :groups
14
+
15
+ # identity: for a basic credential
16
+ # credential: any other credential (Melos::Credential::X509.create_credential, say); its key is then
17
+ # signature_private_key, the private key of the certified public key, as MLS serializes it
18
+ # credential_types: the credential types this client's leaves claim to support (13.3), by default basic
19
+ # and its own; members of a group must all support every type in use
20
+ def initialize(cipher_suite_id, identity: '', credential: nil, signature_private_key: nil, credential_types: nil)
21
+ @cipher_suite = Melos::Crypto::CipherSuite.new(cipher_suite_id)
22
+ @signature_key_pair = signature_private_key ? @cipher_suite.pkey.deserialize_private_signature_key(signature_private_key) : Melos::Crypto.generate_signature_key_pair(@cipher_suite)
23
+ @credential = credential || Melos::Struct::Credential.create_basic_credential(identity)
24
+ @credential_types = credential_types || ([Melos::Constants::CredentialType::BASIC] | [@credential.credential_type])
25
+ @external_psks = {} # psk_id -> psk; shared by reference with the groups this client is in
26
+ @key_packages = {} # KeyPackageRef -> Melos::KeyPackageBundle, until used to join a group
27
+ @groups = {} # group_id -> Melos::Group this client created or joined
28
+ @resumption_psks = {} # [group_id, epoch] -> resumption_psk, of groups no longer in @groups (8.6)
29
+ end
30
+
31
+ # 7.2: the Capabilities this client's leaves carry unless told otherwise
32
+ def default_capabilities
33
+ Melos::Struct::Capabilities.import(Melos::Capabilities.new(credentials: @credential_types))
34
+ end
35
+
36
+ # 8.6: the resumption PSK of a group this client is or was in, or nil
37
+ def resumption_psk(group_id, epoch)
38
+ @groups[group_id]&.resumption_psks&.[](epoch) || @resumption_psks[[group_id, epoch]]
39
+ end
40
+
41
+ def signature_private_key
42
+ Melos::Crypto.serialize_private_key(@cipher_suite, @signature_key_pair)
43
+ end
44
+
45
+ def signature_public_key
46
+ Melos::Crypto.serialize_public_key(@cipher_suite, @signature_key_pair)
47
+ end
48
+
49
+ # 8.4: an external PSK that commits in this client's groups may reference
50
+ def add_external_psk(psk_id, psk)
51
+ @external_psks[psk_id] = psk
52
+ end
53
+
54
+ # 10: publish a KeyPackage. The bundle is kept so that a Welcome addressed to it can be processed.
55
+ def create_key_package(capabilities: nil, lifetime: nil, extensions: [])
56
+ bundle = Melos::KeyPackageBundle.generate(
57
+ @cipher_suite, signature_private_key: signature_private_key, signature_public_key: signature_public_key,
58
+ credential: @credential, capabilities: capabilities || default_capabilities, lifetime: lifetime, extensions: extensions
59
+ )
60
+ @key_packages[bundle.ref] = bundle
61
+ bundle
62
+ end
63
+
64
+ # 12.1.8: ask to join a group by proposing our own Add, as a new_member_proposal signed with the
65
+ # KeyPackage's key. A member who commits it sends a Welcome addressed to that KeyPackage, which
66
+ # #join_group then accepts. group_id and epoch are the group's current ones (from a GroupInfo, say).
67
+ # Returns [MLSMessage, KeyPackageBundle].
68
+ def create_new_member_proposal(group_id:, epoch:, authenticated_data: '', **key_package_options)
69
+ bundle = create_key_package(**key_package_options)
70
+ add = Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::ADD, add: Melos::Struct::Add.create(key_package: bundle.key_package))
71
+ sender = Melos::Struct::Sender.create_new_member(Melos::Constants::SenderType::NEW_MEMBER_PROPOSAL)
72
+ message = Melos::ExternalSender.sign_proposal(@cipher_suite, signature_private_key, add, sender,
73
+ group_id: group_id, epoch: epoch, authenticated_data: authenticated_data)
74
+ [message, bundle]
75
+ end
76
+
77
+ # 11: create a group with this client as its only member.
78
+ # options are passed to Melos::Group (credential_validator:, max_leaf_node_lifetime:, ...)
79
+ def create_group(group_id, extensions: [], **options)
80
+ bundle = Melos::KeyPackageBundle.generate(
81
+ @cipher_suite, signature_private_key: signature_private_key, signature_public_key: signature_public_key, credential: @credential,
82
+ capabilities: default_capabilities
83
+ )
84
+ ensure_group_id_free!(group_id)
85
+ store_group(Melos::Group.create(
86
+ @cipher_suite, group_id, bundle.key_package.leaf_node,
87
+ encryption_private_key: bundle.encryption_private_key, signature_private_key: signature_private_key,
88
+ extensions: extensions, external_psks: @external_psks, resumption_psk_lookup: method(:resumption_psk), **options
89
+ ))
90
+ end
91
+
92
+ # 11.2: create the group that replaces old_group after a ReInit was committed in it, with the ReInit's
93
+ # group_id, cipher suite (this client's) and extensions, and with the same members, given as fresh
94
+ # KeyPackages of every other member. Returns [new group, Welcome]; the new group is already in epoch 1.
95
+ # member_matcher: ->(old_leaf, new_leaf) { true/false }, whether two leaves are the same member
96
+ def reinit_group(old_group, key_packages, member_matcher: Melos::Group::DEFAULT_MEMBER_MATCHER, **options)
97
+ reinit = old_group.pending_reinit
98
+ raise Melos::StateError.new('no ReInit has been committed in this group') if reinit.nil?
99
+ raise ArgumentError.new("the ReInit is for cipher suite #{reinit.cipher_suite}; use a client of that suite") unless reinit.cipher_suite == @cipher_suite.suite_id
100
+ raise Melos::UnsupportedError.new("unsupported MLS version #{reinit.version}") unless reinit.version == Melos::Constants::Version::MLS10
101
+ new_leaves = key_packages.map { leaf_of(_1) } + [own_leaf]
102
+ old_group.ratchet_tree.each_leaf_node do |old_leaf, _index|
103
+ next if new_leaves.any? { member_matcher.call(old_leaf, _1) }
104
+ raise ArgumentError.new('every member of the old group needs a KeyPackage in the new one')
105
+ end
106
+ resume(old_group, key_packages, Melos::Constants::ResumptionPSKUsage::REINIT, reinit.group_id, reinit.extensions, options)
107
+ end
108
+
109
+ # 11.3: branch a subgroup of old_group's members, given as fresh KeyPackages, with a new group_id and
110
+ # the same cipher suite. Returns [new group, Welcome]; the new group is already in epoch 1.
111
+ def branch_group(old_group, key_packages, group_id:, extensions: old_group.extensions, member_matcher: Melos::Group::DEFAULT_MEMBER_MATCHER, **options)
112
+ raise ArgumentError.new('a branch keeps the cipher suite of its group') unless old_group.suite.suite_id == @cipher_suite.suite_id
113
+ old_leaves = []
114
+ old_group.ratchet_tree.each_leaf_node { |leaf_node, _index| old_leaves << leaf_node }
115
+ (key_packages.map { leaf_of(_1) } + [own_leaf]).each do |new_leaf|
116
+ next if old_leaves.any? { member_matcher.call(_1, new_leaf) }
117
+ raise ArgumentError.new('every member of a branch must be a member of the group it branches from')
118
+ end
119
+ resume(old_group, key_packages, Melos::Constants::ResumptionPSKUsage::BRANCH, group_id, extensions, options)
120
+ end
121
+
122
+ # 12.4.3.2: join a group by external commit, from a GroupInfo with an external_pub extension (see
123
+ # Melos::Group#group_info). The new group is merged and stored right away; send the commit, and if the
124
+ # Delivery Service rejects it, drop the group (groups.delete(group.group_id)) and try again with a fresh GroupInfo.
125
+ # remove: the leaf index of this client's earlier appearance in the group, to replace it (a "resync")
126
+ # psk_ids: external PSKs (added with #add_external_psk) to inject
127
+ # Returns [group, commit MLSMessage].
128
+ def join_by_external_commit(group_info, ratchet_tree: nil, remove: nil, psk_ids: [], authenticated_data: '', **options)
129
+ bundle = Melos::KeyPackageBundle.generate(
130
+ @cipher_suite, signature_private_key: signature_private_key, signature_public_key: signature_public_key, credential: @credential,
131
+ capabilities: default_capabilities
132
+ )
133
+ group, result = Melos::Group.join_by_external_commit(
134
+ @cipher_suite, group_info, signature_private_key: signature_private_key, leaf_node: bundle.key_package.leaf_node,
135
+ ratchet_tree: ratchet_tree, remove: remove, psk_ids: psk_ids, external_psks: @external_psks, authenticated_data: authenticated_data,
136
+ resumption_psk_lookup: method(:resumption_psk), **options
137
+ )
138
+ # a resync replaces this client's own earlier state of the group, which may still be here
139
+ ensure_group_id_free!(group.group_id) unless remove
140
+ group.merge_commit(result.staged)
141
+ store_group(group)
142
+ [group, result.commit]
143
+ end
144
+
145
+ # 12.4.3.1: join the group a Welcome adds us to, using whichever of our KeyPackages it is addressed to.
146
+ # That KeyPackage is then forgotten: its init key is single-use.
147
+ # resumed_groups: groups held elsewhere (by a client of another cipher suite, say) that a reinit or
148
+ # branch Welcome may resume; this client's own groups are always looked in
149
+ # member_matcher: as for #reinit_group, for the checks of 11.2 and 11.3
150
+ def join_group(welcome, ratchet_tree: nil, resumed_groups: [], member_matcher: Melos::Group::DEFAULT_MEMBER_MATCHER, **options)
151
+ welcome_struct = welcome.is_a?(Melos::Struct::MLSMessage) ? welcome.welcome : welcome
152
+ raise ArgumentError.new('not a Welcome message') if welcome_struct.nil?
153
+ bundle = welcome_struct.secrets.map(&:new_member).filter_map { @key_packages[_1] }.first
154
+ raise Melos::ProtocolError.new('Welcome is not addressed to any KeyPackage of this client') if bundle.nil?
155
+ group = Melos::Group.from_welcome(
156
+ @cipher_suite, welcome,
157
+ key_package: bundle.key_package, init_private_key: bundle.init_private_key,
158
+ encryption_private_key: bundle.encryption_private_key, signature_private_key: signature_private_key,
159
+ external_psks: @external_psks, ratchet_tree: ratchet_tree,
160
+ resumption_psk_lookup: ->(group_id, epoch) { resumed_groups.find { _1.group_id == group_id }&.resumption_psks&.[](epoch) || resumption_psk(group_id, epoch) },
161
+ resumed_group_lookup: ->(group_id) { resumed_groups.find { _1.group_id == group_id } || @groups[group_id] },
162
+ member_matcher: member_matcher, **options
163
+ )
164
+ ensure_group_id_free!(group.group_id)
165
+ @key_packages.delete(bundle.ref)
166
+ store_group(group)
167
+ end
168
+
169
+ # version of the Hash produced by #to_h
170
+ STATE_FORMAT = 1
171
+
172
+ # The client's whole state, its groups included, in the form Melos::Group#to_h describes.
173
+ # Private keys are in it: store it encrypted.
174
+ def to_h
175
+ {
176
+ format: STATE_FORMAT,
177
+ cipher_suite: @cipher_suite.suite_id,
178
+ signature_private_key: signature_private_key,
179
+ credential: @credential.raw, credential_types: @credential_types,
180
+ external_psks: @external_psks.to_a,
181
+ key_packages: @key_packages.map { |ref, bundle| [ref, bundle.to_h] },
182
+ groups: @groups.map { |group_id, group| [group_id, group.to_h(include_external_psks: false)] },
183
+ resumption_psks: @resumption_psks.map { |(group_id, epoch), psk| [group_id, epoch, psk] }
184
+ }
185
+ end
186
+
187
+ # A client from #to_h. group_options (credential_validator:, external_proposal_validator:) go to every group.
188
+ def self.from_h(hash, **group_options)
189
+ raise ArgumentError.new("unknown client state format #{hash[:format]}") unless hash[:format] == STATE_FORMAT
190
+ client = allocate
191
+ client.send(:restore_state, hash, group_options)
192
+ client
193
+ end
194
+
195
+ private
196
+
197
+ def restore_state(hash, group_options)
198
+ @cipher_suite = Melos::Crypto::CipherSuite.new(hash[:cipher_suite])
199
+ @signature_key_pair = @cipher_suite.pkey.deserialize_private_signature_key(hash[:signature_private_key])
200
+ @credential = Melos::Struct::Credential.new(hash[:credential])
201
+ @credential_types = hash[:credential_types] || [Melos::Constants::CredentialType::BASIC]
202
+ @external_psks = hash[:external_psks].to_h
203
+ @key_packages = hash[:key_packages].to_h { |ref, bundle| [ref, Melos::KeyPackageBundle.from_h(@cipher_suite, bundle)] }
204
+ @groups = hash[:groups].to_h do |group_id, group|
205
+ [group_id, Melos::Group.from_h(group, external_psks: @external_psks, resumption_psk_lookup: method(:resumption_psk), **group_options)]
206
+ end
207
+ @resumption_psks = (hash[:resumption_psks] || []).to_h { |group_id, epoch, psk| [[group_id, epoch], psk] }
208
+ end
209
+
210
+ # a group goes into @groups; one it replaces (removed or reinitialized, see #ensure_group_id_free!)
211
+ # leaves its resumption PSKs behind for groups that resume it (8.6)
212
+ def store_group(group)
213
+ if (replaced = @groups[group.group_id])
214
+ replaced.resumption_psks.each { |epoch, psk| @resumption_psks[[group.group_id, epoch]] = psk }
215
+ end
216
+ @groups[group.group_id] = group
217
+ end
218
+
219
+ # the options of #reinit_group and #branch_group that go to the new group's first commit rather than to the group
220
+ RESUMPTION_COMMIT_OPTIONS = %i[wire_format include_ratchet_tree path].freeze
221
+
222
+ # 11.2, 11.3: a new group of this client resuming old_group: created in epoch 0, then a first commit adding
223
+ # key_packages with the resumption PSK of old_group's current epoch, merged at once
224
+ def resume(old_group, key_packages, usage, group_id, extensions, options)
225
+ psk_id = Melos::Struct::PreSharedKeyID.create_resumption(
226
+ usage: usage, psk_group_id: old_group.group_id, psk_epoch: old_group.epoch, psk_nonce: SecureRandom.random_bytes(@cipher_suite.kdf.n_h)
227
+ )
228
+ psk = old_group.resumption_psks.fetch(old_group.epoch)
229
+ commit_options = options.slice(*RESUMPTION_COMMIT_OPTIONS)
230
+ group = create_group(group_id, extensions: extensions, **options.except(*RESUMPTION_COMMIT_OPTIONS))
231
+ result = group.send(:create_resumption_commit, key_packages, psk_id, psk, **commit_options)
232
+ group.merge_commit(result.staged)
233
+ [group, result.welcome]
234
+ end
235
+
236
+ def leaf_of(key_package)
237
+ (key_package.is_a?(Melos::Struct::MLSMessage) ? key_package.key_package : key_package).leaf_node
238
+ end
239
+
240
+ # a leaf standing for this client, for the membership checks of #reinit_group and #branch_group
241
+ def own_leaf
242
+ Melos::Struct::LeafNode.create(
243
+ encryption_key: '', signature_key: signature_public_key, credential: @credential, capabilities: nil,
244
+ leaf_node_source: nil, lifetime: nil, parent_hash: nil, extensions: [], signature: nil
245
+ )
246
+ end
247
+
248
+ # 12.4.3: a group_id MUST be unique among the groups this client is participating in;
249
+ # a group this client has been removed from no longer counts
250
+ def ensure_group_id_free!(group_id)
251
+ existing = @groups[group_id]
252
+ return if existing.nil? || !existing.active?
253
+ raise Melos::StateError.new('this client is already in a group with this group_id')
254
+ end
255
+ end
@@ -0,0 +1,91 @@
1
+ require 'openssl'
2
+ require_relative '../constants'
3
+ require_relative '../struct/structs'
4
+
5
+ module Melos::Credential; end
6
+
7
+ # X.509 credentials (RFC 9420 5.3, 5.3.1): building them, and an Authentication Service check that a
8
+ # group can use as its credential_validator:
9
+ #
10
+ # validator = Melos::Credential::X509.new(store: store) # an OpenSSL::X509::Store with the trusted roots
11
+ # client.create_group(group_id, credential_validator: validator)
12
+ #
13
+ # For a leaf (or external sender) with an X.509 credential, it checks that the end-entity certificate's
14
+ # public key is the holder's signature_key (5.3), that the chain verifies against the store at the
15
+ # given time (the current time by default; this covers validity dates), and, if given, the
16
+ # application's identity check: which presented identifiers it accepts for this member (5.3.1).
17
+ # Whether a new credential is a valid successor of the one it replaces is also the application's call,
18
+ # through that check. Basic credentials are rejected unless accept_basic: is true.
19
+ class Melos::Credential::X509
20
+ attr_reader :last_error
21
+
22
+ # certificates: the chain, end-entity first, as OpenSSL::X509::Certificate or DER strings
23
+ def self.create_credential(certificates)
24
+ Melos::Struct::Credential.create(
25
+ credential_type: Melos::Constants::CredentialType::X509, identity: nil,
26
+ certificates: certificates.map { Melos::Struct::Certificate.create(cert_data: _1.is_a?(OpenSSL::X509::Certificate) ? _1.to_der : _1) }
27
+ )
28
+ end
29
+
30
+ # the certificates of an X.509 credential, end-entity first
31
+ def self.certificates(credential)
32
+ credential.certificates.map { OpenSSL::X509::Certificate.new(_1.cert_data) }
33
+ end
34
+
35
+ # a public key as MLS encodes a SignaturePublicKey: the raw key for Ed25519 and Ed448, the
36
+ # uncompressed point for ECDSA
37
+ def self.signature_key_bytes(public_key)
38
+ if public_key.is_a?(OpenSSL::PKey::EC)
39
+ public_key.public_key.to_bn.to_s(2)
40
+ else
41
+ public_key.raw_public_key
42
+ end
43
+ end
44
+
45
+ # store: OpenSSL::X509::Store holding the trust anchors (and any intermediates peers may omit)
46
+ # time: the time to verify the chain at, or nil for now
47
+ # identity_check: ->(end_entity_certificate, holder) { true/false }, the application's reference identifiers
48
+ # accept_basic: whether basic credentials pass (they carry nothing to check)
49
+ def initialize(store:, time: nil, identity_check: nil, accept_basic: false)
50
+ @store = store
51
+ @time = time
52
+ @identity_check = identity_check
53
+ @accept_basic = accept_basic
54
+ @last_error = nil
55
+ end
56
+
57
+ # the credential_validator interface: holder is the LeafNode or ExternalSender carrying the credential
58
+ def call(credential, holder)
59
+ validate!(credential, holder)
60
+ @last_error = nil
61
+ true
62
+ rescue Melos::ProtocolError, OpenSSL::X509::CertificateError, OpenSSL::PKey::PKeyError => e
63
+ @last_error = e.message
64
+ false
65
+ end
66
+
67
+ # like #call, but raises Melos::ProtocolError with the reason
68
+ def validate!(credential, holder)
69
+ case credential.credential_type
70
+ when Melos::Constants::CredentialType::BASIC
71
+ return if @accept_basic
72
+ raise Melos::ProtocolError.new('basic credentials are not accepted')
73
+ when Melos::Constants::CredentialType::X509
74
+ certificates = self.class.certificates(credential)
75
+ raise Melos::ProtocolError.new('X.509 credential has no certificates') if certificates.empty?
76
+ end_entity, *chain = certificates
77
+ # 5.3: the end-entity certificate's key is the holder's signature key
78
+ unless self.class.signature_key_bytes(end_entity.public_key) == holder.signature_key
79
+ raise Melos::ProtocolError.new('end-entity certificate key differs from the signature key')
80
+ end
81
+ context = OpenSSL::X509::StoreContext.new(@store, end_entity, chain)
82
+ context.time = @time if @time
83
+ raise Melos::ProtocolError.new("certificate chain does not verify: #{context.error_string}") unless context.verify
84
+ if @identity_check && !@identity_check.call(end_entity, holder)
85
+ raise Melos::ProtocolError.new('certificate identity not accepted for this member')
86
+ end
87
+ else
88
+ raise Melos::ProtocolError.new("unsupported credential type #{credential.credential_type}")
89
+ end
90
+ end
91
+ end
data/lib/melos/crypto.rb CHANGED
@@ -5,6 +5,14 @@ require_relative 'vec'
5
5
  class Melos::Crypto
6
6
  class CipherSuite
7
7
  module X25519
8
+ def self.serialize_public_key(key)
9
+ key.raw_public_key
10
+ end
11
+
12
+ def self.serialize_private_key(key)
13
+ key.raw_private_key
14
+ end
15
+
8
16
  def self.deserialize_public_encapsulation_key(raw)
9
17
  OpenSSL::PKey.new_raw_public_key('X25519', raw)
10
18
  end
@@ -21,12 +29,28 @@ class Melos::Crypto
21
29
  OpenSSL::PKey.new_raw_private_key('ED25519', raw)
22
30
  end
23
31
 
32
+ def self.encapsulation_algorithm_name
33
+ 'X25519'
34
+ end
35
+
36
+ def self.signature_algorithm_name
37
+ 'ED25519'
38
+ end
39
+
24
40
  def self.hash_algorithm
25
41
  nil
26
42
  end
27
43
  end
28
44
 
29
45
  module X448
46
+ def self.serialize_public_key(key)
47
+ key.raw_public_key
48
+ end
49
+
50
+ def self.serialize_private_key(key)
51
+ key.raw_private_key
52
+ end
53
+
30
54
  def self.deserialize_public_encapsulation_key(raw)
31
55
  OpenSSL::PKey.new_raw_public_key('X448', raw)
32
56
  end
@@ -43,6 +67,14 @@ class Melos::Crypto
43
67
  OpenSSL::PKey.new_raw_private_key('ED448', raw)
44
68
  end
45
69
 
70
+ def self.encapsulation_algorithm_name
71
+ 'X448'
72
+ end
73
+
74
+ def self.signature_algorithm_name
75
+ 'ED448'
76
+ end
77
+
46
78
  def self.hash_algorithm
47
79
  nil
48
80
  end
@@ -50,6 +82,14 @@ class Melos::Crypto
50
82
 
51
83
  class EC
52
84
  # also would like to depend on HPKE gem...
85
+ def self.serialize_public_key(key)
86
+ key.public_key.to_bn.to_s(2)
87
+ end
88
+
89
+ def self.serialize_private_key(key)
90
+ key.private_key.to_s(2)
91
+ end
92
+
53
93
  def self.deserialize_private_key(secret)
54
94
  asn1_seq = OpenSSL::ASN1.Sequence([
55
95
  OpenSSL::ASN1.Integer(1),
@@ -116,51 +156,54 @@ class Melos::Crypto
116
156
  end
117
157
  end
118
158
 
119
- attr_accessor :level, :digest, :hpke, :kdf, :pkey
159
+ attr_accessor :level, :digest, :hpke, :kdf, :pkey, :suite_id
120
160
  def initialize(suite_id)
161
+ @suite_id = suite_id
121
162
  case suite_id
122
163
  when 1 # MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
123
164
  @level = 128
124
165
  @digest = OpenSSL::Digest.new('sha256')
125
- @hpke = HPKE.new(:x25519, :sha256, :sha256, :aes_128_gcm)
166
+ @hpke = HPKE.new(HPKE::DHKEM_X25519_HKDF_SHA256, HPKE::HKDF_SHA256, HPKE::AES_128_GCM)
126
167
  @kdf = @hpke.hkdf
127
168
  @pkey = Melos::Crypto::CipherSuite::X25519
128
169
  when 2 # MLS_128_DHKEMP256_AES128GCM_SHA256_P256
129
170
  @level = 128
130
171
  @digest = OpenSSL::Digest.new('sha256')
131
- @hpke = HPKE.new(:p_256, :sha256, :sha256, :aes_128_gcm)
172
+ @hpke = HPKE.new(HPKE::DHKEM_P256_HKDF_SHA256, HPKE::HKDF_SHA256, HPKE::AES_128_GCM)
132
173
  @kdf = @hpke.hkdf
133
174
  @pkey = Melos::Crypto::CipherSuite::P256
134
175
  when 3 # MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
135
176
  @level = 128
136
177
  @digest = OpenSSL::Digest.new('sha256')
137
- @hpke = HPKE.new(:x25519, :sha256, :sha256, :chacha20_poly1305)
178
+ @hpke = HPKE.new(HPKE::DHKEM_X25519_HKDF_SHA256, HPKE::HKDF_SHA256, HPKE::CHACHA20_POLY1305)
138
179
  @kdf = @hpke.hkdf
139
180
  @pkey = Melos::Crypto::CipherSuite::X25519
140
181
  when 4 # MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
141
182
  @level = 256
142
183
  @digest = OpenSSL::Digest.new('sha512')
143
- @hpke = HPKE.new(:x448, :sha512, :sha512, :aes_256_gcm)
184
+ @hpke = HPKE.new(HPKE::DHKEM_X448_HKDF_SHA512, HPKE::HKDF_SHA512, HPKE::AES_256_GCM)
144
185
  @kdf = @hpke.hkdf
145
186
  @pkey = Melos::Crypto::CipherSuite::X448
146
187
  when 5 # MLS_256_DHKEMP521_AES256GCM_SHA512_P521
147
188
  @level = 256
148
189
  @digest = OpenSSL::Digest.new('sha512')
149
- @hpke = HPKE.new(:p_521, :sha512, :sha512, :aes_256_gcm)
190
+ @hpke = HPKE.new(HPKE::DHKEM_P521_HKDF_SHA512, HPKE::HKDF_SHA512, HPKE::AES_256_GCM)
150
191
  @kdf = @hpke.hkdf
151
192
  @pkey = Melos::Crypto::CipherSuite::P521
152
193
  when 6 # MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448
153
194
  @level = 256
154
195
  @digest = OpenSSL::Digest.new('sha512')
155
- @hpke = HPKE.new(:x448, :sha512, :sha512, :chacha20_poly1305)
196
+ @hpke = HPKE.new(HPKE::DHKEM_X448_HKDF_SHA512, HPKE::HKDF_SHA512, HPKE::CHACHA20_POLY1305)
156
197
  @kdf = @hpke.hkdf
157
198
  @pkey = Melos::Crypto::CipherSuite::X448
158
199
  when 7 # MLS_256_DHKEMP384_AES256GCM_SHA384_P384
159
200
  @level = 256
160
201
  @digest = OpenSSL::Digest.new('sha384')
161
- @hpke = HPKE.new(:p_384, :sha384, :sha384, :aes_256_gcm)
202
+ @hpke = HPKE.new(HPKE::DHKEM_P384_HKDF_SHA384, HPKE::HKDF_SHA384, HPKE::AES_256_GCM)
162
203
  @kdf = @hpke.hkdf
163
204
  @pkey = Melos::Crypto::CipherSuite::P384
205
+ else
206
+ raise Melos::UnsupportedError.new("unsupported cipher suite #{suite_id}")
164
207
  end
165
208
  end
166
209
  end
@@ -172,7 +215,7 @@ class Melos::Crypto
172
215
  end
173
216
 
174
217
  def self.ref_hash(suite, label, value)
175
- ref_hash_input = Melos::Vec.from_string(label) + Melos::Vec.from_string(value)
218
+ ref_hash_input = Melos::Vec.string_to_vec(label) + Melos::Vec.string_to_vec(value)
176
219
  suite.digest.digest(ref_hash_input)
177
220
  end
178
221
 
@@ -189,7 +232,7 @@ class Melos::Crypto
189
232
  end
190
233
 
191
234
  def self.expand_with_label(suite, secret, label, context, length)
192
- kdf_label = [length].pack('S>') + Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
235
+ kdf_label = [length].pack('S>') + Melos::Vec.string_to_vec("MLS 1.0 " + label) + Melos::Vec.string_to_vec(context)
193
236
  suite.kdf.expand(secret, kdf_label, length)
194
237
  end
195
238
 
@@ -226,27 +269,47 @@ class Melos::Crypto
226
269
  ctx.open(aad, ct)
227
270
  end
228
271
 
272
+ # 8.3: the external key pair of an epoch, [private, public], from its external_secret
273
+ def self.external_key_pair(suite, external_secret)
274
+ derive_key_pair(suite, external_secret)
275
+ end
276
+
277
+ # 8.3 (joiner): kem_output, context = SetupBaseS(external_pub, ""); init_secret = context.export("MLS 1.0 external init secret", KDF.Nh)
278
+ # Returns [kem_output, init_secret].
279
+ def self.external_init_sender(suite, external_pub)
280
+ context = suite.hpke.setup_base_s(suite.pkey.deserialize_public_encapsulation_key(external_pub), '')
281
+ [context[:enc], context[:context_s].export('MLS 1.0 external init secret', suite.kdf.n_h)]
282
+ end
283
+
284
+ # 8.3 (members): context = SetupBaseR(kem_output, external_priv, ""); the same init_secret
285
+ def self.external_init_receiver(suite, external_private_key, kem_output)
286
+ context = suite.hpke.setup_base_r(kem_output, suite.pkey.deserialize_private_encapsulation_key(external_private_key), '')
287
+ context.export('MLS 1.0 external init secret', suite.kdf.n_h)
288
+ rescue OpenSSL::PKey::PKeyError, ArgumentError => e
289
+ raise Melos::ProtocolError.new("ExternalInit kem_output is invalid: #{e.message}")
290
+ end
291
+
229
292
  def self.encrypt_with_label(suite, public_key, label, context, plaintext)
230
- encrypt_context = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
293
+ encrypt_context = Melos::Vec.string_to_vec("MLS 1.0 " + label) + Melos::Vec.string_to_vec(context)
231
294
  pkey = suite.pkey.deserialize_public_encapsulation_key(public_key)
232
295
  seal_base(suite, pkey, encrypt_context, "", plaintext)
233
296
  end
234
297
 
235
298
  def self.decrypt_with_label(suite, private_key, label, context, kem_output, ciphertext)
236
- encrypt_context = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
299
+ encrypt_context = Melos::Vec.string_to_vec("MLS 1.0 " + label) + Melos::Vec.string_to_vec(context)
237
300
  pkey = suite.pkey.deserialize_private_encapsulation_key(private_key)
238
301
  open_base(suite, kem_output, pkey, encrypt_context, "", ciphertext)
239
302
  end
240
303
 
241
304
  def self.sign_with_label(suite, signature_key, label, content)
242
305
  skey = suite.pkey.deserialize_private_signature_key(signature_key)
243
- sign_content = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(content)
306
+ sign_content = Melos::Vec.string_to_vec("MLS 1.0 " + label) + Melos::Vec.string_to_vec(content)
244
307
  skey.sign(suite.pkey.hash_algorithm, sign_content)
245
308
  end
246
309
 
247
310
  def self.verify_with_label(suite, verification_key, label, content, signature_value)
248
311
  vkey = suite.pkey.deserialize_public_signature_key(verification_key)
249
- sign_content = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(content)
312
+ sign_content = Melos::Vec.string_to_vec("MLS 1.0 " + label) + Melos::Vec.string_to_vec(content)
250
313
  vkey.verify(suite.pkey.hash_algorithm, signature_value, sign_content)
251
314
  end
252
315
 
@@ -262,8 +325,11 @@ class Melos::Crypto
262
325
  suite.hpke.aead_encrypt(key, nonce, aad, plaintext)
263
326
  end
264
327
 
328
+ # a ciphertext that does not authenticate is input to reject (Melos::ProtocolError)
265
329
  def self.aead_decrypt(suite, key, nonce, aad, ciphertext)
266
330
  suite.hpke.aead_decrypt(key, nonce, aad, ciphertext)
331
+ rescue OpenSSL::Cipher::CipherError => e
332
+ raise Melos::ProtocolError.new("AEAD decryption failed: #{e.message}")
267
333
  end
268
334
 
269
335
  def self.sender_data_key(suite, sender_data_secret, ciphertext)
@@ -301,7 +367,35 @@ class Melos::Crypto
301
367
  end
302
368
 
303
369
  def self.parent_hash(suite, encryption_key, ph_of_parent, sibling_hash)
304
- parent_hash_input = Melos::Vec.from_string(encryption_key) + Melos::Vec.from_string(ph_of_parent) + Melos::Vec.from_string(sibling_hash)
370
+ parent_hash_input = Melos::Vec.string_to_vec(encryption_key) + Melos::Vec.string_to_vec(ph_of_parent) + Melos::Vec.string_to_vec(sibling_hash)
305
371
  Melos::Crypto.hash(suite, parent_hash_input)
306
372
  end
373
+
374
+ def self.generate_encapsulation_key_pair(suite)
375
+ if suite.pkey.equal?(Melos::Crypto::CipherSuite::X25519) || suite.pkey.equal?(Melos::Crypto::CipherSuite::X448)
376
+ # is an Edwards curve
377
+ OpenSSL::PKey.generate_key(suite.pkey.encapsulation_algorithm_name)
378
+ else
379
+ # is an EC
380
+ OpenSSL::PKey::EC.generate(suite.pkey.curve_name)
381
+ end
382
+ end
383
+
384
+ def self.generate_signature_key_pair(suite)
385
+ if suite.pkey.equal?(Melos::Crypto::CipherSuite::X25519) || suite.pkey.equal?(Melos::Crypto::CipherSuite::X448)
386
+ # is an Edwards curve
387
+ OpenSSL::PKey.generate_key(suite.pkey.signature_algorithm_name)
388
+ else
389
+ # is an EC
390
+ OpenSSL::PKey::EC.generate(suite.pkey.curve_name)
391
+ end
392
+ end
393
+
394
+ def self.serialize_public_key(suite, pkey)
395
+ suite.pkey.serialize_public_key(pkey)
396
+ end
397
+
398
+ def self.serialize_private_key(suite, pkey)
399
+ suite.pkey.serialize_private_key(pkey)
400
+ end
307
401
  end