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