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 "rails"
4
4
  require "base64"
5
5
  require_relative "blob_packing"
6
+ require_relative "secret_buffer"
6
7
  require_relative "hybrid_kem"
7
8
 
8
9
  module PqcRails
@@ -13,6 +14,15 @@ module PqcRails
13
14
  # このモジュールに委譲する。環境変数を優先するのは、コンテナのsecret注入のように
14
15
  # credentialsファイルを介さずに鍵を渡せるようにするため。
15
16
  module KeySource
17
+ # 鍵の値が、pqc_railsの鍵(公開鍵・秘密鍵・認証鍵をまとめた値)ではなく、シードだけの秘密鍵らしい時に送出する。
18
+ # PqcRails::Errorのサブクラスなので、PqcRails::Errorを捕まえる呼び出し側はそのまま動く。
19
+ class SeedOnlyKeyError < PqcRails::Error; end
20
+
21
+ # シードだけの秘密鍵の長さ。FIPS 203のML-KEMの鍵生成のシード(dとz、計64バイト)、
22
+ # FIPS 204のML-DSAのシード(ξ、32バイト)、X25519の秘密鍵(32バイト)。
23
+ SEED_LENGTHS = [32, 64].freeze
24
+ TRUNCATED_MESSAGE = "the PQC key is truncated: re-copy the full key value"
25
+
16
26
  module_function
17
27
 
18
28
  def fetch(env_var:, credentials_key:)
@@ -39,13 +49,51 @@ module PqcRails
39
49
 
40
50
  # HybridKem::Keypairのシリアライズ形式。鍵の保存形式そのものであり、
41
51
  # セッション・ActiveRecordの両方の鍵管理から利用する。
52
+ # [公開鍵][秘密鍵][認証鍵]をBlobPacking.pack_allでまとめる。0.3.0以前の鍵は認証鍵を持たない2要素の形で、
53
+ # 0.3.0以前の版は先頭の2要素だけを読むため、3要素の鍵も読める。
42
54
  def encode(keypair)
43
- Base64.strict_encode64(BlobPacking.pack(keypair.public_key, keypair.secret_key))
55
+ parts = [keypair.public_key, keypair.secret_key, keypair.authentication_key].compact
56
+ Base64.strict_encode64(BlobPacking.pack_all(*parts))
44
57
  end
45
58
 
59
+ # Base64から戻したバイト列は、鍵を取り出した後にゼロで埋める(鍵ペアが持つのは取り出したコピーだけ)。
60
+ # 公開鍵・秘密鍵が無い、または認証鍵が32バイトに足りない値は、途中で切れた鍵としてPqcRails::Errorを送出する。
61
+ # ただしシードだけの秘密鍵らしい値(seed_only?)はSeedOnlyKeyErrorにする。
46
62
  def decode(encoded)
47
- public_key, secret_key = BlobPacking.unpack(Base64.strict_decode64(encoded))
48
- HybridKem::Keypair.new(public_key, secret_key)
63
+ raw = Base64.strict_decode64(encoded)
64
+ public_key, secret_key, authentication_key = unpack_key(raw)
65
+ if secret_key.nil? ||
66
+ (authentication_key && authentication_key.bytesize != HybridKem::AUTHENTICATION_KEY_LENGTH)
67
+ SecretBuffer.wipe(secret_key, authentication_key)
68
+ raise invalid_key_error(raw)
69
+ end
70
+
71
+ HybridKem::Keypair.new(public_key, secret_key, authentication_key)
72
+ ensure
73
+ SecretBuffer.wipe(raw)
74
+ end
75
+
76
+ # BlobPackingのArgumentErrorは、値の先頭を長さの欄として読んだ数をメッセージに含む。値が秘密鍵の場合に
77
+ # 例外の原因(cause)からその数が報告に出ないよう、原因を付けずに送出する。
78
+ def unpack_key(raw)
79
+ BlobPacking.unpack_all(raw)
80
+ rescue ArgumentError
81
+ raise invalid_key_error(raw), cause: nil
82
+ end
83
+
84
+ def invalid_key_error(raw)
85
+ return PqcRails::Error.new(TRUNCATED_MESSAGE) unless seed_only?(raw)
86
+
87
+ SeedOnlyKeyError.new(
88
+ "the PQC key looks like a seed-only secret key (#{raw.bytesize} bytes), not a pqc_rails key: " \
89
+ "set the key value generated by `rails generate pqc_rails:install`"
90
+ )
91
+ end
92
+
93
+ # pqc_railsの鍵の値は先頭が公開鍵の長さの欄(4バイト、ビッグエンディアン)で、公開鍵は16MBより短いため、
94
+ # 先頭のバイトは必ず0になる。シードの長さで先頭のバイトが0でない値は、鍵の値の頭が途中で切れたものではない。
95
+ def seed_only?(raw)
96
+ SEED_LENGTHS.include?(raw.bytesize) && raw.getbyte(0) != 0
49
97
  end
50
98
 
51
99
  # ENV、またはRails credentialsから現行鍵・旧鍵世代を読み込む、デフォルトの鍵ソース。
@@ -66,16 +114,32 @@ module PqcRails
66
114
  @label = label
67
115
  end
68
116
 
117
+ # 鍵は最初の呼び出しで1回だけ復元し、以後は同じ鍵ペアを返す。呼び出しのたびに復元すると、
118
+ # 秘密鍵のコピーが作られては消されずに解放され、メモリに溜まるため。ENV・credentialsは
119
+ # プロセスの起動後に変わらない前提で、鍵を替える時はプロセスを再起動する。
69
120
  def current_keypair
70
- KeySource.fetch_keypair!(env_var: @env_var, credentials_key: @credentials_key, label: @label)
121
+ @current_keypair ||= KeySource.fetch_keypair!(env_var: @env_var, credentials_key: @credentials_key,
122
+ label: @label)
71
123
  end
72
124
 
73
125
  def previous_keypairs
74
- raw = KeySource.fetch(env_var: @previous_env_var, credentials_key: @previous_credentials_key)
75
- return [] if raw.nil?
126
+ @previous_keypairs ||= begin
127
+ raw = KeySource.fetch(env_var: @previous_env_var, credentials_key: @previous_credentials_key)
128
+ entries = raw.nil? ? [] : (raw.is_a?(::Array) ? raw : raw.split(","))
129
+ decode_generations(entries)
130
+ end
131
+ end
132
+
133
+ private
76
134
 
77
- entries = raw.is_a?(::Array) ? raw : raw.split(",")
78
- entries.map { |encoded| KeySource.decode(encoded.strip) }
135
+ # 途中の世代が読めない時は、それまでに復元した世代の鍵をゼロで埋めてから、何世代目かを示して同じ型の例外を送出する。
136
+ def decode_generations(entries)
137
+ entries.each_with_index.with_object([]) do |(encoded, index), keypairs|
138
+ keypairs << KeySource.decode(encoded.strip)
139
+ rescue PqcRails::Error => e
140
+ keypairs.each { |keypair| SecretBuffer.wipe(keypair.secret_key, keypair.authentication_key) }
141
+ raise e.class, "PQC #{@label} previous key ##{index + 1}: #{e.message}"
142
+ end
79
143
  end
80
144
  end
81
145
  end
@@ -6,11 +6,17 @@ module PqcRails
6
6
  module LengthValidation
7
7
  private
8
8
 
9
+ # 文字列でない値(nil等)もArgumentErrorにする。FFIへ渡す前に、長さの違う入力を必ず止めるため。
9
10
  def validate_length!(bytes, expected_length, name)
11
+ validate_string!(bytes, name)
10
12
  return if bytes.bytesize == expected_length
11
13
 
12
14
  raise ArgumentError,
13
15
  "#{name} has wrong length: expected #{expected_length} bytes, got #{bytes.bytesize}"
14
16
  end
17
+
18
+ def validate_string!(bytes, name)
19
+ raise ArgumentError, "#{name} must be a String, got #{bytes.class}" unless bytes.is_a?(String)
20
+ end
15
21
  end
16
22
  end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PqcRails
4
+ # 鍵ペア(Sig・Kem・DhKem・HybridKemのKeypair)とKEMの結果(Encapsulation)の表示・JSONで、
5
+ # 秘密の値を伏せる共通処理。
6
+ #
7
+ # 素のStructはinspect・to_s・pp(IRBの表示もこれを使う)で全メンバーの値をそのまま出し、
8
+ # ActiveSupportのas_json(to_json・render json:が使う)も全メンバーを取り出すため、
9
+ # ログ・例外の画面・コンソール・JSONのレスポンスに秘密のバイト列が漏れる。
10
+ # 公開鍵と暗号文は長さだけを出し、それ以外のメンバー(秘密鍵・認証鍵・共有秘密)は"[FILTERED]"
11
+ # (Railsのfilter_parametersと同じ表記)にする。公開してよいメンバーを列挙する形なので、
12
+ # 秘密のメンバーが増えても伏せられる。
13
+ # 公開側の値が文字列でない場合(Struct.newに直接渡した場合)は、長さを出さず"[FILTERED]"にする。
14
+ # 表示で例外を出すと、例外の画面やログで元のエラーが見えなくなるため。
15
+ # 値の取り出し(keypair.secret_key・to_h・to_a)と==はStructのまま変えない。
16
+ # to_h・to_aで取り出した値をログやJSONに渡せば、秘密の値はそのまま出る。
17
+ # YAML(to_yaml、Railsのdebugヘルパー)はas_jsonと同じ内容のタグ無しのマップにする。読み戻しても鍵にはならない。
18
+ # Marshalは復元のための形式なので伏せず、秘密の値をそのまま含む。
19
+ module RedactedStruct
20
+ PUBLIC_MEMBERS = %i[public_key ciphertext].freeze
21
+
22
+ def inspect
23
+ fields = each_pair.map { |name, value| "#{name}=#{redacted_value(name, value) || 'nil'}" }
24
+ "#<struct #{self.class.name} #{fields.join(', ')}>"
25
+ end
26
+
27
+ def to_s = inspect
28
+
29
+ def pretty_print(pp)
30
+ pp.text(inspect)
31
+ end
32
+
33
+ # only・exceptなどのオプションは受け取るだけで使わない。常に全メンバーを伏せた形を返す。
34
+ def as_json(_options = nil)
35
+ each_pair.to_h { |name, value| [name.to_s, redacted_value(name, value)] }
36
+ end
37
+
38
+ def encode_with(coder)
39
+ coder.represent_map(nil, as_json)
40
+ coder.implicit = true
41
+ end
42
+
43
+ private
44
+
45
+ def redacted_value(name, value)
46
+ return nil if value.nil?
47
+ return "[FILTERED]" unless PUBLIC_MEMBERS.include?(name)
48
+ return "[FILTERED]" unless value.respond_to?(:bytesize)
49
+
50
+ "[#{value.bytesize} bytes]"
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module PqcRails
6
+ # liboqsに秘密鍵・共有鍵を渡す、またはliboqsから受け取るためのCのバッファを扱う共通処理。
7
+ #
8
+ # FFI::MemoryPointerはGCで解放される時に中身を消さないため、解放された領域に秘密の値が残る。
9
+ # ここではブロックを抜ける時に(例外の場合も)バッファをゼロで埋める。
10
+ # Rubyの文字列は、使い終わった途中のコピーをwipeでゼロ埋めする。プロセスが持ち続ける鍵そのものと、
11
+ # Ruby・OpenSSLが内部で作るコピーは消せない(docs/THREAT_MODEL.md「中間値の破棄」)。
12
+ module SecretBuffer
13
+ module_function
14
+
15
+ # 秘密の値を持つRubyの文字列を、同じ領域のままゼロで上書きする。nilと凍結された文字列は飛ばす。
16
+ # 消せるのはその文字列自身の領域だけで、すでに作られたコピーや、他の文字列と共有している元の領域は残る。
17
+ def wipe(*strings)
18
+ strings.each do |string|
19
+ next if string.nil? || string.frozen?
20
+
21
+ string.bytesplice(0, string.bytesize, "\0".b * string.bytesize)
22
+ end
23
+ nil
24
+ end
25
+
26
+ # sizeバイトのバッファを確保し、bytesがあれば書き込んでからブロックに渡す。ブロックの戻り値を返す。
27
+ def with(size, bytes = nil)
28
+ pointer = FFI::MemoryPointer.new(:uint8, size)
29
+ pointer.put_bytes(0, bytes) if bytes
30
+ yield pointer
31
+ ensure
32
+ pointer&.clear
33
+ end
34
+ end
35
+ end
@@ -4,6 +4,8 @@ require "base64"
4
4
  require_relative "../blob_packing"
5
5
  require_relative "../hybrid_kem"
6
6
  require_relative "../envelope_cipher"
7
+ require_relative "../ciphertext_format"
8
+ require_relative "../active_record/key_provider"
7
9
 
8
10
  module PqcRails
9
11
  module Session
@@ -25,21 +27,113 @@ module PqcRails
25
27
 
26
28
  def encrypt(data)
27
29
  serialized = Marshal.dump(data)
30
+ return Base64.strict_encode64(seal_legacy(serialized)) if CiphertextFormat.write_legacy?
31
+
32
+ Base64.strict_encode64(seal_v1(serialized))
33
+ end
34
+
35
+ # 先頭バイトで形式を判別する。旧形式(v0)は先頭がKEM暗号文の4バイト長(ビッグエンディアン)で、
36
+ # KEM暗号文は16MB未満のため先頭バイトは必ず0になる。1以上なら形式バージョンとして読む。
37
+ # 途中で切れた・壊れたCookieは、どの段で見つかってもPqcRails::Errorにする。
38
+ def decrypt(blob)
39
+ bytes = Base64.strict_decode64(blob)
40
+ Marshal.load(open_cookie(bytes))
41
+ end
42
+
43
+ # この鍵で旧形式のCookieを書けない理由(読み戻せないため)。書ける場合はnil。
44
+ def legacy_write_blocker
45
+ return "the key has an authentication key" unless @keypair.authentication_key.nil?
46
+
47
+ "the key is also configured for records" if shared_with_records?
48
+ end
49
+
50
+ private
51
+
52
+ # 既定の鍵の置き場所と、Context.install!の鍵ソース、ActiveRecord::Encryptionの今のコンテキストの鍵ソースを見る。
53
+ # 属性ごとに指定したkey_providerは対象外。
54
+ def shared_with_records?
55
+ public_key = @keypair.public_key.b
56
+ default_record_public_keys.include?(public_key) || configured_record_public_keys.include?(public_key)
57
+ end
58
+
59
+ # 既定の鍵の置き場所はプロセスの間変わらないので、読み込みは1回だけにする。
60
+ def default_record_public_keys
61
+ @default_record_public_keys ||= ActiveRecord::KeyProvider.new.public_keys.map(&:b)
62
+ end
63
+
64
+ # コンテキストはスレッドや処理の範囲で変わるので、結果を覚えない。
65
+ def configured_record_public_keys
66
+ ActiveRecord::KeyProvider.configured.flat_map(&:public_keys).map(&:b)
67
+ end
68
+
69
+ def open_cookie(bytes)
70
+ case bytes.getbyte(0)
71
+ when 0 then open_legacy(bytes)
72
+ when CiphertextFormat::VERSION then open_v1(bytes)
73
+ else raise PqcRails::Error, "unsupported ciphertext format version: #{bytes.getbyte(0).inspect}"
74
+ end
75
+ rescue OpenSSL::Cipher::CipherError, ArgumentError => e
76
+ raise PqcRails::Error, e.message
77
+ end
78
+
79
+ # 旧形式(v0): [4バイト長][KEM暗号文][4バイト長][AES暗号文]
80
+ def seal_legacy(serialized)
81
+ blocker = legacy_write_blocker
82
+ raise PqcRails::Error, "ciphertext_format :v0 cannot write session cookies: #{blocker}; see docs/MIGRATION.md" if blocker
28
83
 
29
84
  HybridKem.open(@pq_alg_name) do |hybrid|
30
85
  encap = hybrid.encapsulate(@keypair.public_key)
31
- encrypted = EnvelopeCipher.new(encap.shared_secret).encrypt(serialized)
32
-
33
- Base64.strict_encode64(BlobPacking.pack(encap.ciphertext, encrypted))
86
+ BlobPacking.pack(encap.ciphertext, EnvelopeCipher.new(encap.shared_secret).encrypt(serialized))
34
87
  end
35
88
  end
36
89
 
37
- def decrypt(blob)
38
- ciphertext, encrypted = BlobPacking.unpack(Base64.strict_decode64(blob))
90
+ def open_legacy(bytes)
91
+ CiphertextFormat.ensure_legacy_cookie_accepted!(@keypair, shared_with_records: shared_with_records?)
92
+ ciphertext, encrypted = BlobPacking.unpack(bytes, exact: true)
39
93
 
40
94
  HybridKem.open(@pq_alg_name) do |hybrid|
41
95
  shared_secret = hybrid.decapsulate(ciphertext, @keypair.secret_key)
42
- Marshal.load(EnvelopeCipher.new(shared_secret).decrypt(encrypted))
96
+ EnvelopeCipher.new(shared_secret).decrypt(encrypted)
97
+ end
98
+ end
99
+
100
+ # v1: [形式バージョン 1B][アルゴリズムIDの長さ 1B][アルゴリズムID][鍵ID 2B][v0と同じ本体]
101
+ def seal_v1(serialized)
102
+ algorithm_id = CiphertextFormat.algorithm_id(@pq_alg_name)
103
+ key_id = CiphertextFormat.key_id(@keypair.public_key)
104
+ associated_data = CiphertextFormat.associated_data(algorithm_id: algorithm_id, key_id: key_id, purpose: :session)
105
+ header = [CiphertextFormat::VERSION, algorithm_id.bytesize].pack("CC") + algorithm_id + [key_id].pack("H4")
106
+
107
+ HybridKem.open(CiphertextFormat.canonical_pq_alg_name(@pq_alg_name)) do |hybrid|
108
+ encap = hybrid.encapsulate(@keypair.public_key)
109
+ data_key = CiphertextFormat.data_key(encap.shared_secret, @keypair.authentication_key, purpose: :session)
110
+ encrypted = EnvelopeCipher.new(data_key).encrypt(serialized, associated_data: associated_data)
111
+ header + BlobPacking.pack(encap.ciphertext, encrypted)
112
+ end
113
+ end
114
+
115
+ def open_v1(bytes)
116
+ algorithm_id_length = bytes.getbyte(1)
117
+ if algorithm_id_length.nil? || bytes.bytesize < 4 + algorithm_id_length
118
+ raise PqcRails::Error, "the cookie is truncated: missing the format header"
119
+ end
120
+
121
+ algorithm_id = bytes[2, algorithm_id_length]
122
+ key_id = bytes[2 + algorithm_id_length, 2].unpack1("H4")
123
+ body = bytes[(4 + algorithm_id_length)..]
124
+
125
+ if key_id != CiphertextFormat.key_id(@keypair.public_key)
126
+ raise PqcRails::Error, "the cookie was encrypted with a different key id (#{key_id})"
127
+ end
128
+
129
+ pq_alg_name = CiphertextFormat.pq_alg_name_for(algorithm_id, configured: @pq_alg_name)
130
+ associated_data = CiphertextFormat.associated_data(algorithm_id: algorithm_id, key_id: key_id, purpose: :session)
131
+ ciphertext, encrypted = BlobPacking.unpack(body, exact: true)
132
+
133
+ HybridKem.open(pq_alg_name) do |hybrid|
134
+ shared_secret = hybrid.decapsulate(ciphertext, @keypair.secret_key)
135
+ data_key = CiphertextFormat.data_key(shared_secret, @keypair.authentication_key, purpose: :session)
136
+ EnvelopeCipher.new(data_key).decrypt(encrypted, associated_data: associated_data)
43
137
  end
44
138
  end
45
139
  end
@@ -13,7 +13,9 @@ module PqcRails
13
13
  # set_cookie/get_cookieはCookieStoreがRailsの暗号化クッキージャーへの委譲点として
14
14
  # 用意しているprivateな拡張点(Rails 7.1〜8.1で同一シグネチャ)。ここを上書きして
15
15
  # 生のcookie_jar(署名・暗号化なし)に対してEncryptorで暗号化した文字列を直接書き込む。
16
- # AEAD(AES-256-GCM)が改竄検知も兼ねるため、Railsの署名は不要。
16
+ # Railsの署名は使わない。v1形式の暗号文はAES鍵を鍵ペアの認証鍵から導くため、AES-256-GCMの
17
+ # 認証タグが改竄検知と作成元の認証(認証鍵の持ち主が作ったこと)を兼ねる(CiphertextFormat.data_key参照)。
18
+ # 旧形式(v0)は作成元の認証を持たないため、accept_legacy_cookies_untilで受け付けの期限を決める。
17
19
  #
18
20
  # 鍵ローテーション対応: 書き込みは常に現行鍵(@encryptor)のみを使う。読み込みは
19
21
  # 現行鍵で失敗した場合、previous_keypairs(鍵ローテーション前の旧鍵)で順に再試行する。
@@ -43,12 +45,14 @@ module PqcRails
43
45
  raw = request.cookie_jar[@key]
44
46
  return nil if raw.nil?
45
47
 
48
+ last_error = nil
46
49
  [@encryptor, *@previous_encryptors].each do |encryptor|
47
50
  return encryptor.decrypt(raw)
48
- rescue StandardError
49
- next
51
+ rescue StandardError => e
52
+ last_error = e
50
53
  end
51
54
 
55
+ PqcRails.instrument_decryption_failure(target: :session, error: last_error)
52
56
  nil
53
57
  end
54
58
  end
data/lib/pqc_rails/sig.rb CHANGED
@@ -2,7 +2,9 @@
2
2
 
3
3
  require_relative "algorithms"
4
4
  require_relative "length_validation"
5
+ require_relative "secret_buffer"
5
6
  require_relative "ffi/sig"
7
+ require_relative "redacted_struct"
6
8
 
7
9
  module PqcRails
8
10
  # liboqsのGeneric SIG(署名)APIをRubyらしく包んだクラス。
@@ -17,7 +19,9 @@ module PqcRails
17
19
  class Sig
18
20
  include LengthValidation
19
21
 
20
- Keypair = Struct.new(:public_key, :secret_key)
22
+ Keypair = Struct.new(:public_key, :secret_key) do
23
+ include RedactedStruct
24
+ end
21
25
 
22
26
  attr_reader :alg_name
23
27
 
@@ -48,31 +52,31 @@ module PqcRails
48
52
  ensure_not_freed!
49
53
 
50
54
  public_key = FFI::MemoryPointer.new(:uint8, length_public_key)
51
- secret_key = FFI::MemoryPointer.new(:uint8, length_secret_key)
52
55
 
53
- status = Ffi::Sig.OQS_SIG_keypair(@sig_ptr, public_key, secret_key)
54
- raise PqcRails::Error, "OQS_SIG_keypair failed (status=#{status})" unless status.zero?
56
+ SecretBuffer.with(length_secret_key) do |secret_key|
57
+ status = Ffi::Sig.OQS_SIG_keypair(@sig_ptr, public_key, secret_key)
58
+ raise PqcRails::Error, "OQS_SIG_keypair failed (status=#{status})" unless status.zero?
55
59
 
56
- Keypair.new(
57
- public_key.read_bytes(length_public_key),
58
- secret_key.read_bytes(length_secret_key)
59
- )
60
+ Keypair.new(
61
+ public_key.read_bytes(length_public_key),
62
+ secret_key.read_bytes(length_secret_key)
63
+ )
64
+ end
60
65
  end
61
66
 
62
67
  # メッセージに署名する
63
68
  # @param message [String] 署名対象のバイト列
64
69
  # @param secret_key [String] バイト列
65
70
  # @return [String] 署名のバイト列(実際の長さは length_signature 以下のことがある)
71
+ # @raise [ArgumentError] messageが文字列でない場合
66
72
  def sign(message, secret_key)
67
73
  ensure_not_freed!
74
+ validate_string!(message, "message")
68
75
  validate_length!(secret_key, length_secret_key, "secret_key")
69
76
 
70
77
  message_ptr = FFI::MemoryPointer.new(:uint8, message.bytesize)
71
78
  message_ptr.put_bytes(0, message)
72
79
 
73
- secret_key_ptr = FFI::MemoryPointer.new(:uint8, secret_key.bytesize)
74
- secret_key_ptr.put_bytes(0, secret_key)
75
-
76
80
  # signatureバッファは「最大長」で確保しておく。
77
81
  # 実際に書き込まれた長さは signature_len_ptr 経由で後から読み取る。
78
82
  signature_ptr = FFI::MemoryPointer.new(:uint8, length_signature)
@@ -83,14 +87,10 @@ module PqcRails
83
87
  # read_uint64のような固定幅の読み出しメソッドではなく :size_t シンボルを使う)。
84
88
  signature_len_ptr = FFI::MemoryPointer.new(:size_t, 1)
85
89
 
86
- status = Ffi::Sig.OQS_SIG_sign(
87
- @sig_ptr,
88
- signature_ptr,
89
- signature_len_ptr,
90
- message_ptr,
91
- message.bytesize,
92
- secret_key_ptr
93
- )
90
+ status = SecretBuffer.with(secret_key.bytesize, secret_key) do |secret_key_ptr|
91
+ Ffi::Sig.OQS_SIG_sign(@sig_ptr, signature_ptr, signature_len_ptr, message_ptr, message.bytesize,
92
+ secret_key_ptr)
93
+ end
94
94
  raise PqcRails::Error, "OQS_SIG_sign failed (status=#{status})" unless status.zero?
95
95
 
96
96
  actual_signature_len = signature_len_ptr.read(:size_t)
@@ -101,9 +101,11 @@ module PqcRails
101
101
  # @param message [String] 元のメッセージのバイト列
102
102
  # @param signature [String] 検証する署名のバイト列
103
103
  # @param public_key [String] バイト列
104
- # @return [Boolean] 署名が正当であれば true
104
+ # @return [Boolean] 署名が正当であれば true。文字列でない署名は false
105
+ # @raise [ArgumentError] messageが文字列でない場合、public_keyが文字列でないか長さが違う場合
105
106
  def verify(message, signature, public_key)
106
107
  ensure_not_freed!
108
+ validate_string!(message, "message")
107
109
  validate_length!(public_key, length_public_key, "public_key")
108
110
 
109
111
  # FIPS 204 3.6.2 (Public-Key and Signature Length Checks) は、
@@ -112,6 +114,9 @@ module PqcRails
112
114
  # (verifyの契約上、不正な入力は例外ではなく検証失敗として扱う。上のpublic_keyチェックとは
113
115
  # 非対称だが、public_keyは通常呼び出し側が管理する信頼済みの値である一方、
114
116
  # signatureは検証対象そのもの=攻撃者制御下にありうる値のため、扱いを分けている)。
117
+ # 文字列でない署名(nil等)も同じ理由で検証失敗として扱う。messageは呼び出し側が作る値なので、
118
+ # 鍵と同じくArgumentErrorにする。
119
+ return false unless signature.is_a?(String)
115
120
  return false if signature.bytesize > length_signature
116
121
 
117
122
  message_ptr = FFI::MemoryPointer.new(:uint8, message.bytesize)