pqc_rails 0.2.1 → 0.4.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.
@@ -3,6 +3,7 @@
3
3
  require "active_record"
4
4
  require_relative "hybrid_kem"
5
5
  require_relative "envelope_cipher"
6
+ require_relative "ciphertext_format"
6
7
  require_relative "session/encryptor"
7
8
 
8
9
  module PqcRails
@@ -18,6 +19,9 @@ module PqcRails
18
19
  # 内部的にはSession::Encryptorと同じKEM-DEM構成(HybridKem+EnvelopeCipher)。
19
20
  # Session::Encryptorを再利用しないのは、ARはCipher層に外から`key:`を渡す設計のため
20
21
  # 鍵の持ち方が異なるから(Session::Encryptorは自分でKeypairを保持する)。
22
+ #
23
+ # 暗号文の形式(v1)はheadersに、KEM暗号文(kem_ct)に加えて形式バージョン(pv)・アルゴリズムID(alg)・
24
+ # 鍵ID(kid)を持つ。各値の意味と検証はCiphertextFormatを参照。
21
25
  class Cipher
22
26
  DEFAULT_PQ_ALG_NAME = PqcRails::Session::Encryptor::DEFAULT_PQ_ALG_NAME
23
27
 
@@ -27,30 +31,51 @@ module PqcRails
27
31
 
28
32
  def encrypt(clear_text, key:, deterministic: false)
29
33
  raise ArgumentError, "PqcRails::Cipher does not support deterministic encryption" if deterministic
34
+ return encrypt_legacy(clear_text, key) if CiphertextFormat.write_legacy?
30
35
 
31
- HybridKem.open(@pq_alg_name) do |hybrid|
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|
32
41
  encap = hybrid.encapsulate(key.public_key)
33
- envelope = EnvelopeCipher.new(encap.shared_secret).encrypt(clear_text)
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)
34
44
 
35
45
  ::ActiveRecord::Encryption::Message.new(payload: envelope).tap do |message|
36
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
37
50
  end
38
51
  end
39
52
  end
40
53
 
54
+ # 形式バージョンのヘッダーがあればv1として、無ければ旧形式(v0)として復号する。
55
+ # v1では、暗号文に書かれたアルゴリズムで復号し、鍵IDが一致する鍵だけを試す。
56
+ # ActiveRecordは、previousスキーム(Rails標準の暗号化の導出鍵等)の鍵もkey:に渡してくることがあるため、
57
+ # pqc_railsの鍵ペア(public_key/secret_keyを持つもの)だけを使う。
41
58
  def decrypt(encrypted_message, key:)
42
- keypairs = key.is_a?(::Array) ? key : [key]
43
- last_error = nil
59
+ keypairs = (key.is_a?(::Array) ? key : [key]).select { |candidate| keypair?(candidate) }
60
+ version = header(encrypted_message, :pv)
44
61
 
45
- HybridKem.open(@pq_alg_name) do |hybrid|
46
- keypairs.each do |keypair|
47
- return decrypt_with(hybrid, encrypted_message, keypair)
48
- rescue OpenSSL::Cipher::CipherError, PqcRails::Error, ArgumentError, TypeError => e
49
- last_error = e
50
- end
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)
51
72
  end
73
+ raise ::ActiveRecord::Encryption::Errors::Decryption, e.message
74
+ end
52
75
 
53
- raise ::ActiveRecord::Encryption::Errors::Decryption, last_error&.message
76
+ # 新しく暗号化するときに暗号文へ書くアルゴリズムID(例: "X25519+ML-KEM-768")。
77
+ def algorithm_id
78
+ CiphertextFormat.algorithm_id(@pq_alg_name)
54
79
  end
55
80
 
56
81
  def key_length
@@ -63,12 +88,80 @@ module PqcRails
63
88
 
64
89
  private
65
90
 
66
- def decrypt_with(hybrid, encrypted_message, keypair)
67
- kem_ciphertext = encrypted_message.headers[:kem_ct]
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)
68
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
69
161
 
70
- shared_secret = hybrid.decapsulate(kem_ciphertext, keypair.secret_key)
71
- EnvelopeCipher.new(shared_secret).decrypt(encrypted_message.payload)
162
+ # headersのキーは、シンボルと文字列の両方を読む(キーの型が違う版のActiveRecordで読み戻した暗号文に備える)。
163
+ def header(encrypted_message, name)
164
+ encrypted_message.headers[name] || encrypted_message.headers[name.to_s]
72
165
  end
73
166
  end
74
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
@@ -8,23 +8,77 @@ module PqcRails
8
8
  # config.liboqs_path = "/usr/local/lib/liboqs.dylib"
9
9
  # end
10
10
  class Configuration
11
+ # プラットフォーム別のgem(x86_64-linux-gnu等)が、ビルド済みのliboqsを同梱する場所。
12
+ NATIVE_DIR = File.expand_path("native", __dir__)
11
13
  # liboqsの共有ライブラリへのパス。
12
14
  # 未設定の場合、環境変数 LIBOQS_PATH、それも無ければOS標準の場所を仮定する。
13
15
  attr_accessor :liboqs_path
14
16
 
17
+ CIPHERTEXT_FORMATS = %i[v1 v0].freeze
18
+
19
+ # 暗号化時に書く暗号文の形式。復号は設定によらず両方の形式を読める。
20
+ # :v1 形式バージョン・アルゴリズムID・鍵IDを持つ形式(既定)
21
+ # :v0 0.3.0以前と同じ旧形式。複数台のサーバーへ順番にデプロイする間、まだ旧版のgemが動いている
22
+ # サーバーにも読める暗号文を書くために使う。全台の更新後に:v1へ戻す
23
+ attr_reader :ciphertext_format
24
+
25
+ # 旧形式(v0)の暗号文は作成元の認証を持たず、公開鍵だけで正しく復号できる暗号文を作れる。
26
+ # 旧形式のデータが残っていない状態になったら、旧形式を受け付けないようにする。
27
+
28
+ # 旧形式のDBカラムを復号するかどうか(既定はtrue)。全レコードを再暗号化した後にfalseにする。
29
+ attr_reader :accept_legacy_records
30
+
31
+ # 認証鍵を持たない鍵(0.3.0以前に生成した鍵)宛の旧形式のセッションCookieを、この日時まで復号する。
32
+ # 既定のnilでは復号しない。ciphertext_formatが:v0の間は、順番デプロイ中のCookieを読むため期限によらず復号する。
33
+ # 旧形式のCookieは発行日時を持たないため、旧形式の発行が止まる日時に最長のセッション有効期限を足した日時を設定する。
34
+ attr_reader :accept_legacy_cookies_until
35
+
15
36
  def initialize
16
37
  @liboqs_path = ENV["LIBOQS_PATH"] || default_liboqs_path
38
+ @ciphertext_format = :v1
39
+ @accept_legacy_records = true
40
+ @accept_legacy_cookies_until = nil
41
+ end
42
+
43
+ def ciphertext_format=(format)
44
+ unless CIPHERTEXT_FORMATS.include?(format)
45
+ raise ArgumentError, "ciphertext_format must be one of #{CIPHERTEXT_FORMATS.inspect}, got #{format.inspect}"
46
+ end
47
+
48
+ @ciphertext_format = format
49
+ end
50
+
51
+ def accept_legacy_records=(value)
52
+ unless [true, false].include?(value)
53
+ raise ArgumentError, "accept_legacy_records must be true or false, got #{value.inspect}"
54
+ end
55
+
56
+ @accept_legacy_records = value
57
+ end
58
+
59
+ def accept_legacy_cookies_until=(time)
60
+ unless time.nil? || time.is_a?(Time)
61
+ raise ArgumentError, "accept_legacy_cookies_until must be a Time or nil, got #{time.inspect}"
62
+ end
63
+
64
+ @accept_legacy_cookies_until = time
17
65
  end
18
66
 
19
67
  private
20
68
 
21
69
  # liboqsのデフォルトパス。
22
- # bundle install時にext/pqc_rails/extconf.rbが自前でビルドしたliboqsが見つかれば
23
- # それを優先する(gemを介した自動ビルド、Phase5 Step3のプロトタイプ)。
70
+ # プラットフォーム別のgemが同梱したビルド済みのliboqs、次にbundle install時に
71
+ # ext/pqc_rails/extconf.rbが自前でビルドしたliboqsの順に探す。
24
72
  # 見つからない場合はOS別の「よくあるインストール場所」を当て推量するが、
25
73
  # 本番運用では明示的に liboqs_path を設定することを強く推奨する。
26
74
  def default_liboqs_path
27
- bundled_liboqs_path || os_default_liboqs_path
75
+ native_liboqs_path || bundled_liboqs_path || os_default_liboqs_path
76
+ end
77
+
78
+ # プラットフォーム別のgemが同梱したビルド済みのliboqsがあれば、そのパスを返す。
79
+ # ソースのgem(platform: ruby)には含まれないので、その場合はnilを返す。
80
+ def native_liboqs_path
81
+ %w[liboqs.dylib liboqs.so].map { |name| File.join(NATIVE_DIR, name) }.find { |path| File.exist?(path) }
28
82
  end
29
83
 
30
84
  # gemのインストールディレクトリ配下、ext/pqc_rails/extconf.rbがビルド後にコピーした
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "openssl"
4
4
  require_relative "length_validation"
5
+ require_relative "redacted_struct"
5
6
 
6
7
  module PqcRails
7
8
  # 古典的なECDH(X25519)を「KEM」のAPI形状(generate_keypair/encapsulate/decapsulate)で
@@ -23,8 +24,12 @@ module PqcRails
23
24
  class DhKem
24
25
  include LengthValidation
25
26
 
26
- Keypair = Struct.new(:public_key, :secret_key)
27
- Encapsulation = Struct.new(:ciphertext, :shared_secret)
27
+ Keypair = Struct.new(:public_key, :secret_key) do
28
+ include RedactedStruct
29
+ end
30
+ Encapsulation = Struct.new(:ciphertext, :shared_secret) do
31
+ include RedactedStruct
32
+ end
28
33
 
29
34
  KEY_LENGTH = 32
30
35
 
@@ -41,7 +41,15 @@ module PqcRails
41
41
  iv + cipher.auth_tag + ciphertext
42
42
  end
43
43
 
44
+ # IVと認証タグに満たない入力は、OpenSSLに短い認証タグを設定する前にArgumentErrorにする
45
+ # (GCMは短い認証タグでも検証を行うため、タグの長さはここで保証する)。
44
46
  def decrypt(encrypted, associated_data: nil)
47
+ validate_string!(encrypted, "encrypted")
48
+ if encrypted.bytesize < IV_LENGTH + TAG_LENGTH
49
+ raise ArgumentError,
50
+ "encrypted is too short: expected at least #{IV_LENGTH + TAG_LENGTH} bytes, got #{encrypted.bytesize}"
51
+ end
52
+
45
53
  iv = encrypted[0, IV_LENGTH]
46
54
  tag = encrypted[IV_LENGTH, TAG_LENGTH]
47
55
  ciphertext = encrypted[(IV_LENGTH + TAG_LENGTH)..]
@@ -55,5 +63,16 @@ module PqcRails
55
63
 
56
64
  cipher.update(ciphertext) + cipher.final
57
65
  end
66
+
67
+ # 既定のinspect(ppも使う)・ActiveSupportのas_json・YAMLはインスタンス変数を出すため、鍵を伏せる。
68
+ def inspect = "#<#{self.class.name} key=[FILTERED]>"
69
+
70
+ def as_json(_options = nil) = { "key" => "[FILTERED]" }
71
+
72
+ # YAMLも同じ内容のタグ無しのマップにする。読み戻してもEnvelopeCipherにはならない。
73
+ def encode_with(coder)
74
+ coder.represent_map(nil, as_json)
75
+ coder.implicit = true
76
+ end
58
77
  end
59
78
  end
@@ -35,6 +35,9 @@ module PqcRails
35
35
  attach_function :OQS_KEM_keypair, [:pointer, :pointer, :pointer], :int
36
36
  attach_function :OQS_KEM_encaps, [:pointer, :pointer, :pointer, :pointer], :int
37
37
  attach_function :OQS_KEM_decaps, [:pointer, :pointer, :pointer, :pointer], :int
38
+
39
+ # liboqs/include/oqs/common.h の const char *OQS_version(void)。読み込んだliboqsの版を返す。
40
+ attach_function :OQS_version, [], :string
38
41
  end
39
42
  end
40
43
  end
@@ -4,6 +4,8 @@ require "openssl"
4
4
  require_relative "blob_packing"
5
5
  require_relative "dh_kem"
6
6
  require_relative "kem"
7
+ require_relative "secret_buffer"
8
+ require_relative "redacted_struct"
7
9
 
8
10
  module PqcRails
9
11
  # 古典ECDH(DhKem)とPQ KEM(liboqs経由のKem)を組み合わせたハイブリッドKEM。
@@ -35,8 +37,15 @@ module PqcRails
35
37
  # shared == encap.shared_secret # => true
36
38
  # end
37
39
  class HybridKem
38
- Keypair = Struct.new(:public_key, :secret_key)
39
- Encapsulation = Struct.new(:ciphertext, :shared_secret)
40
+ # authentication_keyは、暗号文の作成元の認証に使う32バイトのランダムな共通鍵
41
+ # (CiphertextFormat.data_key参照)。KEMの演算には使わない。0.3.0以前に生成した鍵は持たない(nil)。
42
+ Keypair = Struct.new(:public_key, :secret_key, :authentication_key) do
43
+ include RedactedStruct
44
+ end
45
+ AUTHENTICATION_KEY_LENGTH = 32
46
+ Encapsulation = Struct.new(:ciphertext, :shared_secret) do
47
+ include RedactedStruct
48
+ end
40
49
 
41
50
  COMBINER_LABEL = "pqc_rails-hybrid-kem-v1"
42
51
  SHARED_SECRET_LENGTH = 32
@@ -59,14 +68,15 @@ module PqcRails
59
68
 
60
69
  Keypair.new(
61
70
  BlobPacking.pack(classical_keypair.public_key, pq_keypair.public_key),
62
- BlobPacking.pack(classical_keypair.secret_key, pq_keypair.secret_key)
71
+ BlobPacking.pack(classical_keypair.secret_key, pq_keypair.secret_key),
72
+ OpenSSL::Random.random_bytes(AUTHENTICATION_KEY_LENGTH)
63
73
  )
64
74
  end
65
75
 
66
76
  def encapsulate(public_key)
67
77
  ensure_not_freed!
68
78
 
69
- classical_public_key, pq_public_key = BlobPacking.unpack(public_key)
79
+ classical_public_key, pq_public_key = BlobPacking.unpack(public_key, exact: true)
70
80
  classical_encap = @classical.encapsulate(classical_public_key)
71
81
  pq_encap = @pq.encapsulate(pq_public_key)
72
82
 
@@ -80,13 +90,16 @@ module PqcRails
80
90
  def decapsulate(ciphertext, secret_key)
81
91
  ensure_not_freed!
82
92
 
83
- classical_ciphertext, pq_ciphertext = BlobPacking.unpack(ciphertext)
93
+ classical_ciphertext, pq_ciphertext = BlobPacking.unpack(ciphertext, exact: true)
84
94
  classical_secret_key, pq_secret_key = BlobPacking.unpack(secret_key)
85
95
 
86
96
  classical_shared = @classical.decapsulate(classical_ciphertext, classical_secret_key)
87
97
  pq_shared = @pq.decapsulate(pq_ciphertext, pq_secret_key)
88
98
 
89
99
  combine(classical_shared, pq_shared, classical_ciphertext, pq_ciphertext)
100
+ ensure
101
+ # unpackが作った秘密鍵のコピーを消す。呼び出し側が渡したsecret_keyはそのまま残る。
102
+ SecretBuffer.wipe(classical_secret_key, pq_secret_key)
90
103
  end
91
104
 
92
105
  def free
data/lib/pqc_rails/kem.rb CHANGED
@@ -2,9 +2,16 @@
2
2
 
3
3
  require_relative "algorithms"
4
4
  require_relative "length_validation"
5
+ require_relative "secret_buffer"
5
6
  require_relative "ffi/kem"
7
+ require_relative "redacted_struct"
6
8
 
7
9
  module PqcRails
10
+ # 読み込んだliboqsの版(例: "0.16.0")。
11
+ def self.liboqs_version
12
+ Ffi::Kem.OQS_version
13
+ end
14
+
8
15
  # liboqsのGeneric KEM APIをRubyらしく包んだクラス。
9
16
  #
10
17
  # 使い方:
@@ -19,8 +26,12 @@ module PqcRails
19
26
  class Kem
20
27
  include LengthValidation
21
28
 
22
- Keypair = Struct.new(:public_key, :secret_key)
23
- Encapsulation = Struct.new(:ciphertext, :shared_secret)
29
+ Keypair = Struct.new(:public_key, :secret_key) do
30
+ include RedactedStruct
31
+ end
32
+ Encapsulation = Struct.new(:ciphertext, :shared_secret) do
33
+ include RedactedStruct
34
+ end
24
35
 
25
36
  attr_reader :alg_name
26
37
 
@@ -47,33 +58,35 @@ module PqcRails
47
58
  ensure_not_freed!
48
59
 
49
60
  public_key = FFI::MemoryPointer.new(:uint8, length_public_key)
50
- secret_key = FFI::MemoryPointer.new(:uint8, length_secret_key)
51
61
 
52
- status = Ffi::Kem.OQS_KEM_keypair(@kem_ptr, public_key, secret_key)
53
- raise PqcRails::Error, "OQS_KEM_keypair failed (status=#{status})" unless status.zero?
62
+ SecretBuffer.with(length_secret_key) do |secret_key|
63
+ status = Ffi::Kem.OQS_KEM_keypair(@kem_ptr, public_key, secret_key)
64
+ raise PqcRails::Error, "OQS_KEM_keypair failed (status=#{status})" unless status.zero?
54
65
 
55
- Keypair.new(
56
- public_key.read_bytes(length_public_key),
57
- secret_key.read_bytes(length_secret_key)
58
- )
66
+ Keypair.new(
67
+ public_key.read_bytes(length_public_key),
68
+ secret_key.read_bytes(length_secret_key)
69
+ )
70
+ end
59
71
  end
60
72
 
61
73
  def encapsulate(public_key)
62
74
  ensure_not_freed!
63
75
  validate_length!(public_key, length_public_key, "public_key")
64
76
 
65
- ciphertext = FFI::MemoryPointer.new(:uint8, length_ciphertext)
66
- shared_secret = FFI::MemoryPointer.new(:uint8, length_shared_secret)
67
- pk_ptr = FFI::MemoryPointer.new(:uint8, public_key.bytesize)
77
+ ciphertext = FFI::MemoryPointer.new(:uint8, length_ciphertext)
78
+ pk_ptr = FFI::MemoryPointer.new(:uint8, public_key.bytesize)
68
79
  pk_ptr.put_bytes(0, public_key)
69
80
 
70
- status = Ffi::Kem.OQS_KEM_encaps(@kem_ptr, ciphertext, shared_secret, pk_ptr)
71
- raise PqcRails::Error, "OQS_KEM_encaps failed (status=#{status})" unless status.zero?
81
+ SecretBuffer.with(length_shared_secret) do |shared_secret|
82
+ status = Ffi::Kem.OQS_KEM_encaps(@kem_ptr, ciphertext, shared_secret, pk_ptr)
83
+ raise PqcRails::Error, "OQS_KEM_encaps failed (status=#{status})" unless status.zero?
72
84
 
73
- Encapsulation.new(
74
- ciphertext.read_bytes(length_ciphertext),
75
- shared_secret.read_bytes(length_shared_secret)
76
- )
85
+ Encapsulation.new(
86
+ ciphertext.read_bytes(length_ciphertext),
87
+ shared_secret.read_bytes(length_shared_secret)
88
+ )
89
+ end
77
90
  end
78
91
 
79
92
  def decapsulate(ciphertext, secret_key)
@@ -81,16 +94,17 @@ module PqcRails
81
94
  validate_length!(ciphertext, length_ciphertext, "ciphertext")
82
95
  validate_length!(secret_key, length_secret_key, "secret_key")
83
96
 
84
- shared_secret = FFI::MemoryPointer.new(:uint8, length_shared_secret)
85
- ct_ptr = FFI::MemoryPointer.new(:uint8, ciphertext.bytesize)
97
+ ct_ptr = FFI::MemoryPointer.new(:uint8, ciphertext.bytesize)
86
98
  ct_ptr.put_bytes(0, ciphertext)
87
- sk_ptr = FFI::MemoryPointer.new(:uint8, secret_key.bytesize)
88
- sk_ptr.put_bytes(0, secret_key)
89
99
 
90
- status = Ffi::Kem.OQS_KEM_decaps(@kem_ptr, shared_secret, ct_ptr, sk_ptr)
91
- raise PqcRails::Error, "OQS_KEM_decaps failed (status=#{status})" unless status.zero?
100
+ SecretBuffer.with(secret_key.bytesize, secret_key) do |sk_ptr|
101
+ SecretBuffer.with(length_shared_secret) do |shared_secret|
102
+ status = Ffi::Kem.OQS_KEM_decaps(@kem_ptr, shared_secret, ct_ptr, sk_ptr)
103
+ raise PqcRails::Error, "OQS_KEM_decaps failed (status=#{status})" unless status.zero?
92
104
 
93
- shared_secret.read_bytes(length_shared_secret)
105
+ shared_secret.read_bytes(length_shared_secret)
106
+ end
107
+ end
94
108
  end
95
109
 
96
110
  def free