signature_verification.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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(:param)) do
  26. (param.is_a?(Array) ? param : [param]).each_with_object({}) { |(key, value), hash| hash[key] = value }
  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_account_signature!
  39. render json: signature_verification_failure_reason, status: signature_verification_failure_code unless signed_request_account
  40. end
  41. def require_actor_signature!
  42. render json: signature_verification_failure_reason, status: signature_verification_failure_code unless signed_request_actor
  43. end
  44. def signed_request?
  45. request.headers['Signature'].present?
  46. end
  47. def signature_verification_failure_reason
  48. @signature_verification_failure_reason
  49. end
  50. def signature_verification_failure_code
  51. @signature_verification_failure_code || 401
  52. end
  53. def signature_key_id
  54. signature_params['keyId']
  55. rescue SignatureVerificationError
  56. nil
  57. end
  58. def signed_request_account
  59. signed_request_actor.is_a?(Account) ? signed_request_actor : nil
  60. end
  61. def signed_request_actor
  62. return @signed_request_actor if defined?(@signed_request_actor)
  63. raise SignatureVerificationError, 'Request not signed' unless signed_request?
  64. raise SignatureVerificationError, 'Incompatible request signature. keyId and signature are required' if missing_required_signature_parameters?
  65. raise SignatureVerificationError, 'Unsupported signature algorithm (only rsa-sha256 and hs2019 are supported)' unless %w(rsa-sha256 hs2019).include?(signature_algorithm)
  66. raise SignatureVerificationError, 'Signed request date outside acceptable time window' unless matches_time_window?
  67. verify_signature_strength!
  68. verify_body_digest!
  69. actor = actor_from_key_id(signature_params['keyId'])
  70. raise SignatureVerificationError, "Public key not found for key #{signature_params['keyId']}" if actor.nil?
  71. signature = Base64.decode64(signature_params['signature'])
  72. compare_signed_string = build_signed_string
  73. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  74. actor = stoplight_wrap_request { actor_refresh_key!(actor) }
  75. raise SignatureVerificationError, "Could not refresh public key #{signature_params['keyId']}" if actor.nil?
  76. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  77. fail_with! "Verification failed for #{actor.to_log_human_identifier} #{actor.uri} using rsa-sha256 (RSASSA-PKCS1-v1_5 with SHA-256)", signed_string: compare_signed_string, signature: signature_params['signature']
  78. rescue SignatureVerificationError => e
  79. fail_with! e.message
  80. rescue HTTP::Error, OpenSSL::SSL::SSLError => e
  81. fail_with! "Failed to fetch remote data: #{e.message}"
  82. rescue Mastodon::UnexpectedResponseError
  83. fail_with! 'Failed to fetch remote data (got unexpected reply from server)'
  84. rescue Stoplight::Error::RedLight
  85. fail_with! 'Fetching attempt skipped because of recent connection failure'
  86. end
  87. def request_body
  88. @request_body ||= request.raw_post
  89. end
  90. private
  91. def fail_with!(message, **options)
  92. Rails.logger.debug { "Signature verification failed: #{message}" }
  93. @signature_verification_failure_reason = { error: message }.merge(options)
  94. @signed_request_actor = nil
  95. end
  96. def signature_params
  97. @signature_params ||= begin
  98. raw_signature = request.headers['Signature']
  99. tree = SignatureParamsParser.new.parse(raw_signature)
  100. SignatureParamsTransformer.new.apply(tree)
  101. end
  102. rescue Parslet::ParseFailed
  103. raise SignatureVerificationError, 'Error parsing signature parameters'
  104. end
  105. def signature_algorithm
  106. signature_params.fetch('algorithm', 'hs2019')
  107. end
  108. def signed_headers
  109. signature_params.fetch('headers', signature_algorithm == 'hs2019' ? '(created)' : 'date').downcase.split
  110. end
  111. def verify_signature_strength!
  112. raise SignatureVerificationError, 'Mastodon requires the Date header or (created) pseudo-header to be signed' unless signed_headers.include?('date') || signed_headers.include?('(created)')
  113. 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')
  114. raise SignatureVerificationError, 'Mastodon requires the Host header to be signed when doing a GET request' if request.get? && !signed_headers.include?('host')
  115. raise SignatureVerificationError, 'Mastodon requires the Digest header to be signed when doing a POST request' if request.post? && !signed_headers.include?('digest')
  116. end
  117. def verify_body_digest!
  118. return unless signed_headers.include?('digest')
  119. raise SignatureVerificationError, 'Digest header missing' unless request.headers.key?('Digest')
  120. digests = request.headers['Digest'].split(',').map { |digest| digest.split('=', 2) }.map { |key, value| [key.downcase, value] }
  121. sha256 = digests.assoc('sha-256')
  122. raise SignatureVerificationError, "Mastodon only supports SHA-256 in Digest header. Offered algorithms: #{digests.map(&:first).join(', ')}" if sha256.nil?
  123. return if body_digest == sha256[1]
  124. digest_size = begin
  125. Base64.strict_decode64(sha256[1].strip).length
  126. rescue ArgumentError
  127. raise SignatureVerificationError, "Invalid Digest value. The provided Digest value is not a valid base64 string. Given digest: #{sha256[1]}"
  128. end
  129. raise SignatureVerificationError, "Invalid Digest value. The provided Digest value is not a SHA-256 digest. Given digest: #{sha256[1]}" if digest_size != 32
  130. raise SignatureVerificationError, "Invalid Digest value. Computed SHA-256 digest: #{body_digest}; given: #{sha256[1]}"
  131. end
  132. def verify_signature(actor, signature, compare_signed_string)
  133. if actor.keypair.public_key.verify(OpenSSL::Digest.new('SHA256'), signature, compare_signed_string)
  134. @signed_request_actor = actor
  135. @signed_request_actor
  136. end
  137. rescue OpenSSL::PKey::RSAError
  138. nil
  139. end
  140. def build_signed_string
  141. signed_headers.map do |signed_header|
  142. case signed_header
  143. when Request::REQUEST_TARGET
  144. "#{Request::REQUEST_TARGET}: #{request.method.downcase} #{request.path}"
  145. when '(created)'
  146. raise SignatureVerificationError, 'Invalid pseudo-header (created) for rsa-sha256' unless signature_algorithm == 'hs2019'
  147. raise SignatureVerificationError, 'Pseudo-header (created) used but corresponding argument missing' if signature_params['created'].blank?
  148. "(created): #{signature_params['created']}"
  149. when '(expires)'
  150. raise SignatureVerificationError, 'Invalid pseudo-header (expires) for rsa-sha256' unless signature_algorithm == 'hs2019'
  151. raise SignatureVerificationError, 'Pseudo-header (expires) used but corresponding argument missing' if signature_params['expires'].blank?
  152. "(expires): #{signature_params['expires']}"
  153. else
  154. "#{signed_header}: #{request.headers[to_header_name(signed_header)]}"
  155. end
  156. end.join("\n")
  157. end
  158. def matches_time_window?
  159. created_time = nil
  160. expires_time = nil
  161. begin
  162. if signature_algorithm == 'hs2019' && signature_params['created'].present?
  163. created_time = Time.at(signature_params['created'].to_i).utc
  164. elsif request.headers['Date'].present?
  165. created_time = Time.httpdate(request.headers['Date']).utc
  166. end
  167. expires_time = Time.at(signature_params['expires'].to_i).utc if signature_params['expires'].present?
  168. rescue ArgumentError => e
  169. raise SignatureVerificationError, "Invalid Date header: #{e.message}"
  170. end
  171. expires_time ||= created_time + 5.minutes unless created_time.nil?
  172. expires_time = [expires_time, created_time + EXPIRATION_WINDOW_LIMIT].min unless created_time.nil?
  173. return false if created_time.present? && created_time > Time.now.utc + CLOCK_SKEW_MARGIN
  174. return false if expires_time.present? && Time.now.utc > expires_time + CLOCK_SKEW_MARGIN
  175. true
  176. end
  177. def body_digest
  178. @body_digest ||= Digest::SHA256.base64digest(request_body)
  179. end
  180. def to_header_name(name)
  181. name.split('-').map(&:capitalize).join('-')
  182. end
  183. def missing_required_signature_parameters?
  184. signature_params['keyId'].blank? || signature_params['signature'].blank?
  185. end
  186. def actor_from_key_id(key_id)
  187. domain = key_id.start_with?('acct:') ? key_id.split('@').last : key_id
  188. if domain_not_allowed?(domain)
  189. @signature_verification_failure_code = 403
  190. return
  191. end
  192. if key_id.start_with?('acct:')
  193. stoplight_wrap_request { ResolveAccountService.new.call(key_id.delete_prefix('acct:'), suppress_errors: false) }
  194. elsif !ActivityPub::TagManager.instance.local_uri?(key_id)
  195. account = ActivityPub::TagManager.instance.uri_to_actor(key_id)
  196. account ||= stoplight_wrap_request { ActivityPub::FetchRemoteKeyService.new.call(key_id, id: false, suppress_errors: false) }
  197. account
  198. end
  199. rescue Mastodon::PrivateNetworkAddressError => e
  200. raise SignatureVerificationError, "Requests to private network addresses are disallowed (tried to query #{e.host})"
  201. rescue Mastodon::HostValidationError, ActivityPub::FetchRemoteActorService::Error, ActivityPub::FetchRemoteKeyService::Error, Webfinger::Error => e
  202. raise SignatureVerificationError, e.message
  203. end
  204. def stoplight_wrap_request(&block)
  205. Stoplight("source:#{request.remote_ip}", &block)
  206. .with_threshold(1)
  207. .with_cool_off_time(5.minutes.seconds)
  208. .with_error_handler { |error, handle| error.is_a?(HTTP::Error) || error.is_a?(OpenSSL::SSL::SSLError) ? handle.call(error) : raise(error) }
  209. .run
  210. end
  211. def actor_refresh_key!(actor)
  212. return if actor.local? || !actor.activitypub?
  213. return actor.refresh! if actor.respond_to?(:refresh!) && actor.possibly_stale?
  214. ActivityPub::FetchRemoteActorService.new.call(actor.uri, only_key: true, suppress_errors: false)
  215. rescue Mastodon::PrivateNetworkAddressError => e
  216. raise SignatureVerificationError, "Requests to private network addresses are disallowed (tried to query #{e.host})"
  217. rescue Mastodon::HostValidationError, ActivityPub::FetchRemoteActorService::Error, Webfinger::Error => e
  218. raise SignatureVerificationError, e.message
  219. end
  220. end