Module: Gem::Security

Defined in:
lib/rubygems/security.rb,
lib/rubygems/security_option.rb,
lib/rubygems/security/policies.rb,
lib/rubygems/commands/unpack_command.rb

Overview

forward-declare

Defined Under Namespace

Classes: Exception, Policy, Signer, TrustDir

Constant Summary collapse

DIGEST_NAME =

Used internally to select the signing digest from all computed digests

"SHA256"
RSA_DSA_KEY_LENGTH =

Length of keys created by RSA and DSA keys

3072
DEFAULT_KEY_ALGORITHM =

Default algorithm to use when building a key pair

"RSA"
EC_NAME =

Named curve used for Elliptic Curve

"secp384r1"
KEY_CIPHER =

Cipher used to encrypt the key pair used to sign gems. Must be in the list returned by OpenSSL::Cipher.ciphers

OpenSSL::Cipher.new("AES-256-CBC")
ONE_DAY =

One day in seconds

86_400
ONE_YEAR =

One year in seconds

ONE_DAY * 365
EXTENSIONS =

The default set of extensions are:

  • The certificate is not a certificate authority

  • The key for the certificate may be used for key and data encipherment and digital signatures

  • The certificate contains a subject key identifier

{
  "basicConstraints" => "CA:FALSE",
  "keyUsage" =>
    "keyEncipherment,dataEncipherment,digitalSignature",
  "subjectKeyIdentifier" => "hash",
}.freeze
NoSecurity =

No security policy: all package signature checks are disabled.

Policy.new(
  "No Security",
  verify_data: false,
  verify_signer: false,
  verify_chain: false,
  verify_root: false,
  only_trusted: false,
  only_signed: false
)
AlmostNoSecurity =

AlmostNo security policy: only verify that the signing certificate is the one that actually signed the data. Make no attempt to verify the signing certificate chain.

This policy is basically useless. better than nothing, but can still be easily spoofed, and is not recommended.

Policy.new(
  "Almost No Security",
  verify_data: true,
  verify_signer: false,
  verify_chain: false,
  verify_root: false,
  only_trusted: false,
  only_signed: false
)
LowSecurity =

Low security policy: only verify that the signing certificate is actually the gem signer, and that the signing certificate is valid.

This policy is better than nothing, but can still be easily spoofed, and is not recommended.

Policy.new(
  "Low Security",
  verify_data: true,
  verify_signer: true,
  verify_chain: false,
  verify_root: false,
  only_trusted: false,
  only_signed: false
)
MediumSecurity =

Medium security policy: verify the signing certificate, verify the signing certificate chain all the way to the root certificate, and only trust root certificates that we have explicitly allowed trust for.

This security policy is reasonable, but it allows unsigned packages, so a malicious person could simply delete the package signature and pass the gem off as unsigned.

Policy.new(
  "Medium Security",
  verify_data: true,
  verify_signer: true,
  verify_chain: true,
  verify_root: true,
  only_trusted: true,
  only_signed: false
)
HighSecurity =

High security policy: only allow signed gems to be installed, verify the signing certificate, verify the signing certificate chain all the way to the root certificate, and only trust root certificates that we have explicitly allowed trust for.

This security policy is significantly more difficult to bypass, and offers a reasonable guarantee that the contents of the gem have not been altered.

Policy.new(
  "High Security",
  verify_data: true,
  verify_signer: true,
  verify_chain: true,
  verify_root: true,
  only_trusted: true,
  only_signed: true
)
SigningPolicy =

Policy used to verify a certificate and key when signing a gem

Policy.new(
  "Signing Policy",
  verify_data: false,
  verify_signer: true,
  verify_chain: true,
  verify_root: true,
  only_trusted: false,
  only_signed: false
)
Policies =

Hash of configured security policies

{
  "NoSecurity" => NoSecurity,
  "AlmostNoSecurity" => AlmostNoSecurity,
  "LowSecurity" => LowSecurity,
  "MediumSecurity" => MediumSecurity,
  "HighSecurity" => HighSecurity,
  # SigningPolicy is not intended for use by `gem -P` so do not list it
}.freeze

Class Method Summary collapse

Class Method Details

.alt_name_or_x509_entry(certificate, x509_entry) ⇒ Object



385
386
387
388
389
390
391
392
393
# File 'lib/rubygems/security.rb', line 385

def self.alt_name_or_x509_entry(certificate, x509_entry)
  alt_name = certificate.extensions.find do |extension|
    extension.oid == "#{x509_entry}AltName"
  end

  return alt_name.value if alt_name

  certificate.send x509_entry
end

.create_cert(subject, key, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1) ⇒ Object

Creates an unsigned certificate for subject and key. The lifetime of the key is from the current time to age which defaults to one year.

The extensions restrict the key to the indicated uses.



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/rubygems/security.rb', line 401

def self.create_cert(subject, key, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1)
  cert = OpenSSL::X509::Certificate.new

  cert.public_key = get_public_key(key)
  cert.version    = 2
  cert.serial     = serial

  cert.not_before = Time.now
  cert.not_after  = Time.now + age

  cert.subject    = subject

  ef = OpenSSL::X509::ExtensionFactory.new nil, cert

  cert.extensions = extensions.map do |ext_name, value|
    ef.create_extension ext_name, value
  end

  cert
end

.create_cert_email(email, key, age = ONE_YEAR, extensions = EXTENSIONS) ⇒ Object

Creates a self-signed certificate with an issuer and subject from email, a subject alternative name of email and the given extensions for the key.



440
441
442
443
444
445
446
# File 'lib/rubygems/security.rb', line 440

def self.create_cert_email(email, key, age = ONE_YEAR, extensions = EXTENSIONS)
  subject = email_to_name email

  extensions = extensions.merge "subjectAltName" => "email:#{email}"

  create_cert_self_signed subject, key, age, extensions
end

.create_cert_self_signed(subject, key, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1) ⇒ Object

Creates a self-signed certificate with an issuer and subject of subject and the given extensions for the key.



452
453
454
455
456
# File 'lib/rubygems/security.rb', line 452

def self.create_cert_self_signed(subject, key, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1)
  certificate = create_cert subject, key, age, extensions

  sign certificate, key, certificate, age, extensions, serial
end

.create_digest(algorithm = DIGEST_NAME) ⇒ Object

Creates a new digest instance using the specified algorithm. The default is SHA256.



462
463
464
# File 'lib/rubygems/security.rb', line 462

def self.create_digest(algorithm = DIGEST_NAME)
  OpenSSL::Digest.new(algorithm)
end

.create_key(algorithm) ⇒ Object

Creates a new key pair of the specified algorithm. RSA, DSA, and EC are supported.



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/rubygems/security.rb', line 470

def self.create_key(algorithm)
  if defined?(OpenSSL::PKey)
    case algorithm.downcase
    when "dsa"
      OpenSSL::PKey::DSA.new(RSA_DSA_KEY_LENGTH)
    when "rsa"
      OpenSSL::PKey::RSA.new(RSA_DSA_KEY_LENGTH)
    when "ec"
      OpenSSL::PKey::EC.generate(EC_NAME)
    else
      raise Gem::Security::Exception,
      "#{algorithm} algorithm not found. RSA, DSA, and EC algorithms are supported."
    end
  end
end

.email_to_name(email_address) ⇒ Object

Turns email_address into an OpenSSL::X509::Name



489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/rubygems/security.rb', line 489

def self.email_to_name(email_address)
  email_address = email_address.gsub(/[^\[email protected]]+/i, "_")

  cn, dcs = email_address.split "@"

  dcs = dcs.split "."

  OpenSSL::X509::Name.new([
    ["CN", cn],
    *dcs.map {|dc| ["DC", dc] },
  ])
end

.get_public_key(key) ⇒ Object

Gets the right public key from a PKey instance



425
426
427
428
429
430
431
432
433
# File 'lib/rubygems/security.rb', line 425

def self.get_public_key(key)
  # Ruby 3.0 (Ruby/OpenSSL 2.2) or later
  return OpenSSL::PKey.read(key.public_to_der) if key.respond_to?(:public_to_der)
  return key.public_key unless key.is_a?(OpenSSL::PKey::EC)

  ec_key = OpenSSL::PKey::EC.new(key.group.curve_name)
  ec_key.public_key = key.public_key
  ec_key
end

.re_sign(expired_certificate, private_key, age = ONE_YEAR, extensions = EXTENSIONS) ⇒ Object

Signs expired_certificate with private_key if the keys match and the expired certificate was self-signed. – TODO increment serial



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

def self.re_sign(expired_certificate, private_key, age = ONE_YEAR, extensions = EXTENSIONS)
  raise Gem::Security::Exception,
        "incorrect signing key for re-signing " +
        expired_certificate.subject.to_s unless
    expired_certificate.check_private_key(private_key)

  unless expired_certificate.subject.to_s ==
         expired_certificate.issuer.to_s
    subject = alt_name_or_x509_entry expired_certificate, :subject
    issuer  = alt_name_or_x509_entry expired_certificate, :issuer

    raise Gem::Security::Exception,
          "#{subject} is not self-signed, contact #{issuer} " \
          "to obtain a valid certificate"
  end

  serial = expired_certificate.serial + 1

  create_cert_self_signed(expired_certificate.subject, private_key, age,
                          extensions, serial)
end

.resetObject

Resets the trust directory for verifying gems.



533
534
535
# File 'lib/rubygems/security.rb', line 533

def self.reset
  @trust_dir = nil
end

.sign(certificate, signing_key, signing_cert, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1) ⇒ Object

Sign the public key from certificate with the signing_key and signing_cert, using the Gem::Security::DIGEST_NAME. Uses the default certificate validity range and extensions.

Returns the newly signed certificate.



544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/rubygems/security.rb', line 544

def self.sign(certificate, signing_key, signing_cert, age = ONE_YEAR, extensions = EXTENSIONS, serial = 1)
  signee_subject = certificate.subject
  signee_key     = certificate.public_key

  alt_name = certificate.extensions.find do |extension|
    extension.oid == "subjectAltName"
  end

  extensions = extensions.merge "subjectAltName" => alt_name.value if
    alt_name

  issuer_alt_name = signing_cert.extensions.find do |extension|
    extension.oid == "subjectAltName"
  end

  extensions = extensions.merge "issuerAltName" => issuer_alt_name.value if
    issuer_alt_name

  signed = create_cert signee_subject, signee_key, age, extensions, serial
  signed.issuer = signing_cert.subject

  signed.sign signing_key, Gem::Security::DIGEST_NAME
end

.trust_dirObject

Returns a Gem::Security::TrustDir which wraps the directory where trusted certificates live.



572
573
574
575
576
577
578
# File 'lib/rubygems/security.rb', line 572

def self.trust_dir
  return @trust_dir if @trust_dir

  dir = File.join Gem.user_home, ".gem", "trust"

  @trust_dir ||= Gem::Security::TrustDir.new dir
end

.trusted_certificates(&block) ⇒ Object

Enumerates the trusted certificates via Gem::Security::TrustDir.



583
584
585
# File 'lib/rubygems/security.rb', line 583

def self.trusted_certificates(&block)
  trust_dir.each_certificate(&block)
end

.write(pemmable, path, permissions = 0o600, passphrase = nil, cipher = KEY_CIPHER) ⇒ Object

Writes pemmable, which must respond to to_pem to path with the given permissions. If passed cipher and passphrase those arguments will be passed to to_pem.



592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/rubygems/security.rb', line 592

def self.write(pemmable, path, permissions = 0o600, passphrase = nil, cipher = KEY_CIPHER)
  path = File.expand_path path

  File.open path, "wb", permissions do |io|
    if passphrase && cipher
      io.write pemmable.to_pem cipher, passphrase
    else
      io.write pemmable.to_pem
    end
  end

  path
end