Module: Altcha::V2

Defined in:
lib/altcha/v2.rb

Overview

V2 proof-of-work: find a counter C such that KDF(nonce+C) starts with keyPrefix. Supports SHA-, PBKDF2/SHA-, and SCRYPT algorithms via OpenSSL::KDF.

Defined Under Namespace

Classes: Challenge, ChallengeParameters, CreateChallengeOptions, Payload, ServerSignaturePayload, Solution, VerifyServerSignatureResult, VerifySolutionResult

Constant Summary collapse

DEFAULT_KEY_LENGTH =
32
DEFAULT_KEY_PREFIX =
'00'

Class Method Summary collapse

Class Method Details

.canonical_json(obj) ⇒ Object

Produces a canonical (sorted-key, compact) JSON string.



254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/altcha/v2.rb', line 254

def self.canonical_json(obj)
  case obj
  when Hash
    pairs = obj.sort_by { |k, _| k.to_s }
               .map { |k, v| "#{k.to_s.to_json}:#{canonical_json(v)}" }
    "{#{pairs.join(',')}}"
  when Array
    "[#{obj.map { |v| canonical_json(v) }.join(',')}]"
  else
    obj.to_json
  end
end

.constant_time_equal?(a, b) ⇒ Boolean

Constant-time string comparison.

Returns:

  • (Boolean)


345
346
347
348
349
350
351
# File 'lib/altcha/v2.rb', line 345

def self.constant_time_equal?(a, b)
  return false if a.bytesize != b.bytesize

  OpenSSL.fixed_length_secure_compare(a, b)
rescue ArgumentError
  false
end

.create_challenge(options) ⇒ Challenge

Creates a v2 proof-of-work challenge.

Parameters:

Returns:



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/altcha/v2.rb', line 356

def self.create_challenge(options)
  key_length        = options.key_length        || DEFAULT_KEY_LENGTH
  key_prefix        = options.key_prefix        || DEFAULT_KEY_PREFIX
  key_prefix_length = options.key_prefix_length || (key_length / 2)
  expires_at        = options.expires_at.is_a?(Time) ? options.expires_at.to_i : options.expires_at

  parameters = ChallengeParameters.new(
    algorithm:   options.algorithm,
    nonce:       OpenSSL::Random.random_bytes(16).unpack1('H*'),
    salt:        OpenSSL::Random.random_bytes(16).unpack1('H*'),
    cost:        options.cost,
    key_length:  key_length,
    key_prefix:  key_prefix,
    memory_cost: options.memory_cost,
    parallelism: options.parallelism,
    expires_at:  expires_at,
    data:        options.data
  )

  derived_key_bytes = nil

  if options.counter
    nonce_bytes       = [parameters.nonce].pack('H*')
    salt_bytes        = [parameters.salt].pack('H*')
    password_bytes    = make_password(nonce_bytes, options.counter)
    derived_key_bytes = derive_key(parameters, salt_bytes, password_bytes)
    parameters.key_prefix = derived_key_bytes[0, key_prefix_length].unpack1('H*')
  end

  if options.hmac_signature_secret
    if derived_key_bytes && options.hmac_key_signature_secret
      parameters.key_signature = hmac_hex(
        derived_key_bytes,
        options.hmac_key_signature_secret
      )
    end
    signature = hmac_hex(
      canonical_json(parameters.to_h),
      options.hmac_signature_secret
    )
    Challenge.new(parameters: parameters, signature: signature)
  else
    Challenge.new(parameters: parameters)
  end
end

.derive_key(parameters, salt_bytes, password_bytes) ⇒ Object

Derives a key from the given parameters, salt, and password bytes.



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/altcha/v2.rb', line 274

def self.derive_key(parameters, salt_bytes, password_bytes)
  alg     = parameters.algorithm
  key_len = parameters.key_length || DEFAULT_KEY_LENGTH

  case alg
  when 'ARGON2ID'
    begin
      require 'argon2/kdf'
    rescue LoadError
      raise LoadError, "Add 'argon2-kdf' to your Gemfile to use the ARGON2ID algorithm"
    end
    # argon2-kdf's `m` is log2(memory_cost_in_KiB) — convert from KiB.
    m_kib = parameters.memory_cost || 65536
    Argon2::KDF.argon2id(
      password_bytes,
      salt:   salt_bytes,
      t:      parameters.cost,
      m:      Math.log2(m_kib).round,
      p:      parameters.parallelism || 1,
      length: key_len
    )
  when /\APBKDF2\//
    digest = case alg
             when 'PBKDF2/SHA-512' then 'SHA512'
             when 'PBKDF2/SHA-384' then 'SHA384'
             else 'SHA256'
             end
    OpenSSL::KDF.pbkdf2_hmac(
      password_bytes,
      salt:       salt_bytes,
      iterations: parameters.cost,
      length:     key_len,
      hash:       digest
    )
  when 'SCRYPT'
    OpenSSL::KDF.scrypt(
      password_bytes,
      salt:   salt_bytes,
      N:      parameters.cost,
      r:      parameters.memory_cost || 8,
      p:      parameters.parallelism || 1,
      length: key_len
    )
  else
    # SHA-256 / SHA-384 / SHA-512 (iterative)
    digest     = case alg
                 when 'SHA-512' then 'SHA512'
                 when 'SHA-384' then 'SHA384'
                 else 'SHA256'
                 end
    iterations = [parameters.cost, 1].max
    buf        = salt_bytes.b + password_bytes.b
    derived    = nil
    iterations.times do |i|
      derived = OpenSSL::Digest.digest(digest, i.zero? ? buf : derived)
    end
    derived[0, key_len]
  end
end

.hmac_hex(data, key, algorithm = 'SHA-256') ⇒ Object

Computes an HMAC hex digest using the specified algorithm ('SHA-256' etc.).



335
336
337
338
339
340
341
342
# File 'lib/altcha/v2.rb', line 335

def self.hmac_hex(data, key, algorithm = 'SHA-256')
  digest = case algorithm
           when 'SHA-384' then 'SHA384'
           when 'SHA-512' then 'SHA512'
           else 'SHA256'
           end
  OpenSSL::HMAC.hexdigest(digest, key, data)
end

.make_password(nonce_bytes, counter) ⇒ Object

Builds the password buffer (nonce bytes + counter) used for key derivation. Counter is encoded as a 4-byte big-endian unsigned integer.



269
270
271
# File 'lib/altcha/v2.rb', line 269

def self.make_password(nonce_bytes, counter)
  nonce_bytes + [counter].pack('N')
end

.parse_verification_data(data, array_fields: %w[fields reasons])) ⇒ Object

Parses a URL-encoded verification_data string into a typed Hash. Booleans, integers, and floats are auto-detected; comma-separated fields listed in array_fields are converted to arrays.



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/altcha/v2.rb', line 507

def self.parse_verification_data(data, array_fields: %w[fields reasons])
  result = {}
  URI.decode_www_form(data).each do |key, value|
    result[key] = if value == 'true'
                    true
                  elsif value == 'false'
                    false
                  elsif /\A\d+\z/.match?(value)
                    value.to_i
                  elsif /\A\d+\.\d+\z/.match?(value)
                    value.to_f
                  elsif array_fields.include?(key) && !value.empty?
                    value.strip.split(',')
                  else
                    value.strip
                  end
  end
  result
rescue StandardError
  nil
end

.solve_challenge(challenge, max_counter: nil, counter_start: 0, counter_step: 1) ⇒ Solution?

Solves a v2 challenge by brute-forcing counter values.

Parameters:

  • challenge (Challenge)
  • max_counter (Integer, nil) (defaults to: nil)

    Safety cap; nil means no limit.

  • counter_start (Integer) (defaults to: 0)
  • counter_step (Integer) (defaults to: 1)

Returns:



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/altcha/v2.rb', line 408

def self.solve_challenge(challenge, max_counter: nil, counter_start: 0, counter_step: 1)
  parameters  = challenge.parameters
  nonce_bytes = [parameters.nonce].pack('H*')
  salt_bytes  = [parameters.salt].pack('H*')
  key_prefix  = parameters.key_prefix
  start_time  = Time.now
  counter     = counter_start

  loop do
    return nil if max_counter && counter > max_counter

    password_bytes    = make_password(nonce_bytes, counter)
    derived_key_bytes = derive_key(parameters, salt_bytes, password_bytes)
    derived_key_hex   = derived_key_bytes.unpack1('H*')

    if derived_key_hex.start_with?(key_prefix)
      return Solution.new(
        counter:     counter,
        derived_key: derived_key_hex,
        time:        ((Time.now - start_time) * 1000).round
      )
    end

    counter += counter_step
  end
end

.verify_fields_hash(form_data:, fields:, fields_hash:, algorithm: 'SHA-256') ⇒ Boolean

Verifies the SHA hash of selected form fields.

Parameters:

  • form_data (Hash)
  • fields (Array<String>)
  • fields_hash (String)

    Expected hex digest.

  • algorithm (String) (defaults to: 'SHA-256')

    Defaults to 'SHA-256'.

Returns:

  • (Boolean)


535
536
537
538
539
540
541
542
543
# File 'lib/altcha/v2.rb', line 535

def self.verify_fields_hash(form_data:, fields:, fields_hash:, algorithm: 'SHA-256')
  digest = case algorithm
           when 'SHA-512' then 'SHA512'
           when 'SHA-384' then 'SHA384'
           else 'SHA256'
           end
  lines = fields.map { |f| form_data[f].to_s }
  OpenSSL::Digest.hexdigest(digest, lines.join("\n")) == fields_hash
end

.verify_server_signature(payload:, hmac_secret:) ⇒ VerifyServerSignatureResult

Verifies a server signature payload from the ALTCHA backend.

Parameters:

Returns:



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/altcha/v2.rb', line 549

def self.verify_server_signature(payload:, hmac_secret:)
  start_time = Time.now

  digest = case payload.algorithm
           when 'SHA-512' then 'SHA512'
           when 'SHA-384' then 'SHA384'
           else 'SHA256'
           end

  hash_bytes        = OpenSSL::Digest.digest(digest, payload.verification_data)
  expected_sig      = hmac_hex(hash_bytes, hmac_secret, payload.algorithm)
  verification_data = parse_verification_data(payload.verification_data)

  expired = !!(verification_data &&
               verification_data['expire'] &&
               verification_data['expire'] < Time.now.to_i)

  invalid_signature = !constant_time_equal?(payload.signature.to_s, expected_sig)

  invalid_solution = verification_data.nil? ||
                     verification_data['verified'] != true ||
                     payload.verified != true

  verified = !expired && !invalid_signature && !invalid_solution

  VerifyServerSignatureResult.new(
    expired:           expired,
    invalid_signature: invalid_signature,
    invalid_solution:  invalid_solution,
    time:              elapsed_ms(start_time),
    verification_data: verification_data,
    verified:          verified
  )
end

.verify_solution(challenge, solution, hmac_signature_secret:, hmac_key_signature_secret: nil, hmac_algorithm: 'SHA-256') ⇒ VerifySolutionResult

Verifies a v2 solution against its challenge.

Parameters:

  • challenge (Challenge)
  • solution (Solution)
  • hmac_signature_secret (String)

    Must match what was used in create_challenge.

  • hmac_key_signature_secret (String, nil) (defaults to: nil)

    Required when keySignature is present.

  • hmac_algorithm (String) (defaults to: 'SHA-256')

    Defaults to 'SHA-256'.

Returns:



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/altcha/v2.rb', line 442

def self.verify_solution(challenge, solution, hmac_signature_secret:,
                         hmac_key_signature_secret: nil,
                         hmac_algorithm: 'SHA-256')
  start_time = Time.now

  # 1. Expiration check.
  if challenge.parameters.expires_at && Time.now.to_i > challenge.parameters.expires_at
    return VerifySolutionResult.new(
      expired: true, invalid_signature: nil, invalid_solution: nil,
      time: elapsed_ms(start_time), verified: false
    )
  end

  # 2. Signature presence check.
  unless challenge.signature
    return VerifySolutionResult.new(
      expired: false, invalid_signature: true, invalid_solution: nil,
      time: elapsed_ms(start_time), verified: false
    )
  end

  # 3. Verify challenge signature (tamper detection).
  expected_sig = hmac_hex(
    canonical_json(challenge.parameters.to_h),
    hmac_signature_secret,
    hmac_algorithm
  )
  unless constant_time_equal?(challenge.signature, expected_sig)
    return VerifySolutionResult.new(
      expired: false, invalid_signature: true, invalid_solution: nil,
      time: elapsed_ms(start_time), verified: false
    )
  end

  # 4a. Fast path: verify via key signature when available.
  if challenge.parameters.key_signature && hmac_key_signature_secret
    derived_key_bytes = [solution.derived_key].pack('H*')
    expected_key_sig  = hmac_hex(derived_key_bytes, hmac_key_signature_secret, hmac_algorithm)
    valid = constant_time_equal?(challenge.parameters.key_signature, expected_key_sig)
    return VerifySolutionResult.new(
      expired: false, invalid_signature: false, invalid_solution: !valid,
      time: elapsed_ms(start_time), verified: valid
    )
  end

  # 4b. Slow path: re-derive key from the submitted counter and compare,
  # and require it to satisfy the signed key prefix.
  nonce_bytes       = [challenge.parameters.nonce].pack('H*')
  salt_bytes        = [challenge.parameters.salt].pack('H*')
  password_bytes    = make_password(nonce_bytes, solution.counter)
  derived_key_bytes = derive_key(challenge.parameters, salt_bytes, password_bytes)
  derived_key_hex   = derived_key_bytes.unpack1('H*')
  key_matches       = constant_time_equal?(derived_key_hex, solution.derived_key)
  prefix_matches    = derived_key_hex.start_with?(challenge.parameters.key_prefix)
  invalid           = !(key_matches && prefix_matches)

  VerifySolutionResult.new(
    expired: false, invalid_signature: false, invalid_solution: invalid,
    time: elapsed_ms(start_time), verified: !invalid
  )
end