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