3 * @file src/Module/Owa.php
5 namespace Friendica\Module;
7 use Friendica\BaseModule;
8 use Friendica\Core\Logger;
9 use Friendica\Core\System;
10 use Friendica\Database\DBA;
11 use Friendica\Model\Contact;
12 use Friendica\Model\OpenWebAuthToken;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Util\Strings;
17 * OpenWebAuth verifier and token generator
19 * See https://macgirvin.com/wiki/mike/OpenWebAuth/Home
20 * Requests to this endpoint should be signed using HTTP Signatures
21 * using the 'Authorization: Signature' authentication method
22 * If the signature verifies a token is returned.
24 * This token may be exchanged for an authenticated cookie.
26 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Owa.php
28 class Owa extends BaseModule
30 public static function init(array $parameters = [])
33 $ret = [ 'success' => false ];
35 foreach (['REDIRECT_REMOTE_USER', 'HTTP_AUTHORIZATION'] as $head) {
36 if (array_key_exists($head, $_SERVER) && substr(trim($_SERVER[$head]), 0, 9) === 'Signature') {
37 if ($head !== 'HTTP_AUTHORIZATION') {
38 $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER[$head];
42 $sigblock = HTTPSignature::parseSigheader($_SERVER[$head]);
44 $keyId = $sigblock['keyId'];
47 // Try to find the public contact entry of the handle.
48 $handle = str_replace('acct:', '', $keyId);
50 $cid = Contact::getIdForURL($handle);
51 $fields = ['id', 'url', 'addr', 'pubkey'];
52 $condition = ['id' => $cid];
54 $contact = DBA::selectFirst('contact', $fields, $condition);
56 if (DBA::isResult($contact)) {
57 // Try to verify the signed header with the public key of the contact record
59 $verified = HTTPSignature::verifyMagic($contact['pubkey']);
61 if ($verified && $verified['header_signed'] && $verified['header_valid']) {
62 Logger::log('OWA header: ' . print_r($verified, true), Logger::DATA);
63 Logger::log('OWA success: ' . $contact['addr'], Logger::DATA);
65 $ret['success'] = true;
66 $token = Strings::getRandomHex(32);
68 // Store the generated token in the databe.
69 OpenWebAuthToken::create('owt', 0, $token, $contact['addr']);
73 // Encrypt the token with the public contacts publik key.
74 // Only the specific public contact will be able to encrypt it.
75 // At a later time, we will compare weather the token we're getting
76 // is really the same token we have stored in the database.
77 openssl_public_encrypt($token, $result, $contact['pubkey']);
78 $ret['encrypted_token'] = Strings::base64UrlEncode($result);
80 Logger::log('OWA fail: ' . $contact['id'] . ' ' . $contact['addr'] . ' ' . $contact['url'], Logger::DEBUG);
83 Logger::log('Contact not found: ' . $handle, Logger::DEBUG);
89 System::jsonExit($ret, 'application/x-zot+json');