pgp_key.rb 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class PGPKey < ApplicationModel
  3. default_scope { order(created_at: :desc, id: :desc) }
  4. before_validation :ensure_ascii_key, :prepare_key_info, on: :create
  5. before_create :prepare_email_addresses, :prepare_domain_alias
  6. validates :fingerprint, uniqueness: { message: __('There is already a PGP key with the same fingerprint.') }
  7. KEY_UID_DELIMITER = ', '.freeze
  8. KEY_BEGIN_REGEXP = %r{-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----}
  9. KEY_END_REGEXP = %r{-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----}
  10. def self.find_by_uid(uid, only_valid: true, secret: false)
  11. find_all_by_uid(uid, only_valid:, secret:).first.tap do |result|
  12. raise ActiveRecord::RecordNotFound, "The PGP key for #{uid} was not found." if result.nil?
  13. end
  14. end
  15. def self.find_all_by_uid(uid, only_valid: true, secret: false)
  16. uid = uid.downcase
  17. email_addresses_query = SqlHelper.new(object: PGPKey).array_contains_one(:email_addresses, uid)
  18. query = if domain_alias_configuration_active?
  19. ["#{email_addresses_query} OR (? LIKE domain_alias)", SqlHelper.quote_like(uid)]
  20. else
  21. email_addresses_query
  22. end
  23. keys_selector = PGPKey.where(query)
  24. keys_selector = keys_selector.where(secret: true) if secret
  25. only_valid ? keys_selector.reject(&:expired?) : keys_selector.all
  26. end
  27. def self.for_recipient_email_addresses!(addresses)
  28. keys = []
  29. not_found = []
  30. addresses.each do |address|
  31. found_keys = find_by_uid(address)
  32. if found_keys.nil?
  33. not_found.push(address)
  34. next
  35. end
  36. keys.push(*found_keys)
  37. end
  38. return keys if not_found.blank?
  39. raise ActiveRecord::RecordNotFound, "The PGP keys for #{not_found.join(KEY_UID_DELIMITER)} could not be found."
  40. end
  41. def self.ascii_key?(given_key)
  42. given_key.match?(KEY_BEGIN_REGEXP) && given_key.match?(KEY_END_REGEXP)
  43. rescue ArgumentError => e
  44. return false if e.message == 'invalid byte sequence in UTF-8'
  45. raise e
  46. end
  47. def self.params_cleanup!(params)
  48. if params[:key].present?
  49. params[:key].strip!
  50. return params
  51. end
  52. return params if !params[:file].is_a? ActionDispatch::Http::UploadedFile
  53. params[:key] = params[:file].tempfile
  54. params
  55. end
  56. def self.convert_binary_key_to_ascii(binary, passphrase)
  57. SecureMailing::PGP::Tool.new.with_private_keyring do |pgp_tool|
  58. pgp_tool.import(binary)
  59. info = pgp_tool.info(binary)
  60. pgp_tool.export(info.fingerprint, passphrase, secret: info.secret).stdout
  61. end
  62. end
  63. def self.domain_alias_configuration_active?
  64. Setting.get('pgp_recipient_alias_configuration')
  65. end
  66. def key_id
  67. fingerprint[-16..]
  68. end
  69. def expired?
  70. return false if expires_at.nil?
  71. expires_at < Time.zone.now
  72. end
  73. def expired!
  74. raise "The PGP keys for #{email_addresses.join(KEY_UID_DELIMITER)} with fingerprint #{fingerprint} have expired at #{expires_at}" if expired?
  75. end
  76. def ensure_ascii_key
  77. raw_key_contents = read_attribute_before_type_cast('key').try(:read)
  78. return if raw_key_contents.nil?
  79. self.key = if self.class.ascii_key?(raw_key_contents)
  80. raw_key_contents
  81. else
  82. self.class.convert_binary_key_to_ascii(raw_key_contents, passphrase)
  83. end
  84. rescue => e
  85. errors.add(:key, e.message)
  86. end
  87. def prepare_key_info
  88. SecureMailing::PGP::Tool.new.with_private_keyring do |pgp_tool|
  89. apply_key_attrs(pgp_tool.info(key))
  90. # Validate the passphrase of a private key.
  91. if secret
  92. pgp_tool.import(key)
  93. pgp_tool.passphrase(fingerprint, passphrase)
  94. end
  95. end
  96. rescue => e
  97. errors.add(:key, e.message)
  98. end
  99. def prepare_email_addresses
  100. self.email_addresses = email_addresses_from_name(name)
  101. end
  102. private
  103. def prepare_domain_alias
  104. if domain_alias.blank?
  105. self.domain_alias = nil
  106. return
  107. end
  108. self.domain_alias = "%@#{domain_alias}"
  109. end
  110. def apply_key_attrs(info)
  111. self.fingerprint = info.fingerprint
  112. self.name = info.uids.join(KEY_UID_DELIMITER)
  113. self.created_at = info.created_at
  114. self.expires_at = info.expires_at
  115. self.secret = info.secret
  116. end
  117. def email_addresses_from_name(name)
  118. entries = name.split(KEY_UID_DELIMITER)
  119. entries.each_with_object([]) do |entry, result|
  120. email_address = entry.split.last.gsub(%r{[<>]}, '').downcase
  121. if !EmailAddressValidation.new(email_address).valid?
  122. Rails.logger.warn <<~TEXT.squish
  123. The PGP key #{fingerprint}
  124. has the malformed email address "#{email_address}"
  125. as part of its UID "#{entry}".
  126. This makes it useless in terms of PGP, please check.
  127. TEXT
  128. next
  129. end
  130. result.push(email_address)
  131. end
  132. end
  133. end