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\Model\Contact;
11 use Friendica\Model\OpenWebAuthToken;
12 use Friendica\Util\HTTPSignature;
15 * @brief OpenWebAuth verifier and token generator
17 * See https://macgirvin.com/wiki/mike/OpenWebAuth/Home
18 * Requests to this endpoint should be signed using HTTP Signatures
19 * using the 'Authorization: Signature' authentication method
20 * If the signature verifies a token is returned.
22 * This token may be exchanged for an authenticated cookie.
24 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Owa.php
26 class Owa extends BaseModule
28 public static function init()
31 $ret = [ 'success' => false ];
33 foreach (['REDIRECT_REMOTE_USER', 'HTTP_AUTHORIZATION'] as $head) {
34 if (array_key_exists($head, $_SERVER) && substr(trim($_SERVER[$head]), 0, 9) === 'Signature') {
35 if ($head !== 'HTTP_AUTHORIZATION') {
36 $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER[$head];
40 $sigblock = HTTPSignature::parseSigheader($_SERVER[$head]);
42 $keyId = $sigblock['keyId'];
45 // Try to find the public contact entry of the handle.
46 $handle = str_replace('acct:', '', $keyId);
48 $cid = Contact::getIdForURL($handle);
49 $fields = ['id', 'url', 'addr', 'pubkey'];
50 $condition = ['id' => $cid];
52 $contact = DBA::selectFirst('contact', $fields, $condition);
54 if (DBA::isResult($contact)) {
55 // Try to verify the signed header with the public key of the contact record
57 $verified = HTTPSignature:verifyMagic($contact['pubkey']);
59 if ($verified && $verified['header_signed'] && $verified['header_valid']) {
60 logger('OWA header: ' . print_r($verified, true), LOGGER_DATA);
61 logger('OWA success: ' . $contact['addr'], LOGGER_DATA);
63 $ret['success'] = true;
64 $token = random_string(32);
66 // Store the generated token in the databe.
67 OpenWebAuthToken::create('owt', 0, $token, $contact['addr']);
71 // Encrypt the token with the public contacts publik key.
72 // Only the specific public contact will be able to encrypt it.
73 // At a later time, we will compare weather the token we're getting
74 // is really the same token we have stored in the database.
75 openssl_public_encrypt($token, $result, $contact['pubkey']);
76 $ret['encrypted_token'] = base64url_encode($result);
78 logger('OWA fail: ' . $contact['id'] . ' ' . $contact['addr'] . ' ' . $contact['url'], LOGGER_DEBUG);
81 logger('Contact not found: ' . $handle, LOGGER_DEBUG);
87 System::jsonExit($ret, 'application/x-dfrn+json');