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