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