InboxValidator.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Jobs\InboxPipeline;
  3. use Cache;
  4. use App\Profile;
  5. use App\Util\ActivityPub\{
  6. Helpers,
  7. HttpSignature,
  8. Inbox
  9. };
  10. use Illuminate\Bus\Queueable;
  11. use Illuminate\Contracts\Queue\ShouldQueue;
  12. use Illuminate\Foundation\Bus\Dispatchable;
  13. use Illuminate\Queue\InteractsWithQueue;
  14. use Illuminate\Queue\SerializesModels;
  15. use Zttp\Zttp;
  16. use App\Jobs\DeletePipeline\DeleteRemoteProfilePipeline;
  17. class InboxValidator implements ShouldQueue
  18. {
  19. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  20. protected $username;
  21. protected $headers;
  22. protected $payload;
  23. public $timeout = 60;
  24. public $tries = 1;
  25. /**
  26. * Create a new job instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct($username, $headers, $payload)
  31. {
  32. $this->username = $username;
  33. $this->headers = $headers;
  34. $this->payload = $payload;
  35. }
  36. /**
  37. * Execute the job.
  38. *
  39. * @return void
  40. */
  41. public function handle()
  42. {
  43. $username = $this->username;
  44. $headers = $this->headers;
  45. $payload = json_decode($this->payload, true, 8);
  46. $profile = Profile::whereNull('domain')->whereUsername($username)->first();
  47. if(isset($payload['id'])) {
  48. $lockKey = hash('sha256', $payload['id']);
  49. if(Cache::get($lockKey) !== null) {
  50. // Job processed already
  51. return 1;
  52. }
  53. Cache::put($lockKey, 1, 3600);
  54. }
  55. if(!isset($headers['signature']) || !isset($headers['date'])) {
  56. return;
  57. }
  58. if(empty($profile) || empty($headers) || empty($payload)) {
  59. return;
  60. }
  61. if( $payload['type'] === 'Delete' &&
  62. ( ( is_string($payload['object']) &&
  63. $payload['object'] === $payload['actor'] ) ||
  64. ( is_array($payload['object']) &&
  65. isset($payload['object']['id'], $payload['object']['type']) &&
  66. $payload['object']['type'] === 'Person' &&
  67. $payload['actor'] === $payload['object']['id']
  68. ))
  69. ) {
  70. $actor = $payload['actor'];
  71. $hash = strlen($actor) <= 48 ?
  72. 'b:' . base64_encode($actor) :
  73. 'h:' . hash('sha256', $actor);
  74. $lockKey = 'ap:inbox:actor-delete-exists:lock:' . $hash;
  75. Cache::lock($lockKey, 10)->block(5, function () use(
  76. $headers,
  77. $payload,
  78. $actor,
  79. $hash,
  80. $profile
  81. ) {
  82. $key = 'ap:inbox:actor-delete-exists:' . $hash;
  83. $actorDelete = Cache::remember($key, now()->addMinutes(15), function() use($actor) {
  84. return Profile::whereRemoteUrl($actor)
  85. ->whereNotNull('domain')
  86. ->exists();
  87. });
  88. if($actorDelete) {
  89. if($this->verifySignature($headers, $profile, $payload) == true) {
  90. Cache::set($key, false);
  91. $profile = Profile::whereNotNull('domain')
  92. ->whereNull('status')
  93. ->whereRemoteUrl($actor)
  94. ->first();
  95. if($profile) {
  96. DeleteRemoteProfilePipeline::dispatchNow($profile);
  97. }
  98. return;
  99. } else {
  100. // Signature verification failed, exit.
  101. return;
  102. }
  103. } else {
  104. // Remote user doesn't exist, exit early.
  105. return;
  106. }
  107. });
  108. return;
  109. }
  110. if($profile->status != null) {
  111. return;
  112. }
  113. if($this->verifySignature($headers, $profile, $payload) == true) {
  114. (new Inbox($headers, $profile, $payload))->handle();
  115. return;
  116. } else if($this->blindKeyRotation($headers, $profile, $payload) == true) {
  117. (new Inbox($headers, $profile, $payload))->handle();
  118. return;
  119. } else {
  120. return;
  121. }
  122. }
  123. protected function verifySignature($headers, $profile, $payload)
  124. {
  125. $body = $this->payload;
  126. $bodyDecoded = $payload;
  127. $signature = is_array($headers['signature']) ? $headers['signature'][0] : $headers['signature'];
  128. $date = is_array($headers['date']) ? $headers['date'][0] : $headers['date'];
  129. if(!$signature) {
  130. return;
  131. }
  132. if(!$date) {
  133. return;
  134. }
  135. if(!now()->parse($date)->gt(now()->subDays(1)) ||
  136. !now()->parse($date)->lt(now()->addDays(1))
  137. ) {
  138. return;
  139. }
  140. if(!isset($bodyDecoded['id'])) {
  141. return;
  142. }
  143. $signatureData = HttpSignature::parseSignatureHeader($signature);
  144. $keyId = Helpers::validateUrl($signatureData['keyId']);
  145. $id = Helpers::validateUrl($bodyDecoded['id']);
  146. $keyDomain = parse_url($keyId, PHP_URL_HOST);
  147. $idDomain = parse_url($id, PHP_URL_HOST);
  148. if(isset($bodyDecoded['object'])
  149. && is_array($bodyDecoded['object'])
  150. && isset($bodyDecoded['object']['attributedTo'])
  151. ) {
  152. if(parse_url($bodyDecoded['object']['attributedTo'], PHP_URL_HOST) !== $keyDomain) {
  153. return;
  154. abort(400, 'Invalid request');
  155. }
  156. }
  157. if(!$keyDomain || !$idDomain || $keyDomain !== $idDomain) {
  158. return;
  159. abort(400, 'Invalid request');
  160. }
  161. $actor = Profile::whereKeyId($keyId)->first();
  162. if(!$actor) {
  163. $actorUrl = is_array($bodyDecoded['actor']) ? $bodyDecoded['actor'][0] : $bodyDecoded['actor'];
  164. $actor = Helpers::profileFirstOrNew($actorUrl);
  165. }
  166. if(!$actor) {
  167. return;
  168. }
  169. $pkey = openssl_pkey_get_public($actor->public_key);
  170. if(!$pkey) {
  171. return 0;
  172. }
  173. $inboxPath = "/users/{$profile->username}/inbox";
  174. list($verified, $headers) = HttpSignature::verify($pkey, $signatureData, $headers, $inboxPath, $body);
  175. if($verified == 1) {
  176. return true;
  177. } else {
  178. return false;
  179. }
  180. }
  181. protected function blindKeyRotation($headers, $profile, $payload)
  182. {
  183. $signature = is_array($headers['signature']) ? $headers['signature'][0] : $headers['signature'];
  184. $date = is_array($headers['date']) ? $headers['date'][0] : $headers['date'];
  185. if(!$signature) {
  186. return;
  187. }
  188. if(!$date) {
  189. return;
  190. }
  191. if(!now()->parse($date)->gt(now()->subDays(1)) ||
  192. !now()->parse($date)->lt(now()->addDays(1))
  193. ) {
  194. return;
  195. }
  196. $signatureData = HttpSignature::parseSignatureHeader($signature);
  197. $keyId = Helpers::validateUrl($signatureData['keyId']);
  198. $actor = Profile::whereKeyId($keyId)->whereNotNull('remote_url')->first();
  199. if(!$actor) {
  200. return;
  201. }
  202. if(Helpers::validateUrl($actor->remote_url) == false) {
  203. return;
  204. }
  205. $res = Zttp::timeout(5)->withHeaders([
  206. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  207. 'User-Agent' => 'PixelfedBot v0.1 - https://pixelfed.org',
  208. ])->get($actor->remote_url);
  209. $res = json_decode($res->body(), true, 8);
  210. if(!$res || empty($res) || !isset($res['publicKey']) || !isset($res['publicKey']['id'])) {
  211. return;
  212. }
  213. if($res['publicKey']['id'] !== $actor->key_id) {
  214. return;
  215. }
  216. $actor->public_key = $res['publicKey']['publicKeyPem'];
  217. $actor->save();
  218. return $this->verifySignature($headers, $profile, $payload);
  219. }
  220. }