Issue 8714: Make redirects more secure
[friendica.git/.git] / mod / redir.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Core\Logger;
24 use Friendica\Core\Session;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Profile;
30 use Friendica\Util\Network;
31 use Friendica\Util\Strings;
32
33 function redir_init(App $a) {
34         if (!Session::isAuthenticated()) {
35                 throw new \Friendica\Network\HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
36         }
37
38         $url = $_GET['url'] ?? '';
39         $quiet = !empty($_GET['quiet']) ? '&quiet=1' : '';
40
41         if ($a->argc > 1 && intval($a->argv[1])) {
42                 $cid = intval($a->argv[1]);
43         } else {
44                 $cid = 0;
45         }
46
47         // Try magic auth before the legacy stuff
48         redir_magic($a, $cid, $url);
49
50         if (empty($cid)) {
51                 throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Contact not found.'));
52         }
53
54         $fields = ['id', 'uid', 'nurl', 'url', 'addr', 'name', 'network', 'poll', 'issued-id', 'dfrn-id', 'duplex', 'pending'];
55         $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => [0, local_user()]]);
56         if (!DBA::isResult($contact)) {
57                 throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Contact not found.'));
58         }
59
60         $contact_url = $contact['url'];
61
62         if (!empty($a->contact['id']) && $a->contact['id'] == $cid) {
63                 // Local user is already authenticated.
64                 redir_check_url($contact_url, $url);
65                 $a->redirect($url ?: $contact_url);
66         }
67
68         if ($contact['uid'] == 0 && local_user()) {
69                 // Let's have a look if there is an established connection
70                 // between the public contact we have found and the local user.
71                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => $contact['nurl'], 'uid' => local_user()]);
72
73                 if (DBA::isResult($contact)) {
74                         $cid = $contact['id'];
75                 }
76
77                 if (!empty($a->contact['id']) && $a->contact['id'] == $cid) {
78                         // Local user is already authenticated.
79                         redir_check_url($contact_url, $url);
80                         $target_url = $url ?: $contact_url;
81                         Logger::log($contact['name'] . " is already authenticated. Redirecting to " . $target_url, Logger::DEBUG);
82                         $a->redirect($target_url);
83                 }
84         }
85
86         if (remote_user()) {
87                 $host = substr(DI::baseUrl()->getUrlPath() . (DI::baseUrl()->getUrlPath() ? '/' . DI::baseUrl()->getUrlPath() : ''), strpos(DI::baseUrl()->getUrlPath(), '://') + 3);
88                 $remotehost = substr($contact['addr'], strpos($contact['addr'], '@') + 1);
89
90                 // On a local instance we have to check if the local user has already authenticated
91                 // with the local contact. Otherwise the local user would ask the local contact
92                 // for authentification everytime he/she is visiting a profile page of the local
93                 // contact.
94                 if (($host == $remotehost) && (Session::getRemoteContactID(Session::get('visitor_visiting')) == Session::get('visitor_id'))) {
95                         // Remote user is already authenticated.
96                         redir_check_url($contact_url, $url);
97                         $target_url = $url ?: $contact_url;
98                         Logger::log($contact['name'] . " is already authenticated. Redirecting to " . $target_url, Logger::DEBUG);
99                         $a->redirect($target_url);
100                 }
101         }
102
103         // Doing remote auth with dfrn.
104         if (local_user() && (!empty($contact['dfrn-id']) || !empty($contact['issued-id'])) && empty($contact['pending'])) {
105                 $dfrn_id = $orig_id = (($contact['issued-id']) ? $contact['issued-id'] : $contact['dfrn-id']);
106
107                 if ($contact['duplex'] && $contact['issued-id']) {
108                         $orig_id = $contact['issued-id'];
109                         $dfrn_id = '1:' . $orig_id;
110                 }
111                 if ($contact['duplex'] && $contact['dfrn-id']) {
112                         $orig_id = $contact['dfrn-id'];
113                         $dfrn_id = '0:' . $orig_id;
114                 }
115
116                 $sec = Strings::getRandomHex();
117
118                 $fields = ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
119                         'sec' => $sec, 'expire' => time() + 45];
120                 DBA::insert('profile_check', $fields);
121
122                 Logger::log('mod_redir: ' . $contact['name'] . ' ' . $sec, Logger::DEBUG);
123
124                 $dest = (!empty($url) ? '&destination_url=' . $url : '');
125
126                 System::externalRedirect($contact['poll'] . '?dfrn_id=' . $dfrn_id
127                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest . $quiet);
128
129                 redir_check_url($contact_url, $url);
130                 $url = $url ?: $contact_url;
131         }
132
133         if (empty($url)) {
134                 throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Contact not found.'));
135         }
136
137         // If we don't have a connected contact, redirect with
138         // the 'zrl' parameter.
139         $my_profile = Profile::getMyURL();
140
141         if (!empty($my_profile) && !Strings::compareLink($my_profile, $url)) {
142                 $separator = strpos($url, '?') ? '&' : '?';
143
144                 $url .= $separator . 'zrl=' . urlencode($my_profile);
145         }
146
147         Logger::log('redirecting to ' . $url, Logger::DEBUG);
148         $a->redirect($url);
149 }
150
151 function redir_magic($a, $cid, $url)
152 {
153         $visitor = Profile::getMyURL();
154         if (!empty($visitor)) {
155                 Logger::info('Got my url', ['visitor' => $visitor]);
156         }
157
158         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid]);
159         if (!DBA::isResult($contact)) {
160                 Logger::info('Contact not found', ['id' => $cid]);
161                 throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Contact not found.'));
162         } else {
163                 $contact_url = $contact['url'];
164                 redir_check_url($contact_url, $url);
165                 $target_url = $url ?: $contact_url;
166         }
167
168         $basepath = Contact::getBasepath($contact_url);
169
170         // We don't use magic auth when there is no visitor, we are on the same system or we visit our own stuff
171         if (empty($visitor) || Strings::compareLink($basepath, DI::baseUrl()) || Strings::compareLink($contact_url, $visitor)) {
172                 Logger::info('Redirecting without magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
173                 DI::app()->redirect($target_url);
174         }
175
176         // Test for magic auth on the target system
177         $serverret = Network::curl($basepath . '/magic');
178         if ($serverret->isSuccess()) {
179                 $separator = strpos($target_url, '?') ? '&' : '?';
180                 $target_url .= $separator . 'zrl=' . urlencode($visitor) . '&addr=' . urlencode($contact_url);
181
182                 Logger::info('Redirecting with magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
183                 System::externalRedirect($target_url);
184         } else {
185                 Logger::info('No magic for contact', ['contact' => $contact_url]);
186         }
187 }
188
189 function redir_check_url(string $contact_url, string $url)
190 {
191         if (empty($contact_url) || empty($url)) {
192                 return;
193         }
194
195         $url_host = parse_url($url, PHP_URL_HOST);
196         $contact_url_host = parse_url($contact_url, PHP_URL_HOST);
197
198         if ($url_host == $contact_url_host) {
199                 return;
200         }
201
202         Logger::error('URL check host mismatch', ['contact' => $contact_url, 'url' => $url]);
203         throw new \Friendica\Network\HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
204 }