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