signature_verification.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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(include_query_string: true)
  73. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  74. # Compatibility quirk with older Mastodon versions
  75. compare_signed_string = build_signed_string(include_query_string: false)
  76. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  77. actor = stoplight_wrap_request { actor_refresh_key!(actor) }
  78. raise SignatureVerificationError, "Could not refresh public key #{signature_params['keyId']}" if actor.nil?
  79. compare_signed_string = build_signed_string(include_query_string: true)
  80. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  81. # Compatibility quirk with older Mastodon versions
  82. compare_signed_string = build_signed_string(include_query_string: false)
  83. return actor unless verify_signature(actor, signature, compare_signed_string).nil?
  84. 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']
  85. rescue SignatureVerificationError => e
  86. fail_with! e.message
  87. rescue HTTP::Error, OpenSSL::SSL::SSLError => e
  88. fail_with! "Failed to fetch remote data: #{e.message}"
  89. rescue Mastodon::UnexpectedResponseError
  90. fail_with! 'Failed to fetch remote data (got unexpected reply from server)'
  91. rescue Stoplight::Error::RedLight
  92. fail_with! 'Fetching attempt skipped because of recent connection failure'
  93. end
  94. def request_body
  95. @request_body ||= request.raw_post
  96. end
  97. private
  98. def fail_with!(message, **options)
  99. Rails.logger.debug { "Signature verification failed: #{message}" }
  100. @signature_verification_failure_reason = { error: message }.merge(options)
  101. @signed_request_actor = nil
  102. end
  103. def signature_params
  104. @signature_params ||= begin
  105. raw_signature = request.headers['Signature']
  106. tree = SignatureParamsParser.new.parse(raw_signature)
  107. SignatureParamsTransformer.new.apply(tree)
  108. end
  109. rescue Parslet::ParseFailed
  110. raise SignatureVerificationError, 'Error parsing signature parameters'
  111. end
  112. def signature_algorithm
  113. signature_params.fetch('algorithm', 'hs2019')
  114. end
  115. def signed_headers
  116. signature_params.fetch('headers', signature_algorithm == 'hs2019' ? '(created)' : 'date').downcase.split
  117. end
  118. def verify_signature_strength!
  119. raise SignatureVerificationError, 'Mastodon requires the Date header or (created) pseudo-header to be signed' unless signed_headers.include?('date') || signed_headers.include?('(created)')
  120. 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')
  121. raise SignatureVerificationError, 'Mastodon requires the Host header to be signed when doing a GET request' if request.get? && !signed_headers.include?('host')
  122. raise SignatureVerificationError, 'Mastodon requires the Digest header to be signed when doing a POST request' if request.post? && !signed_headers.include?('digest')
  123. end
  124. def verify_body_digest!
  125. return unless signed_headers.include?('digest')
  126. raise SignatureVerificationError, 'Digest header missing' unless request.headers.key?('Digest')
  127. digests = request.headers['Digest'].split(',').map { |digest| digest.split('=', 2) }.map { |key, value| [key.downcase, value] }
  128. sha256 = digests.assoc('sha-256')
  129. raise SignatureVerificationError, "Mastodon only supports SHA-256 in Digest header. Offered algorithms: #{digests.map(&:first).join(', ')}" if sha256.nil?
  130. return if body_digest == sha256[1]
  131. digest_size = begin
  132. Base64.strict_decode64(sha256[1].strip).length
  133. rescue ArgumentError
  134. raise SignatureVerificationError, "Invalid Digest value. The provided Digest value is not a valid base64 string. Given digest: #{sha256[1]}"
  135. end
  136. raise SignatureVerificationError, "Invalid Digest value. The provided Digest value is not a SHA-256 digest. Given digest: #{sha256[1]}" if digest_size != 32
  137. raise SignatureVerificationError, "Invalid Digest value. Computed SHA-256 digest: #{body_digest}; given: #{sha256[1]}"
  138. end
  139. def verify_signature(actor, signature, compare_signed_string)
  140. if actor.keypair.public_key.verify(OpenSSL::Digest.new('SHA256'), signature, compare_signed_string)
  141. @signed_request_actor = actor
  142. @signed_request_actor
  143. end
  144. rescue OpenSSL::PKey::RSAError
  145. nil
  146. end
  147. def build_signed_string(include_query_string: true)
  148. signed_headers.map do |signed_header|
  149. case signed_header
  150. when Request::REQUEST_TARGET
  151. if include_query_string
  152. "#{Request::REQUEST_TARGET}: #{request.method.downcase} #{request.original_fullpath}"
  153. else
  154. # Current versions of Mastodon incorrectly omit the query string from the (request-target) pseudo-header.
  155. # Therefore, temporarily support such incorrect signatures for compatibility.
  156. # TODO: remove eventually some time after release of the fixed version
  157. "#{Request::REQUEST_TARGET}: #{request.method.downcase} #{request.path}"
  158. end
  159. when '(created)'
  160. raise SignatureVerificationError, 'Invalid pseudo-header (created) for rsa-sha256' unless signature_algorithm == 'hs2019'
  161. raise SignatureVerificationError, 'Pseudo-header (created) used but corresponding argument missing' if signature_params['created'].blank?
  162. "(created): #{signature_params['created']}"
  163. when '(expires)'
  164. raise SignatureVerificationError, 'Invalid pseudo-header (expires) for rsa-sha256' unless signature_algorithm == 'hs2019'
  165. raise SignatureVerificationError, 'Pseudo-header (expires) used but corresponding argument missing' if signature_params['expires'].blank?
  166. "(expires): #{signature_params['expires']}"
  167. else
  168. "#{signed_header}: #{request.headers[to_header_name(signed_header)]}"
  169. end
  170. end.join("\n")
  171. end
  172. def matches_time_window?
  173. created_time = nil
  174. expires_time = nil
  175. begin
  176. if signature_algorithm == 'hs2019' && signature_params['created'].present?
  177. created_time = Time.at(signature_params['created'].to_i).utc
  178. elsif request.headers['Date'].present?
  179. created_time = Time.httpdate(request.headers['Date']).utc
  180. end
  181. expires_time = Time.at(signature_params['expires'].to_i).utc if signature_params['expires'].present?
  182. rescue ArgumentError => e
  183. raise SignatureVerificationError, "Invalid Date header: #{e.message}"
  184. end
  185. expires_time ||= created_time + 5.minutes unless created_time.nil?
  186. expires_time = [expires_time, created_time + EXPIRATION_WINDOW_LIMIT].min unless created_time.nil?
  187. return false if created_time.present? && created_time > Time.now.utc + CLOCK_SKEW_MARGIN
  188. return false if expires_time.present? && Time.now.utc > expires_time + CLOCK_SKEW_MARGIN
  189. true
  190. end
  191. def body_digest
  192. @body_digest ||= Digest::SHA256.base64digest(request_body)
  193. end
  194. def to_header_name(name)
  195. name.split('-').map(&:capitalize).join('-')
  196. end
  197. def missing_required_signature_parameters?
  198. signature_params['keyId'].blank? || signature_params['signature'].blank?
  199. end
  200. def actor_from_key_id(key_id)
  201. domain = key_id.start_with?('acct:') ? key_id.split('@').last : key_id
  202. if domain_not_allowed?(domain)
  203. @signature_verification_failure_code = 403
  204. return
  205. end
  206. if key_id.start_with?('acct:')
  207. stoplight_wrap_request { ResolveAccountService.new.call(key_id.delete_prefix('acct:'), suppress_errors: false) }
  208. elsif !ActivityPub::TagManager.instance.local_uri?(key_id)
  209. account = ActivityPub::TagManager.instance.uri_to_actor(key_id)
  210. account ||= stoplight_wrap_request { ActivityPub::FetchRemoteKeyService.new.call(key_id, id: false, suppress_errors: false) }
  211. account
  212. end
  213. rescue Mastodon::PrivateNetworkAddressError => e
  214. raise SignatureVerificationError, "Requests to private network addresses are disallowed (tried to query #{e.host})"
  215. rescue Mastodon::HostValidationError, ActivityPub::FetchRemoteActorService::Error, ActivityPub::FetchRemoteKeyService::Error, Webfinger::Error => e
  216. raise SignatureVerificationError, e.message
  217. end
  218. def stoplight_wrap_request(&block)
  219. Stoplight("source:#{request.remote_ip}", &block)
  220. .with_threshold(1)
  221. .with_cool_off_time(5.minutes.seconds)
  222. .with_error_handler { |error, handle| error.is_a?(HTTP::Error) || error.is_a?(OpenSSL::SSL::SSLError) ? handle.call(error) : raise(error) }
  223. .run
  224. end
  225. def actor_refresh_key!(actor)
  226. return if actor.local? || !actor.activitypub?
  227. return actor.refresh! if actor.respond_to?(:refresh!) && actor.possibly_stale?
  228. ActivityPub::FetchRemoteActorService.new.call(actor.uri, only_key: true, suppress_errors: false)
  229. rescue Mastodon::PrivateNetworkAddressError => e
  230. raise SignatureVerificationError, "Requests to private network addresses are disallowed (tried to query #{e.host})"
  231. rescue Mastodon::HostValidationError, ActivityPub::FetchRemoteActorService::Error, Webfinger::Error => e
  232. raise SignatureVerificationError, e.message
  233. end
  234. end