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