]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Merge pull request #6209 from MrPetovan/task/move-config-to-php-array
[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\Model\User;
41
42 class ExAuth
43 {
44         private $bDebug;
45         private $host;
46
47         /**
48          * @brief Create the class
49          *
50          * @param boolean $bDebug Debug mode
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          */
67         public function readStdin()
68         {
69                 while (!feof(STDIN)) {
70                         // Quit if the database connection went down
71                         if (!DBA::connected()) {
72                                 $this->writeLog(LOG_ERR, 'the database connection went down');
73                                 return;
74                         }
75
76                         $iHeader = fgets(STDIN, 3);
77                         $aLength = unpack('n', $iHeader);
78                         $iLength = $aLength['1'];
79
80                         // No data? Then quit
81                         if ($iLength == 0) {
82                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');
83                                 return;
84                         }
85
86                         // Fetching the data
87                         $sData = fgets(STDIN, $iLength + 1);
88                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
89                         $aCommand = explode(':', $sData);
90                         if (is_array($aCommand)) {
91                                 switch ($aCommand[0]) {
92                                         case 'isuser':
93                                                 // Check the existance of a given username
94                                                 $this->isUser($aCommand);
95                                                 break;
96                                         case 'auth':
97                                                 // Check if the givven password is correct
98                                                 $this->auth($aCommand);
99                                                 break;
100                                         case 'setpass':
101                                                 // We don't accept the setting of passwords here
102                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
103                                                 fwrite(STDOUT, pack('nn', 2, 0));
104                                                 break;
105                                         default:
106                                                 // We don't know the given command
107                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
108                                                 fwrite(STDOUT, pack('nn', 2, 0));
109                                                 break;
110                                 }
111                         } else {
112                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
113                                 fwrite(STDOUT, pack('nn', 2, 0));
114                         }
115                 }
116         }
117
118         /**
119          * @brief Check if the given username exists
120          *
121          * @param array $aCommand The command array
122          */
123         private function isUser(array $aCommand)
124         {
125                 $a = get_app();
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 ($a->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          */
174         private function checkUser($host, $user, $ssl)
175         {
176                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
177
178                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
179
180                 $curlResult = Network::curl($url);
181
182                 if (!$curlResult->isSuccess()) {
183                         return false;
184                 }
185
186                 if ($curlResult->getReturnCode() != 200) {
187                         return false;
188                 }
189
190                 $json = @json_decode($curlResult->getBody());
191                 if (!is_object($json)) {
192                         return false;
193                 }
194
195                 return $json->nick == $user;
196         }
197
198         /**
199          * @brief Authenticate the given user and password
200          *
201          * @param array $aCommand The command array
202          */
203         private function auth(array $aCommand)
204         {
205                 $a = get_app();
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 ($a->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]);
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          */
298         private function setHost($host)
299         {
300                 if (!empty($this->host)) {
301                         return;
302                 }
303
304                 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
305
306                 $this->host = $host;
307
308                 $lockpath = Config::get('jabber', 'lockpath');
309                 if (is_null($lockpath)) {
310                         $this->writeLog(LOG_INFO, 'No lockpath defined.');
311                         return;
312                 }
313
314                 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
315                 if (PidFile::isRunningProcess($file)) {
316                         if (PidFile::killProcess($file)) {
317                                 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
318                         } else {
319                                 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
320                                 die();
321                         }
322                 }
323
324                 // Now it is safe to create the pid file
325                 PidFile::create($file);
326                 if (!file_exists($file)) {
327                         $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
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 }