pqc_rails 0.4.0-aarch64-linux-gnu

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 +7 -0
  2. data/CHANGELOG.md +379 -0
  3. data/LICENSE.txt +202 -0
  4. data/NOTICE.md +73 -0
  5. data/README.md +478 -0
  6. data/Rakefile +18 -0
  7. data/docs/CRYPTO_INVENTORY.md +49 -0
  8. data/docs/MIGRATION.md +211 -0
  9. data/docs/THREAT_MODEL.md +188 -0
  10. data/gemfiles/rails_7.1.gemfile +14 -0
  11. data/gemfiles/rails_8.1.gemfile +14 -0
  12. data/lib/pqc_rails/active_record/ciphertext_info.rb +48 -0
  13. data/lib/pqc_rails/active_record/context.rb +44 -0
  14. data/lib/pqc_rails/active_record/key_provider.rb +97 -0
  15. data/lib/pqc_rails/algorithms.rb +74 -0
  16. data/lib/pqc_rails/blob_packing.rb +73 -0
  17. data/lib/pqc_rails/cipher.rb +167 -0
  18. data/lib/pqc_rails/ciphertext_format.rb +163 -0
  19. data/lib/pqc_rails/configuration.rb +123 -0
  20. data/lib/pqc_rails/dh_kem.rb +71 -0
  21. data/lib/pqc_rails/envelope_cipher.rb +78 -0
  22. data/lib/pqc_rails/ffi/kem.rb +43 -0
  23. data/lib/pqc_rails/ffi/sig.rb +68 -0
  24. data/lib/pqc_rails/generators/install/install_generator.rb +48 -0
  25. data/lib/pqc_rails/generators/install/templates/initializer.rb +10 -0
  26. data/lib/pqc_rails/hybrid_kem.rb +144 -0
  27. data/lib/pqc_rails/kem.rb +130 -0
  28. data/lib/pqc_rails/key_source.rb +146 -0
  29. data/lib/pqc_rails/length_validation.rb +22 -0
  30. data/lib/pqc_rails/native/liboqs.so +0 -0
  31. data/lib/pqc_rails/railtie.rb +12 -0
  32. data/lib/pqc_rails/redacted_struct.rb +53 -0
  33. data/lib/pqc_rails/secret_buffer.rb +35 -0
  34. data/lib/pqc_rails/session/encryptor.rb +141 -0
  35. data/lib/pqc_rails/session/key_manager.rb +40 -0
  36. data/lib/pqc_rails/session/pqc_cookie_store.rb +60 -0
  37. data/lib/pqc_rails/sig.rb +165 -0
  38. data/lib/pqc_rails/status_check.rb +240 -0
  39. data/lib/pqc_rails/tasks/pqc_rails.rake +16 -0
  40. data/lib/pqc_rails/version.rb +5 -0
  41. data/lib/pqc_rails.rb +41 -0
  42. data/sig/pqc_rails.rbs +4 -0
  43. metadata +176 -0
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+ require_relative "../cipher"
5
+ require_relative "key_provider"
6
+
7
+ module PqcRails
8
+ module ActiveRecord
9
+ # ActiveRecord::Encryptionのデフォルトcontextに、PqcRails::Cipherと
10
+ # PqcRails::ActiveRecord::KeyProviderを設定する。
11
+ #
12
+ # 注意: ActiveRecord::Encryption.config.custom_contexts はwith_encryption_context用の
13
+ # スレッドローカルな一時上書きスタックで、永続的な差し替えには使えない。
14
+ # 永続的な差し替えの正しい入口は ActiveRecord::Encryption.configure(...)。
15
+ module Context
16
+ module_function
17
+
18
+ def install!(pq_alg_name: PqcRails::Cipher::DEFAULT_PQ_ALG_NAME,
19
+ key_provider: PqcRails::ActiveRecord::KeyProvider.new,
20
+ primary_key: existing_config_value(:primary_key),
21
+ deterministic_key: existing_config_value(:deterministic_key),
22
+ key_derivation_salt: existing_config_value(:key_derivation_salt))
23
+ PqcRails::ActiveRecord::KeyProvider.installed = key_provider
24
+ ::ActiveRecord::Encryption.configure(
25
+ key_provider: key_provider,
26
+ cipher: PqcRails::Cipher.new(pq_alg_name: pq_alg_name),
27
+ primary_key: primary_key,
28
+ deterministic_key: deterministic_key,
29
+ key_derivation_salt: key_derivation_salt
30
+ )
31
+ end
32
+
33
+ # ActiveRecord::Encryption.configure(...)は呼ぶたびにprimary_key/deterministic_key/
34
+ # key_derivation_saltを常に上書きする(未指定ならnilで巻き戻す)ため、install!を呼ぶ前に
35
+ # bin/rails db:encryption:init等で既に設定されていた値を、明示的な指定が無い限り
36
+ # 引き継ぐ。config側の値は未設定だとErrors::Configurationを送出しうるので握りつぶす。
37
+ def existing_config_value(name)
38
+ ::ActiveRecord::Encryption.config.public_send(name)
39
+ rescue ::ActiveRecord::Encryption::Errors::Configuration
40
+ nil
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require_relative "../key_source"
5
+
6
+ module PqcRails
7
+ module ActiveRecord
8
+ # ActiveRecord::Encryption::KeyProvider互換。HybridKemの鍵ペアを返す実装。
9
+ #
10
+ # 既存のActiveRecord::Encryption::KeyProvider(Key#secretが単一の不透明な文字列)は
11
+ # 公開鍵/秘密鍵という「鍵ペア」の概念を持たないため、ML-KEMを使う余地が無い。
12
+ # そのためKeyProvider自体を独自実装し、`key.secret`がPqcRails::HybridKem::Keypair
13
+ # (公開鍵・秘密鍵のペア)を返すようにしている。
14
+ #
15
+ # 鍵のソース(環境変数→Rails credentials→decode)はKeySourceに一本化されており、
16
+ # セッション用の鍵とは異なるENV変数名/credentialsキーを渡すことで用途ごとに鍵を分離する。
17
+ #
18
+ # 鍵ローテーションは#decryption_keysが現行鍵に続けて旧鍵世代を返すことで対応する
19
+ # (ActiveRecord::Encryption::Cipher互換の#decryptは配列の各鍵を順に試すため、
20
+ # PqcRails::Cipher#decryptは変更不要)。旧鍵はPQC_RECORD_PREVIOUS_KEYS(ENV)または
21
+ # pqc_record_previous_keys(credentials)から読み込む。
22
+ class KeyProvider
23
+ ENV_VAR = "PQC_RECORD_KEY"
24
+ PREVIOUS_ENV_VAR = "PQC_RECORD_PREVIOUS_KEYS"
25
+ CREDENTIALS_KEY = :pqc_record_key
26
+ PREVIOUS_CREDENTIALS_KEY = :pqc_record_previous_keys
27
+
28
+ Key = Struct.new(:secret) do
29
+ def id
30
+ Digest::SHA1.hexdigest(secret.public_key).first(4)
31
+ end
32
+
33
+ def public_tags
34
+ @public_tags ||= ::ActiveRecord::Encryption::Properties.new
35
+ end
36
+ end
37
+
38
+ class << self
39
+ # Context.install!で設定したKeyProvider。with_encryption_contextの中でも判定から外れないように持つ。
40
+ attr_accessor :installed
41
+
42
+ # install!で設定したものと、今のコンテキストのもののうち、pqc_railsの鍵を返すKeyProvider。
43
+ def configured
44
+ [installed, current_context_provider].compact.uniq.select { |provider| provider.respond_to?(:public_keys) }
45
+ end
46
+
47
+ private
48
+
49
+ def current_context_provider
50
+ return unless defined?(::ActiveRecord::Encryption)
51
+
52
+ ::ActiveRecord::Encryption.context.key_provider
53
+ rescue ::ActiveRecord::Encryption::Errors::Configuration
54
+ nil
55
+ end
56
+ end
57
+
58
+ def initialize(key_source: default_key_source)
59
+ @key_source = key_source
60
+ end
61
+
62
+ def encryption_key
63
+ @encryption_key ||= build_key(@key_source.current_keypair)
64
+ end
65
+
66
+ def decryption_keys(_encrypted_message)
67
+ [encryption_key] + @key_source.previous_keypairs.map { |keypair| build_key(keypair) }
68
+ end
69
+
70
+ # 現行鍵と旧鍵の公開鍵。鍵が未設定なら含めない。
71
+ def public_keys
72
+ current = begin
73
+ [@key_source.current_keypair]
74
+ rescue PqcRails::MissingKeyError
75
+ []
76
+ end
77
+ (current + @key_source.previous_keypairs).map(&:public_key)
78
+ end
79
+
80
+ private
81
+
82
+ def default_key_source
83
+ PqcRails::KeySource::EnvCredentials.new(
84
+ env_var: ENV_VAR, previous_env_var: PREVIOUS_ENV_VAR,
85
+ credentials_key: CREDENTIALS_KEY, previous_credentials_key: PREVIOUS_CREDENTIALS_KEY,
86
+ label: "record"
87
+ )
88
+ end
89
+
90
+ def build_key(keypair)
91
+ Key.new(keypair).tap do |key|
92
+ key.public_tags.encrypted_data_key_id = key.id if ::ActiveRecord::Encryption.config.store_key_references
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PqcRails
4
+ # NIST標準化アルゴリズムのシンボル名(:ml_kem_512等)とliboqs側のアルゴリズム名文字列
5
+ # ("ML-KEM-512"等)を対応づけるレジストリ。
6
+ #
7
+ # Kem/Sigはliboqsの生の文字列を直接渡すこともできるが(liboqsが対応する任意のアルゴリズムを
8
+ # 使える柔軟性は維持する)、このレジストリを経由してシンボルで指定すれば、
9
+ # liboqs側の命名に依存しない安定したAPIになる。
10
+ # 将来 ActiveRecord::Encryption と統合する際、設定ファイルやモデルにliboqsの生文字列を
11
+ # 書かせるのではなく、このシンボルを書かせることを想定している。
12
+ #
13
+ # 使い方:
14
+ # PqcRails::Kem.new(:ml_kem_512)
15
+ # PqcRails::Sig.new(:ml_dsa_44)
16
+ module Algorithms
17
+ class UnknownAlgorithmError < PqcRails::Error; end
18
+
19
+ Algorithm = Struct.new(:name, :liboqs_name, :family, :security_level, :status, keyword_init: true)
20
+
21
+ KEMS = {
22
+ ml_kem_512: Algorithm.new(
23
+ name: :ml_kem_512, liboqs_name: "ML-KEM-512", family: :kem, security_level: 1, status: :recommended
24
+ ),
25
+ ml_kem_768: Algorithm.new(
26
+ name: :ml_kem_768, liboqs_name: "ML-KEM-768", family: :kem, security_level: 3, status: :recommended
27
+ ),
28
+ ml_kem_1024: Algorithm.new(
29
+ name: :ml_kem_1024, liboqs_name: "ML-KEM-1024", family: :kem, security_level: 5, status: :recommended
30
+ )
31
+ }.freeze
32
+
33
+ SIGS = {
34
+ ml_dsa_44: Algorithm.new(
35
+ name: :ml_dsa_44, liboqs_name: "ML-DSA-44", family: :sig, security_level: 2, status: :recommended
36
+ ),
37
+ ml_dsa_65: Algorithm.new(
38
+ name: :ml_dsa_65, liboqs_name: "ML-DSA-65", family: :sig, security_level: 3, status: :recommended
39
+ ),
40
+ ml_dsa_87: Algorithm.new(
41
+ name: :ml_dsa_87, liboqs_name: "ML-DSA-87", family: :sig, security_level: 5, status: :recommended
42
+ )
43
+ }.freeze
44
+
45
+ module_function
46
+
47
+ def find_kem(name)
48
+ KEMS.fetch(name.to_sym)
49
+ rescue KeyError
50
+ raise UnknownAlgorithmError, "unknown KEM algorithm: #{name.inspect}. Known: #{KEMS.keys.join(', ')}"
51
+ end
52
+
53
+ def find_sig(name)
54
+ SIGS.fetch(name.to_sym)
55
+ rescue KeyError
56
+ raise UnknownAlgorithmError, "unknown SIG algorithm: #{name.inspect}. Known: #{SIGS.keys.join(', ')}"
57
+ end
58
+
59
+ # liboqsに渡すべきアルゴリズム名文字列を解決する。
60
+ # Stringが渡された場合はliboqsの生の名前としてそのまま通す(後方互換・将来の未登録アルゴリズム用)。
61
+ # Symbolが渡された場合はレジストリ経由でliboqs名に変換する。
62
+ def resolve_kem_name(name)
63
+ return name if name.is_a?(String)
64
+
65
+ find_kem(name).liboqs_name
66
+ end
67
+
68
+ def resolve_sig_name(name)
69
+ return name if name.is_a?(String)
70
+
71
+ find_sig(name).liboqs_name
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PqcRails
4
+ # 2つのバイト列を [4byte長][本体][4byte長][本体] で1本のバイト列にまとめる、その逆を行う。
5
+ # 鍵の保存形式(公開鍵+秘密鍵+認証鍵)のように3つ以上をまとめる場合はpack_all/unpack_allを使う。
6
+ # HybridKemの鍵/ciphertextパック(古典+PQ)と、KeyManagerの鍵シリアライズ(公開鍵+秘密鍵)で
7
+ # 同じ処理が必要になるため共通化している。
8
+ #
9
+ # 取り出した値は、元のバイト列と領域を共有しない独立したコピーにする。秘密鍵を取り出した後に
10
+ # SecretBuffer.wipeでゼロ埋めした時、元のバイト列の領域まで残さず消せるようにするため。
11
+ module BlobPacking
12
+ module_function
13
+
14
+ def pack(first, second)
15
+ [first.bytesize].pack("N") + first + [second.bytesize].pack("N") + second
16
+ end
17
+
18
+ # 長さの欄が欠けている、または本体が長さの欄より短い場合はArgumentErrorを送出する。
19
+ # 2つの長さを確かめてからコピーするため、例外の時は秘密鍵のコピーを作らない。
20
+ # 既定では2つ目より後ろのバイト列は読まない(3要素の鍵を2要素として読む0.3.0以前と同じ読み方)。
21
+ # exact: trueのときは、2つ目より後ろに余分なバイトがあればArgumentErrorを送出する。
22
+ # 暗号文・公開鍵で、同じ値に別の書き方ができることと、末尾が壊れた値を黙って受け付けることを防ぐ。
23
+ def unpack(blob, exact: false)
24
+ raise ArgumentError, "packed blob must be a String, got #{blob.class}" unless blob.is_a?(String)
25
+
26
+ first_length = read_length(blob, 0)
27
+ second_offset = 4 + first_length
28
+ second_length = read_length(blob, second_offset)
29
+ packed_length = second_offset + 4 + second_length
30
+ raise ArgumentError, "packed blob is truncated: expected #{second_length} bytes" if packed_length > blob.bytesize
31
+ if exact && packed_length < blob.bytesize
32
+ raise ArgumentError, "packed blob has #{blob.bytesize - packed_length} trailing bytes"
33
+ end
34
+
35
+ [copy(blob, 4, first_length), copy(blob, second_offset + 4, second_length)]
36
+ end
37
+
38
+ # 任意の個数のバイト列を [4byte長][本体] の繰り返しでまとめる。2つの場合はpackと同じ形になる。
39
+ def pack_all(*parts)
40
+ parts.map { |part| [part.bytesize].pack("N") + part }.join
41
+ end
42
+
43
+ # pack_allの逆。本体が長さの欄より短い、または末尾に長さの欄にも満たない余りがある場合は
44
+ # ArgumentErrorを送出する(途中で切れた値を、要素の少ない値として読まないため)。
45
+ def unpack_all(blob)
46
+ raise ArgumentError, "packed blob must be a String, got #{blob.class}" unless blob.is_a?(String)
47
+
48
+ lengths = []
49
+ offset = 0
50
+ while offset < blob.bytesize
51
+ length = read_length(blob, offset)
52
+ raise ArgumentError, "packed blob is truncated: expected #{length} bytes" if offset + 4 + length > blob.bytesize
53
+
54
+ lengths << [offset + 4, length]
55
+ offset += 4 + length
56
+ end
57
+ lengths.map { |start, length| copy(blob, start, length) }
58
+ end
59
+
60
+ def read_length(blob, offset)
61
+ raise ArgumentError, "packed blob is truncated: missing length field" if offset + 4 > blob.bytesize
62
+
63
+ blob.unpack1("@#{offset}N")
64
+ end
65
+
66
+ # blobのoffsetからlengthバイトを、新しく確保した領域にコピーして返す。範囲は呼び出し側が確かめる。
67
+ # byteslice・blob[...]は、末尾まで切り出すとblob自身も共有の状態に変えるため、一時的にでも使わない。
68
+ # その状態のblobに書き込むと、書き込みはblobの新しいコピーに対して行われ、元の領域は残る。
69
+ def copy(blob, offset, length)
70
+ blob.unpack1("@#{offset}a#{length}").force_encoding(blob.encoding)
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,167 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+ require_relative "hybrid_kem"
5
+ require_relative "envelope_cipher"
6
+ require_relative "ciphertext_format"
7
+ require_relative "session/encryptor"
8
+
9
+ module PqcRails
10
+ # ActiveRecord::Encryption::Cipher互換のインターフェースを持つ独立したクラス。
11
+ # ActiveRecord::Encryption.configure(cipher: PqcRails::Cipher.new, key_provider: ...)で
12
+ # デフォルトのAES-256-GCM単体実装を完全に置き換える。
13
+ #
14
+ # ActiveRecord::Encryptionの`key:`は「鍵そのもの」をそのまま渡してくる設計
15
+ # (KeyProvider#encryption_key.secretの値がそのまま渡る)。本実装ではKeyProvider側で
16
+ # `key.secret`がPqcRails::HybridKem::Keypair(公開鍵・秘密鍵のペア)を返すように
17
+ # 揃えてあるので、ここではそのKeypairを直接受け取れる。
18
+ #
19
+ # 内部的にはSession::Encryptorと同じKEM-DEM構成(HybridKem+EnvelopeCipher)。
20
+ # Session::Encryptorを再利用しないのは、ARはCipher層に外から`key:`を渡す設計のため
21
+ # 鍵の持ち方が異なるから(Session::Encryptorは自分でKeypairを保持する)。
22
+ #
23
+ # 暗号文の形式(v1)はheadersに、KEM暗号文(kem_ct)に加えて形式バージョン(pv)・アルゴリズムID(alg)・
24
+ # 鍵ID(kid)を持つ。各値の意味と検証はCiphertextFormatを参照。
25
+ class Cipher
26
+ DEFAULT_PQ_ALG_NAME = PqcRails::Session::Encryptor::DEFAULT_PQ_ALG_NAME
27
+
28
+ def initialize(pq_alg_name: DEFAULT_PQ_ALG_NAME)
29
+ @pq_alg_name = pq_alg_name
30
+ end
31
+
32
+ def encrypt(clear_text, key:, deterministic: false)
33
+ raise ArgumentError, "PqcRails::Cipher does not support deterministic encryption" if deterministic
34
+ return encrypt_legacy(clear_text, key) if CiphertextFormat.write_legacy?
35
+
36
+ algorithm_id = CiphertextFormat.algorithm_id(@pq_alg_name)
37
+ key_id = CiphertextFormat.key_id(key.public_key)
38
+ associated_data = CiphertextFormat.associated_data(algorithm_id: algorithm_id, key_id: key_id, purpose: :record)
39
+
40
+ HybridKem.open(CiphertextFormat.canonical_pq_alg_name(@pq_alg_name)) do |hybrid|
41
+ encap = hybrid.encapsulate(key.public_key)
42
+ data_key = CiphertextFormat.data_key(encap.shared_secret, key.authentication_key, purpose: :record)
43
+ envelope = EnvelopeCipher.new(data_key).encrypt(clear_text, associated_data: associated_data)
44
+
45
+ ::ActiveRecord::Encryption::Message.new(payload: envelope).tap do |message|
46
+ message.headers[:kem_ct] = encap.ciphertext
47
+ message.headers[:pv] = CiphertextFormat::VERSION
48
+ message.headers[:alg] = algorithm_id
49
+ message.headers[:kid] = key_id
50
+ end
51
+ end
52
+ end
53
+
54
+ # 形式バージョンのヘッダーがあればv1として、無ければ旧形式(v0)として復号する。
55
+ # v1では、暗号文に書かれたアルゴリズムで復号し、鍵IDが一致する鍵だけを試す。
56
+ # ActiveRecordは、previousスキーム(Rails標準の暗号化の導出鍵等)の鍵もkey:に渡してくることがあるため、
57
+ # pqc_railsの鍵ペア(public_key/secret_keyを持つもの)だけを使う。
58
+ def decrypt(encrypted_message, key:)
59
+ keypairs = (key.is_a?(::Array) ? key : [key]).select { |candidate| keypair?(candidate) }
60
+ version = header(encrypted_message, :pv)
61
+
62
+ case version
63
+ when nil then decrypt_legacy(encrypted_message, keypairs)
64
+ when CiphertextFormat::VERSION then decrypt_v1(encrypted_message, keypairs)
65
+ else raise PqcRails::Error, "unsupported ciphertext format version: #{version.inspect}"
66
+ end
67
+ rescue PqcRails::Error, ArgumentError, TypeError => e
68
+ # pqc_railsの暗号文でない値(previous:のRails標準の暗号文)や、pqc_railsの鍵を含まない呼び出し
69
+ # (previousスキームの導出鍵だけ)の失敗は、ActiveRecordが復号方式を順に試す過程の正常な失敗なので通知しない。
70
+ if keypairs.any? && header(encrypted_message, :kem_ct)
71
+ PqcRails.instrument_decryption_failure(target: :record, error: e)
72
+ end
73
+ raise ::ActiveRecord::Encryption::Errors::Decryption, e.message
74
+ end
75
+
76
+ # 新しく暗号化するときに暗号文へ書くアルゴリズムID(例: "X25519+ML-KEM-768")。
77
+ def algorithm_id
78
+ CiphertextFormat.algorithm_id(@pq_alg_name)
79
+ end
80
+
81
+ def key_length
82
+ EnvelopeCipher::KEY_LENGTH
83
+ end
84
+
85
+ def iv_length
86
+ EnvelopeCipher::IV_LENGTH
87
+ end
88
+
89
+ private
90
+
91
+ def encrypt_legacy(clear_text, keypair)
92
+ unless keypair.authentication_key.nil?
93
+ raise PqcRails::Error, "ciphertext_format :v0 cannot write with a key that has an authentication key, " \
94
+ "because such a ciphertext is not read back; see docs/MIGRATION.md"
95
+ end
96
+
97
+ HybridKem.open(@pq_alg_name) do |hybrid|
98
+ encap = hybrid.encapsulate(keypair.public_key)
99
+ envelope = EnvelopeCipher.new(encap.shared_secret).encrypt(clear_text)
100
+
101
+ ::ActiveRecord::Encryption::Message.new(payload: envelope).tap do |message|
102
+ message.headers[:kem_ct] = encap.ciphertext
103
+ end
104
+ end
105
+ end
106
+
107
+ def decrypt_legacy(encrypted_message, keypairs)
108
+ CiphertextFormat.ensure_legacy_record_accepted!
109
+
110
+ legacy = CiphertextFormat.legacy_keypairs(keypairs)
111
+ if legacy.empty? && keypairs.any? && header(encrypted_message, :kem_ct)
112
+ raise PqcRails::Error, "legacy (v0) ciphertexts are not read with a key that has an authentication key"
113
+ end
114
+
115
+ try_keypairs(encrypted_message, legacy, pq_alg_name: @pq_alg_name, associated_data: nil, authenticated: false)
116
+ end
117
+
118
+ def decrypt_v1(encrypted_message, keypairs)
119
+ algorithm_id = header(encrypted_message, :alg)
120
+ key_id = header(encrypted_message, :kid)
121
+ pq_alg_name = CiphertextFormat.pq_alg_name_for(algorithm_id, configured: @pq_alg_name)
122
+ candidates = keypairs.select { |keypair| CiphertextFormat.key_id(keypair.public_key) == key_id }
123
+ associated_data = CiphertextFormat.associated_data(algorithm_id: algorithm_id, key_id: key_id, purpose: :record)
124
+
125
+ try_keypairs(encrypted_message, candidates, pq_alg_name: pq_alg_name, associated_data: associated_data,
126
+ authenticated: true)
127
+ end
128
+
129
+ # 各鍵ペアで復号を試す。authenticatedがtrue(v1)ならAES鍵をCiphertextFormat.data_keyで導き、
130
+ # false(旧形式)ならKEMの共有鍵をそのままAES鍵にする。
131
+ # 復号した値はUTF-8として返す(Rails標準のActiveRecord::Encryption::Cipherが、文字コードの記録が無い
132
+ # 暗号文に使う既定と同じ)。暗号文に文字コードを記録しないため、UTF-8以外の文字列は元の文字コードに
133
+ # 戻らない。binary型の属性は、ActiveModelの型がBINARYに付け直す。
134
+ def try_keypairs(encrypted_message, keypairs, pq_alg_name:, associated_data:, authenticated:)
135
+ kem_ciphertext = header(encrypted_message, :kem_ct)
136
+ raise PqcRails::Error, "message is missing the kem_ct header" if kem_ciphertext.nil?
137
+ raise PqcRails::Error, "no decryption key matches the message's key id" if keypairs.empty?
138
+
139
+ last_error = nil
140
+ HybridKem.open(pq_alg_name) do |hybrid|
141
+ keypairs.each do |keypair|
142
+ shared_secret = hybrid.decapsulate(kem_ciphertext, keypair.secret_key)
143
+ data_key = if authenticated
144
+ CiphertextFormat.data_key(shared_secret, keypair.authentication_key, purpose: :record)
145
+ else
146
+ shared_secret
147
+ end
148
+ clear_text = EnvelopeCipher.new(data_key).decrypt(encrypted_message.payload, associated_data: associated_data)
149
+ return clear_text.force_encoding(Encoding::UTF_8)
150
+ rescue OpenSSL::Cipher::CipherError, PqcRails::Error, ArgumentError, TypeError => e
151
+ last_error = e
152
+ end
153
+ end
154
+
155
+ raise PqcRails::Error, last_error.message
156
+ end
157
+
158
+ def keypair?(candidate)
159
+ candidate.respond_to?(:public_key) && candidate.respond_to?(:secret_key)
160
+ end
161
+
162
+ # headersのキーは、シンボルと文字列の両方を読む(キーの型が違う版のActiveRecordで読み戻した暗号文に備える)。
163
+ def header(encrypted_message, name)
164
+ encrypted_message.headers[name] || encrypted_message.headers[name.to_s]
165
+ end
166
+ end
167
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "openssl"
5
+ require_relative "algorithms"
6
+ require_relative "secret_buffer"
7
+
8
+ module PqcRails
9
+ # 認証鍵を持たない鍵(0.3.0以前に生成した鍵)で、新しい形式の暗号文を作ろうとした。
10
+ class MissingAuthenticationKeyError < PqcRails::Error; end
11
+
12
+ # 暗号文に付けるメタデータ(形式バージョン・アルゴリズムID・鍵ID)の定義。
13
+ # Cipher(ActiveRecordのカラム)とSession::Encryptor(セッションCookie)が共通で使う。
14
+ #
15
+ # メタデータが無い旧形式(v0)では、どのアルゴリズムで暗号化したかを暗号文から知る手段が無く、
16
+ # 復号は常に設定値のアルゴリズムで行うしかない。v1では暗号文自身がアルゴリズムIDと鍵IDを持つため、
17
+ # 設定のアルゴリズムを変えても既存の暗号文を読め、復号時に鍵IDの一致する鍵だけを試せる。
18
+ #
19
+ # 形式バージョン・アルゴリズムID・鍵IDはAES-256-GCMの追加認証データ(associated data)に入れる。
20
+ # いずれかが書き換えられると認証タグの検証に失敗し、復号できない。
21
+ #
22
+ # アルゴリズムIDは暗号文から読む値で、DBやCookieを書き換えられる者が自由に指定できる。
23
+ # そのため、復号に使ってよいのはレジストリ(Algorithms::KEMS)に登録されたアルゴリズムと、
24
+ # 設定で明示したアルゴリズムだけに限る。
25
+ #
26
+ # HybridKemは、鍵導出(HKDF)のinfoに、指定されたアルゴリズム名をその書き方のまま含める。
27
+ # 同じML-KEM-768でも:ml_kem_768と"ML-KEM-768"では導出される共有鍵が異なるため、
28
+ # v1では書き方を1つに決める(canonical_pq_alg_name)。暗号化・復号の両方がこの書き方でHybridKemを開く。
29
+ #
30
+ # 作成元の認証: KEMは公開鍵だけで暗号化できるため、KEMの共有鍵をそのままAES鍵にすると、
31
+ # 公開鍵を知る者が正しく復号できる暗号文を作れる。v1では、鍵ペアが持つ認証鍵(32バイトのランダムな共通鍵、
32
+ # HybridKem::Keypair#authentication_key)をKEMの共有鍵と合わせてAES鍵を導く(data_key)。
33
+ # 認証鍵を知らない者はAES鍵を作れず、AES-GCMの認証タグの検証に必ず失敗する。
34
+ # 暗号化と復号を同じアプリケーションが行う前提の構成で、HPKE(RFC 9180)のPSKモードと同じく、
35
+ # 事前共有の秘密を鍵導出に混ぜて作成元を確かめる。共有鍵と認証鍵の組み合わせは、
36
+ # NIST SP 800-227 §4.6.2の鍵結合(KDM((S1, S2), OtherInput))の形を取る。
37
+ # 認証鍵はKEMの秘密鍵から導かず、独立に生成する(1つの鍵を1つの用途に限る、NIST SP 800-57 Part 1 §5.2)。
38
+ # 公開鍵と関係の無い乱数なので、量子計算機で公開鍵から秘密鍵を求めても、認証鍵は得られない。
39
+ module CiphertextFormat
40
+ class UnsupportedAlgorithmError < PqcRails::Error; end
41
+
42
+ VERSION = 1
43
+ CLASSICAL_CURVE = "X25519"
44
+ SEPARATOR = "+"
45
+ KEY_LENGTH = 32
46
+ DATA_KEY_INFO = "pqc_rails:v#{VERSION}:data-key".freeze
47
+ # 暗号文の用途。同じ鍵ペアをDBとセッションに設定しても、一方の暗号文を他方として復号できないよう、
48
+ # AES鍵の導出(HKDFのinfo)と追加認証データの両方に入れる。
49
+ PURPOSES = %i[record session].freeze
50
+
51
+ module_function
52
+
53
+ # HybridKemの組み合わせを表すアルゴリズムID(例: "X25519+ML-KEM-768")を返す。
54
+ def algorithm_id(pq_alg_name)
55
+ "#{CLASSICAL_CURVE}#{SEPARATOR}#{Algorithms.resolve_kem_name(pq_alg_name)}"
56
+ end
57
+
58
+ # アルゴリズムIDを検証し、HybridKemに渡すPQ側のアルゴリズム名をv1の書き方で返す。
59
+ # configuredは呼び出し元に設定されたアルゴリズム(レジストリ未登録の生の名前を含みうる)。
60
+ def pq_alg_name_for(algorithm_id, configured:)
61
+ curve, pq_name = algorithm_id.to_s.split(SEPARATOR, 2)
62
+ unless curve == CLASSICAL_CURVE && allowed_pq_name?(pq_name, configured)
63
+ raise UnsupportedAlgorithmError, "unsupported algorithm id: #{algorithm_id.inspect}"
64
+ end
65
+
66
+ canonical_pq_alg_name(pq_name)
67
+ end
68
+
69
+ # v1でHybridKemに渡すアルゴリズム名。レジストリに登録されたものはシンボル、それ以外はliboqs名。
70
+ def canonical_pq_alg_name(pq_alg_name)
71
+ liboqs_name = Algorithms.resolve_kem_name(pq_alg_name)
72
+ registered = Algorithms::KEMS.values.find { |algorithm| algorithm.liboqs_name == liboqs_name }
73
+ registered ? registered.name : liboqs_name
74
+ end
75
+
76
+ # 公開鍵から鍵IDを求める。ActiveRecord::KeyProvider::Key#idと同じ値になる。
77
+ # 16bitしかなく衝突しうるため、一致した鍵の識別ではなく、一致しない鍵を復号の候補から外す目的に使う。
78
+ def key_id(public_key)
79
+ Digest::SHA1.hexdigest(public_key)[0, 4]
80
+ end
81
+
82
+ def associated_data(algorithm_id:, key_id:, purpose:)
83
+ "pqc_rails:v#{VERSION}:#{purpose_label(purpose)}:#{algorithm_id}:#{key_id}"
84
+ end
85
+
86
+ # KEMの共有鍵と鍵ペアの認証鍵から、AES-256-GCMの鍵(32バイト)をHKDF-SHA256で導く
87
+ # (saltは空文字列、SP 800-56C §8.2)。共有鍵と認証鍵はどちらも32バイト固定なので、連結しても区切りは一意に決まる。
88
+ def data_key(shared_secret, authentication_key, purpose:)
89
+ if authentication_key.nil?
90
+ raise MissingAuthenticationKeyError,
91
+ "this key has no authentication key (a key generated by pqc_rails 0.3.0 or earlier). " \
92
+ "Generate a new key and rotate to it; see docs/MIGRATION.md"
93
+ end
94
+
95
+ unless authentication_key.is_a?(String) && authentication_key.bytesize == KEY_LENGTH
96
+ raise PqcRails::Error, "the authentication key must be a #{KEY_LENGTH}-byte string"
97
+ end
98
+
99
+ secret_part = shared_secret.b
100
+ authentication_part = authentication_key.b
101
+ material = secret_part + authentication_part
102
+ hkdf(material, "#{DATA_KEY_INFO}:#{purpose_label(purpose)}")
103
+ ensure
104
+ SecretBuffer.wipe(material, secret_part, authentication_part)
105
+ end
106
+
107
+ def write_legacy?
108
+ PqcRails.configuration.ciphertext_format == :v0
109
+ end
110
+
111
+ # 旧形式(v0)のDBカラムを受け付けない設定なら、PqcRails::Errorを送出する。
112
+ def ensure_legacy_record_accepted!
113
+ return if PqcRails.configuration.accept_legacy_records
114
+
115
+ raise PqcRails::Error, "legacy (v0) ciphertexts are not accepted (accept_legacy_records is false)"
116
+ end
117
+
118
+ # 旧形式は公開鍵だけで作れるので、復号に使う鍵を、認証鍵を持たない鍵(0.3.0以前に生成した鍵)に限る。
119
+ def legacy_keypairs(keypairs)
120
+ keypairs.select { |keypair| keypair.authentication_key.nil? }
121
+ end
122
+
123
+ # 旧形式(v0)のセッションCookieを受け付けない状態なら、PqcRails::Errorを送出する。
124
+ # 旧形式は公開鍵だけで作れ、中身はMarshal.loadに渡るため、受け付けるのは認証鍵を持たない鍵
125
+ # (0.3.0以前に生成した鍵)だけにする。その鍵でも、旧形式を書いている間(順番デプロイ中)か、期限内に限る。
126
+ # 旧形式には用途の区別が無いため、DBと同じ鍵では、DBの旧形式の値をCookieに組み替えられる。その鍵でも読まない。
127
+ def ensure_legacy_cookie_accepted!(keypair, shared_with_records: false, now: Time.now)
128
+ unless keypair.authentication_key.nil?
129
+ raise PqcRails::Error, "legacy (v0) session cookies are not read with a key that has an authentication key"
130
+ end
131
+ if shared_with_records
132
+ raise PqcRails::Error, "legacy (v0) session cookies are not read with a key also configured for records"
133
+ end
134
+ return if write_legacy?
135
+
136
+ deadline = PqcRails.configuration.accept_legacy_cookies_until
137
+ return if deadline && now <= deadline
138
+
139
+ raise PqcRails::Error,
140
+ "legacy (v0) session cookies are not accepted (accept_legacy_cookies_until: #{deadline.inspect})"
141
+ end
142
+
143
+ def purpose_label(purpose)
144
+ raise ArgumentError, "unknown ciphertext purpose: #{purpose.inspect}" unless PURPOSES.include?(purpose)
145
+
146
+ purpose.to_s
147
+ end
148
+ private_class_method :purpose_label
149
+
150
+ def hkdf(input_key_material, info)
151
+ OpenSSL::KDF.hkdf(input_key_material, salt: "", info: info, length: KEY_LENGTH, hash: "SHA256")
152
+ end
153
+ private_class_method :hkdf
154
+
155
+ def allowed_pq_name?(pq_name, configured)
156
+ return false if pq_name.nil? || pq_name.empty?
157
+
158
+ Algorithms::KEMS.values.any? { |algorithm| algorithm.liboqs_name == pq_name } ||
159
+ Algorithms.resolve_kem_name(configured) == pq_name
160
+ end
161
+ private_class_method :allowed_pq_name?
162
+ end
163
+ end