outgoing.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. class SecureMailing::SMIME::Outgoing < SecureMailing::Backend::Handler
  2. def initialize(mail, security)
  3. @mail = mail
  4. @security = security
  5. end
  6. def process
  7. return if !process?
  8. if @security[:sign][:success] && @security[:encryption][:success]
  9. processed = encrypt(signed)
  10. log('sign', 'success')
  11. log('encryption', 'success')
  12. elsif @security[:sign][:success]
  13. processed = Mail.new(signed)
  14. log('sign', 'success')
  15. elsif @security[:encryption][:success]
  16. processed = encrypt(@mail.encoded)
  17. log('encryption', 'success')
  18. end
  19. overwrite_mail(processed)
  20. end
  21. def process?
  22. return false if @security.blank?
  23. return false if @security[:type] != 'S/MIME'
  24. @security[:sign][:success] || @security[:encryption][:success]
  25. end
  26. def overwrite_mail(processed)
  27. @mail.body = nil
  28. @mail.body = processed.body.encoded
  29. @mail.content_disposition = processed.content_disposition
  30. @mail.content_transfer_encoding = processed.content_transfer_encoding
  31. @mail.content_type = processed.content_type
  32. end
  33. def signed
  34. from = @mail.from.first
  35. cert_model = SMIMECertificate.for_sender_email_address(from)
  36. raise "Unable to find ssl private key for '#{from}'" if !cert_model
  37. raise "Expired certificate for #{from} (fingerprint #{cert_model.fingerprint}) with #{cert_model.not_before_at} to #{cert_model.not_after_at}" if !@security[:sign][:allow_expired] && cert_model.expired?
  38. private_key = OpenSSL::PKey::RSA.new(cert_model.private_key, cert_model.private_key_secret)
  39. OpenSSL::PKCS7.write_smime(OpenSSL::PKCS7.sign(cert_model.parsed, private_key, @mail.encoded, [], OpenSSL::PKCS7::DETACHED))
  40. rescue => e
  41. log('sign', 'failed', e.message)
  42. raise
  43. end
  44. def encrypt(data)
  45. certificates = SMIMECertificate.for_recipipent_email_addresses!(@mail.to)
  46. expired_cert = certificates.detect(&:expired?)
  47. raise "Expired certificates for cert with #{expired_cert.not_before_at} to #{expired_cert.not_after_at}" if !@security[:encryption][:allow_expired] && expired_cert.present?
  48. Mail.new(OpenSSL::PKCS7.write_smime(OpenSSL::PKCS7.encrypt(certificates.map(&:parsed), data, cipher)))
  49. rescue => e
  50. log('encryption', 'failed', e.message)
  51. raise
  52. end
  53. def cipher
  54. @cipher ||= OpenSSL::Cipher.new('AES-128-CBC')
  55. end
  56. def log(action, status, error = nil)
  57. HttpLog.create(
  58. direction: 'out',
  59. facility: 'S/MIME',
  60. url: "#{@mail[:from]} -> #{@mail[:to]}",
  61. status: status,
  62. ip: nil,
  63. request: @security,
  64. response: { error: error },
  65. method: action,
  66. created_by_id: 1,
  67. updated_by_id: 1,
  68. )
  69. end
  70. end