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