3 * @file src/Module/Owa.php
5 namespace Friendica\Module;
7 use Friendica\BaseModule;
8 use Friendica\Core\System;
9 use Friendica\Database\DBA;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\OpenWebAuthToken;
13 use Friendica\Util\HTTPSignature;
16 * @brief OpenWebAuth verifier and token generator
18 * See https://macgirvin.com/wiki/mike/OpenWebAuth/Home
19 * Requests to this endpoint should be signed using HTTP Signatures
20 * using the 'Authorization: Signature' authentication method
21 * If the signature verifies a token is returned.
23 * This token may be exchanged for an authenticated cookie.
25 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Owa.php
27 class Owa extends BaseModule
29 public static function init()
32 $ret = [ 'success' => false ];
34 foreach (['REDIRECT_REMOTE_USER', 'HTTP_AUTHORIZATION'] as $head) {
35 if (array_key_exists($head, $_SERVER) && substr(trim($_SERVER[$head]), 0, 9) === 'Signature') {
36 if ($head !== 'HTTP_AUTHORIZATION') {
37 $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER[$head];
41 $sigblock = HTTPSignature::parseSigheader($_SERVER[$head]);
43 $keyId = $sigblock['keyId'];
46 // Try to find the public contact entry of the handle.
47 $handle = str_replace('acct:', '', $keyId);
49 $cid = Contact::getIdForURL($handle);
50 $fields = ['id', 'url', 'addr', 'pubkey'];
51 $condition = ['id' => $cid];
53 $contact = DBA::selectFirst('contact', $fields, $condition);
55 if (DBM::is_result($contact)) {
56 // Try to verify the signed header with the public key of the contact record
58 $verified = HTTPSignature::verify('', $contact['pubkey']);
60 if ($verified && $verified['header_signed'] && $verified['header_valid']) {
61 logger('OWA header: ' . print_r($verified, true), LOGGER_DATA);
62 logger('OWA success: ' . $contact['addr'], LOGGER_DATA);
64 $ret['success'] = true;
65 $token = random_string(32);
67 // Store the generated token in the databe.
68 OpenWebAuthToken::create('owt', 0, $token, $contact['addr']);
72 // Encrypt the token with the public contacts publik key.
73 // Only the specific public contact will be able to encrypt it.
74 // At a later time, we will compare weather the token we're getting
75 // is really the same token we have stored in the database.
76 openssl_public_encrypt($token, $result, $contact['pubkey']);
77 $ret['encrypted_token'] = base64url_encode($result);
79 logger('OWA fail: ' . $contact['id'] . ' ' . $contact['addr'] . ' ' . $contact['url'], LOGGER_DEBUG);
82 logger('Contact not found: ' . $handle, LOGGER_DEBUG);
88 System::jsonExit($ret, 'application/x-dfrn+json');