signature_verification.rb 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # frozen_string_literal: true
  2. # Implemented according to HTTP signatures (Draft 6)
  3. # <https://tools.ietf.org/html/draft-cavage-http-signatures-06>
  4. module SignatureVerification
  5. extend ActiveSupport::Concern
  6. include DomainControlHelper
  7. EXPIRATION_WINDOW_LIMIT = 12.hours
  8. CLOCK_SKEW_MARGIN = 1.hour
  9. class SignatureVerificationError < StandardError; end
  10. class SignatureParamsParser < Parslet::Parser
  11. rule(:token) { match("[0-9a-zA-Z!#$%&'*+.^_`|~-]").repeat(1).as(:token) }
  12. rule(:quoted_string) { str('"') >> (qdtext | quoted_pair).repeat.as(:quoted_string) >> str('"') }
  13. # qdtext and quoted_pair are not exactly according to spec but meh
  14. rule(:qdtext) { match('[^\\\\"]') }
  15. rule(:quoted_pair) { str('\\') >> any }
  16. rule(:bws) { match('\s').repeat }
  17. rule(:param) { (token.as(:key) >> bws >> str('=') >> bws >> (token | quoted_string).as(:value)).as(:param) }
  18. rule(:comma) { bws >> str(',') >> bws }
  19. # Old versions of node-http-signature add an incorrect "Signature " prefix to the header
  20. rule(:buggy_prefix) { str('Signature ') }
  21. rule(:params) { buggy_prefix.maybe >> (param >> (comma >> param).repeat).as(:params) }
  22. root(:params)
  23. end
  24. class SignatureParamsTransformer < Parslet::Transform
  25. rule(params: subtree(:p)) do
  26. (p.is_a?(Array) ? p : [p]).each_with_object({}) { |(key, val), h| h[key] = val }
  27. end
  28. rule(param: { key: simple(:key), value: simple(:val) }) do
  29. [key, val]
  30. end
  31. rule(quoted_string: simple(:string)) do
  32. string.to_s
  33. end
  34. rule(token: simple(:string)) do
  35. string.to_s
  36. end
  37. end
  38. def require_signature!
  39. render plain: signature_verification_failure_reason, status: signature_verification_failure_code unless signed_request_account
  40. end
  41. def signed_request?
  42. request.headers['Signature'].present?
  43. end
  44. def signature_verification_failure_reason
  45. @signature_verification_failure_reason
  46. end
  47. def signature_verification_failure_code
  48. @signature_verification_failure_code || 401
  49. end
  50. def signature_key_id
  51. signature_params['keyId']
  52. rescue SignatureVerificationError
  53. nil
  54. end
  55. def signed_request_account
  56. return @signed_request_account if defined?(@signed_request_account)
  57. raise SignatureVerificationError, 'Request not signed' unless signed_request?
  58. raise SignatureVerificationError, 'Incompatible request signature. keyId and signature are required' if missing_required_signature_parameters?
  59. raise SignatureVerificationError, 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)' unless %w(rsa-sha256 hs2019).include?(signature_algorithm)
  60. raise SignatureVerificationError, 'Signed request date outside acceptable time window' unless matches_time_window?
  61. verify_signature_strength!
  62. account = account_from_key_id(signature_params['keyId'])
  63. raise SignatureVerificationError, "Public key not found for key #{signature_params['keyId']}" if account.nil?
  64. signature = Base64.decode64(signature_params['signature'])
  65. compare_signed_string = build_signed_string
  66. return account unless verify_signature(account, signature, compare_signed_string).nil?
  67. account = stoplight_wrap_request { account.possibly_stale? ? account.refresh! : account_refresh_key(account) }
  68. raise SignatureVerificationError, "Public key not found for key #{signature_params['keyId']}" if account.nil?
  69. return account unless verify_signature(account, signature, compare_signed_string).nil?
  70. @signature_verification_failure_reason = "Verification failed for #{account.username}@#{account.domain} #{account.uri} using rsa-sha256 (RSASSA-PKCS1-v1_5 with SHA-256)"
  71. @signed_request_account = nil
  72. rescue SignatureVerificationError => e
  73. @signature_verification_failure_reason = e.message
  74. @signed_request_account = nil
  75. end
  76. def request_body
  77. @request_body ||= request.raw_post
  78. end
  79. private
  80. def signature_params
  81. @signature_params ||= begin
  82. raw_signature = request.headers['Signature']
  83. tree = SignatureParamsParser.new.parse(raw_signature)
  84. SignatureParamsTransformer.new.apply(tree)
  85. end
  86. rescue Parslet::ParseFailed
  87. raise SignatureVerificationError, 'Error parsing signature parameters'
  88. end
  89. def signature_algorithm
  90. signature_params.fetch('algorithm', 'hs2019')
  91. end
  92. def signed_headers
  93. signature_params.fetch('headers', signature_algorithm == 'hs2019' ? '(created)' : 'date').downcase.split(' ')
  94. end
  95. def verify_signature_strength!
  96. raise SignatureVerificationError, 'Mastodon requires the Date header or (created) pseudo-header to be signed' unless signed_headers.include?('date') || signed_headers.include?('(created)')
  97. raise SignatureVerificationError, 'Mastodon requires the Digest header or (request-target) pseudo-header to be signed' unless signed_headers.include?(Request::REQUEST_TARGET) || signed_headers.include?('digest')
  98. raise SignatureVerificationError, 'Mastodon requires the Host header to be signed' unless signed_headers.include?('host')
  99. raise SignatureVerificationError, 'Mastodon requires the Digest header to be signed when doing a POST request' if request.post? && !signed_headers.include?('digest')
  100. end
  101. def verify_signature(account, signature, compare_signed_string)
  102. if account.keypair.public_key.verify(OpenSSL::Digest.new('SHA256'), signature, compare_signed_string)
  103. @signed_request_account = account
  104. @signed_request_account
  105. end
  106. rescue OpenSSL::PKey::RSAError
  107. nil
  108. end
  109. def build_signed_string
  110. signed_headers.map do |signed_header|
  111. if signed_header == Request::REQUEST_TARGET
  112. "#{Request::REQUEST_TARGET}: #{request.method.downcase} #{request.path}"
  113. elsif signed_header == '(created)'
  114. raise SignatureVerificationError, 'Invalid pseudo-header (created) for rsa-sha256' unless signature_algorithm == 'hs2019'
  115. raise SignatureVerificationError, 'Pseudo-header (created) used but corresponding argument missing' if signature_params['created'].blank?
  116. "(created): #{signature_params['created']}"
  117. elsif signed_header == '(expires)'
  118. raise SignatureVerificationError, 'Invalid pseudo-header (expires) for rsa-sha256' unless signature_algorithm == 'hs2019'
  119. raise SignatureVerificationError, 'Pseudo-header (expires) used but corresponding argument missing' if signature_params['expires'].blank?
  120. "(expires): #{signature_params['expires']}"
  121. elsif signed_header == 'digest'
  122. "digest: #{body_digest}"
  123. else
  124. "#{signed_header}: #{request.headers[to_header_name(signed_header)]}"
  125. end
  126. end.join("\n")
  127. end
  128. def matches_time_window?
  129. created_time = nil
  130. expires_time = nil
  131. begin
  132. if signature_algorithm == 'hs2019' && signature_params['created'].present?
  133. created_time = Time.at(signature_params['created'].to_i).utc
  134. elsif request.headers['Date'].present?
  135. created_time = Time.httpdate(request.headers['Date']).utc
  136. end
  137. expires_time = Time.at(signature_params['expires'].to_i).utc if signature_params['expires'].present?
  138. rescue ArgumentError
  139. return false
  140. end
  141. expires_time ||= created_time + 5.minutes unless created_time.nil?
  142. expires_time = [expires_time, created_time + EXPIRATION_WINDOW_LIMIT].min unless created_time.nil?
  143. return false if created_time.present? && created_time > Time.now.utc + CLOCK_SKEW_MARGIN
  144. return false if expires_time.present? && Time.now.utc > expires_time + CLOCK_SKEW_MARGIN
  145. true
  146. end
  147. def body_digest
  148. "SHA-256=#{Digest::SHA256.base64digest(request_body)}"
  149. end
  150. def to_header_name(name)
  151. name.split(/-/).map(&:capitalize).join('-')
  152. end
  153. def missing_required_signature_parameters?
  154. signature_params['keyId'].blank? || signature_params['signature'].blank?
  155. end
  156. def account_from_key_id(key_id)
  157. domain = key_id.start_with?('acct:') ? key_id.split('@').last : key_id
  158. if domain_not_allowed?(domain)
  159. @signature_verification_failure_code = 403
  160. return
  161. end
  162. if key_id.start_with?('acct:')
  163. stoplight_wrap_request { ResolveAccountService.new.call(key_id.gsub(/\Aacct:/, '')) }
  164. elsif !ActivityPub::TagManager.instance.local_uri?(key_id)
  165. account = ActivityPub::TagManager.instance.uri_to_resource(key_id, Account)
  166. account ||= stoplight_wrap_request { ActivityPub::FetchRemoteKeyService.new.call(key_id, id: false) }
  167. account
  168. end
  169. rescue Mastodon::HostValidationError
  170. nil
  171. end
  172. def stoplight_wrap_request(&block)
  173. Stoplight("source:#{request.remote_ip}", &block)
  174. .with_fallback { nil }
  175. .with_threshold(1)
  176. .with_cool_off_time(5.minutes.seconds)
  177. .with_error_handler { |error, handle| error.is_a?(HTTP::Error) || error.is_a?(OpenSSL::SSL::SSLError) ? handle.call(error) : raise(error) }
  178. .run
  179. end
  180. def account_refresh_key(account)
  181. return if account.local? || !account.activitypub?
  182. ActivityPub::FetchRemoteAccountService.new.call(account.uri, only_key: true)
  183. end
  184. end