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