]> git.mxchange.org Git - friendica.git/blob - src/Security/ExAuth.php
Merge remote-tracking branch 'upstream/2021.12-rc' into lemmy
[friendica.git] / src / Security / ExAuth.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
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  * ejabberd extauth script for the integration with friendica
21  *
22  * Originally written for joomla by Dalibor Karlovic <dado@krizevci.info>
23  * modified for Friendica by Michael Vogel <icarus@dabo.de>
24  * published under GPL
25  *
26  * Latest version of the original script for joomla is available at:
27  * http://87.230.15.86/~dado/ejabberd/joomla-login
28  *
29  * Installation:
30  *
31  *      - Change it's owner to whichever user is running the server, ie. ejabberd
32  *        $ chown ejabberd:ejabberd /path/to/friendica/bin/auth_ejabberd.php
33  *
34  *      - Change the access mode so it is readable only to the user ejabberd and has exec
35  *        $ chmod 700 /path/to/friendica/bin/auth_ejabberd.php
36  *
37  *      - Edit your ejabberd.cfg file, comment out your auth_method and add:
38  *        {auth_method, external}.
39  *        {extauth_program, "/path/to/friendica/bin/auth_ejabberd.php"}.
40  *
41  *      - Restart your ejabberd service, you should be able to login with your friendica auth info
42  *
43  * Other hints:
44  *      - if your users have a space or a @ in their nickname, they'll run into trouble
45  *        registering with any client so they should be instructed to replace these chars
46  *        " " (space) is replaced with "%20"
47  *        "@" is replaced with "(a)"
48  *
49  */
50
51 namespace Friendica\Security;
52
53 use Exception;
54 use Friendica\App;
55 use Friendica\Core\Config\Capability\IManageConfigValues;
56 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
57 use Friendica\Database\Database;
58 use Friendica\DI;
59 use Friendica\Model\User;
60 use Friendica\Network\HTTPException;
61 use Friendica\Util\PidFile;
62
63 class ExAuth
64 {
65         private $bDebug;
66         private $host;
67
68         /**
69          * @var App\Mode
70          */
71         private $appMode;
72         /**
73          * @var IManageConfigValues
74          */
75         private $config;
76         /**
77          * @var IManagePersonalConfigValues
78          */
79         private $pConfig;
80         /**
81          * @var Database
82          */
83         private $dba;
84         /**
85          * @var App\BaseURL
86          */
87         private $baseURL;
88
89         /**
90          * @param App\Mode                    $appMode
91          * @param IManageConfigValues         $config
92          * @param IManagePersonalConfigValues $pConfig
93          * @param Database                    $dba
94          * @param App\BaseURL                 $baseURL
95          *
96          * @throws Exception
97          */
98         public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
99         {
100                 $this->appMode = $appMode;
101                 $this->config  = $config;
102                 $this->pConfig = $pConfig;
103                 $this->dba     = $dba;
104                 $this->baseURL = $baseURL;
105
106                 $this->bDebug = (int)$config->get('jabber', 'debug');
107
108                 openlog('auth_ejabberd', LOG_PID, LOG_USER);
109
110                 $this->writeLog(LOG_NOTICE, 'start');
111         }
112
113         /**
114          * Standard input reading function, executes the auth with the provided
115          * parameters
116          *
117          * @throws HTTPException\InternalServerErrorException
118          */
119         public function readStdin()
120         {
121                 if (!$this->appMode->isNormal()) {
122                         $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
123                         return;
124                 }
125
126                 while (!feof(STDIN)) {
127                         // Quit if the database connection went down
128                         if (!$this->dba->isConnected()) {
129                                 $this->writeLog(LOG_ERR, 'the database connection went down');
130                                 return;
131                         }
132
133                         $iHeader = fgets(STDIN, 3);
134                         if (empty($iHeader)) {
135                                 $this->writeLog(LOG_ERR, 'empty stdin');
136                                 return;
137                         }
138
139                         $aLength = unpack('n', $iHeader);
140                         $iLength = $aLength['1'];
141
142                         // No data? Then quit
143                         if ($iLength == 0) {
144                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');
145                                 return;
146                         }
147
148                         // Fetching the data
149                         $sData = fgets(STDIN, $iLength + 1);
150                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
151                         $aCommand = explode(':', $sData);
152                         if (is_array($aCommand)) {
153                                 switch ($aCommand[0]) {
154                                         case 'isuser':
155                                                 // Check the existance of a given username
156                                                 $this->isUser($aCommand);
157                                                 break;
158                                         case 'auth':
159                                                 // Check if the givven password is correct
160                                                 $this->auth($aCommand);
161                                                 break;
162                                         case 'setpass':
163                                                 // We don't accept the setting of passwords here
164                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
165                                                 fwrite(STDOUT, pack('nn', 2, 0));
166                                                 break;
167                                         default:
168                                                 // We don't know the given command
169                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
170                                                 fwrite(STDOUT, pack('nn', 2, 0));
171                                                 break;
172                                 }
173                         } else {
174                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
175                                 fwrite(STDOUT, pack('nn', 2, 0));
176                         }
177                 }
178         }
179
180         /**
181          * Check if the given username exists
182          *
183          * @param array $aCommand The command array
184          * @throws HTTPException\InternalServerErrorException
185          */
186         private function isUser(array $aCommand)
187         {
188                 // Check if there is a username
189                 if (!isset($aCommand[1])) {
190                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
191                         fwrite(STDOUT, pack('nn', 2, 0));
192                         return;
193                 }
194
195                 // We only allow one process per hostname. So we set a lock file
196                 // Problem: We get the firstname after the first auth - not before
197                 $this->setHost($aCommand[2]);
198
199                 // Now we check if the given user is valid
200                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
201
202                 // Does the hostname match? So we try directly
203                 if ($this->baseURL->getHostname() == $aCommand[2]) {
204                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
205                         $found = $this->dba->exists('user', ['nickname' => $sUser]);
206                 } else {
207                         $found = false;
208                 }
209
210                 // If the hostnames doesn't match or there is some failure, we try to check remotely
211                 if (!$found) {
212                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);
213                 }
214
215                 if ($found) {
216                         // The user is okay
217                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
218                         fwrite(STDOUT, pack('nn', 2, 1));
219                 } else {
220                         // The user isn't okay
221                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
222                         fwrite(STDOUT, pack('nn', 2, 0));
223                 }
224         }
225
226         /**
227          * Check remote user existance via HTTP(S)
228          *
229          * @param string  $host The hostname
230          * @param string  $user Username
231          * @param boolean $ssl  Should the check be done via SSL?
232          *
233          * @return boolean Was the user found?
234          * @throws HTTPException\InternalServerErrorException
235          */
236         private function checkUser($host, $user, $ssl)
237         {
238                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
239
240                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
241
242                 $curlResult = DI::httpClient()->get($url);
243
244                 if (!$curlResult->isSuccess()) {
245                         return false;
246                 }
247
248                 if ($curlResult->getReturnCode() != 200) {
249                         return false;
250                 }
251
252                 $json = @json_decode($curlResult->getBody());
253                 if (!is_object($json)) {
254                         return false;
255                 }
256
257                 return $json->nick == $user;
258         }
259
260         /**
261          * Authenticate the given user and password
262          *
263          * @param array $aCommand The command array
264          * @throws Exception
265          */
266         private function auth(array $aCommand)
267         {
268                 // check user authentication
269                 if (sizeof($aCommand) != 4) {
270                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
271                         fwrite(STDOUT, pack('nn', 2, 0));
272                         return;
273                 }
274
275                 // We only allow one process per hostname. So we set a lock file
276                 // Problem: We get the firstname after the first auth - not before
277                 $this->setHost($aCommand[2]);
278
279                 // We now check if the password match
280                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
281
282                 $Error = false;
283                 // Does the hostname match? So we try directly
284                 if ($this->baseURL->getHostname() == $aCommand[2]) {
285                         try {
286                                 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
287                                 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
288                         } catch (HTTPException\ForbiddenException $ex) {
289                                 // User exists, authentication failed
290                                 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
291                                 $aUser = User::getByNickname($sUser, ['uid']);
292                                 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
293                                 $Error = ($aCommand[3] != $sPassword);
294                         } catch (\Throwable $ex) {
295                                 // User doesn't exist and any other failure case
296                                 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
297                                 $Error = true;
298                         }
299                 } else {
300                         $Error = true;
301                 }
302
303                 // If the hostnames doesn't match or there is some failure, we try to check remotely
304                 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
305                         $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
306                         fwrite(STDOUT, pack('nn', 2, 0));
307                 } else {
308                         $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
309                         fwrite(STDOUT, pack('nn', 2, 1));
310                 }
311         }
312
313         /**
314          * Check remote credentials via HTTP(S)
315          *
316          * @param string $host The hostname
317          * @param string $user Username
318          * @param string $password Password
319          * @param boolean $ssl Should the check be done via SSL?
320          *
321          * @return boolean Are the credentials okay?
322          */
323         private function checkCredentials($host, $user, $password, $ssl)
324         {
325                 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
326
327                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
328
329                 $ch = curl_init();
330                 curl_setopt($ch, CURLOPT_URL, $url);
331                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
332                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
333                 curl_setopt($ch, CURLOPT_HEADER, true);
334                 curl_setopt($ch, CURLOPT_NOBODY, true);
335                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
336                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
337
338                 curl_exec($ch);
339                 $curl_info = @curl_getinfo($ch);
340                 $http_code = $curl_info['http_code'];
341                 curl_close($ch);
342
343                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
344
345                 return $http_code == 200;
346         }
347
348         /**
349          * Set the hostname for this process
350          *
351          * @param string $host The hostname
352          */
353         private function setHost($host)
354         {
355                 if (!empty($this->host)) {
356                         return;
357                 }
358
359                 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
360
361                 $this->host = $host;
362
363                 $lockpath = $this->config->get('jabber', 'lockpath');
364                 if (is_null($lockpath)) {
365                         $this->writeLog(LOG_INFO, 'No lockpath defined.');
366                         return;
367                 }
368
369                 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
370                 if (PidFile::isRunningProcess($file)) {
371                         if (PidFile::killProcess($file)) {
372                                 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
373                         } else {
374                                 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
375                                 die();
376                         }
377                 }
378
379                 // Now it is safe to create the pid file
380                 PidFile::create($file);
381                 if (!file_exists($file)) {
382                         $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
383                 }
384         }
385
386         /**
387          * write data to the syslog
388          *
389          * @param integer $loglevel The syslog loglevel
390          * @param string $sMessage The syslog message
391          */
392         private function writeLog($loglevel, $sMessage)
393         {
394                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
395                         return;
396                 }
397                 syslog($loglevel, $sMessage);
398         }
399
400         /**
401          * destroy the class, close the syslog connection.
402          */
403         public function __destruct()
404         {
405                 $this->writeLog(LOG_NOTICE, 'stop');
406                 closelog();
407         }
408 }