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