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