]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Fix PHPDoc comments project-wide
[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          */
51         public function __construct()
52         {
53                 $this->bDebug = (int) Config::get('jabber', 'debug');
54
55                 openlog('auth_ejabberd', LOG_PID, LOG_USER);
56
57                 $this->writeLog(LOG_NOTICE, 'start');
58         }
59
60         /**
61          * @brief Standard input reading function, executes the auth with the provided
62          * parameters
63          *
64          * @return null
65          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123          */
124         private function isUser(array $aCommand)
125         {
126                 $a = \get_app();
127
128                 // Check if there is a username
129                 if (!isset($aCommand[1])) {
130                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
131                         fwrite(STDOUT, pack('nn', 2, 0));
132                         return;
133                 }
134
135                 // We only allow one process per hostname. So we set a lock file
136                 // Problem: We get the firstname after the first auth - not before
137                 $this->setHost($aCommand[2]);
138
139                 // Now we check if the given user is valid
140                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
141
142                 // Does the hostname match? So we try directly
143                 if ($a->getHostName() == $aCommand[2]) {
144                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
145                         $found = DBA::exists('user', ['nickname' => $sUser]);
146                 } else {
147                         $found = false;
148                 }
149
150                 // If the hostnames doesn't match or there is some failure, we try to check remotely
151                 if (!$found) {
152                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);
153                 }
154
155                 if ($found) {
156                         // The user is okay
157                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
158                         fwrite(STDOUT, pack('nn', 2, 1));
159                 } else {
160                         // The user isn't okay
161                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
162                         fwrite(STDOUT, pack('nn', 2, 0));
163                 }
164         }
165
166         /**
167          * @brief Check remote user existance via HTTP(S)
168          *
169          * @param string  $host The hostname
170          * @param string  $user Username
171          * @param boolean $ssl  Should the check be done via SSL?
172          *
173          * @return boolean Was the user found?
174          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
175          */
176         private function checkUser($host, $user, $ssl)
177         {
178                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
179
180                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
181
182                 $curlResult = Network::curl($url);
183
184                 if (!$curlResult->isSuccess()) {
185                         return false;
186                 }
187
188                 if ($curlResult->getReturnCode() != 200) {
189                         return false;
190                 }
191
192                 $json = @json_decode($curlResult->getBody());
193                 if (!is_object($json)) {
194                         return false;
195                 }
196
197                 return $json->nick == $user;
198         }
199
200         /**
201          * @brief Authenticate the given user and password
202          *
203          * @param array $aCommand The command array
204          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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(['%20', '(a)'], [' ', '@'], $aCommand[1]);
223
224                 // Does the hostname match? So we try directly
225                 if ($a->getHostName() == $aCommand[2]) {
226                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
227
228                         $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
229                         if (DBA::isResult($aUser)) {
230                                 $uid = $aUser['uid'];
231                                 $success = User::authenticate($aUser, $aCommand[3]);
232                                 $Error = $success === 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                 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
274
275                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
276
277                 $ch = curl_init();
278                 curl_setopt($ch, CURLOPT_URL, $url);
279                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
280                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
281                 curl_setopt($ch, CURLOPT_HEADER, true);
282                 curl_setopt($ch, CURLOPT_NOBODY, true);
283                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
284                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
285
286                 curl_exec($ch);
287                 $curl_info = @curl_getinfo($ch);
288                 $http_code = $curl_info['http_code'];
289                 curl_close($ch);
290
291                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
292
293                 return $http_code == 200;
294         }
295
296         /**
297          * @brief Set the hostname for this process
298          *
299          * @param string $host The hostname
300          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
301          */
302         private function setHost($host)
303         {
304                 if (!empty($this->host)) {
305                         return;
306                 }
307
308                 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
309
310                 $this->host = $host;
311
312                 $lockpath = Config::get('jabber', 'lockpath');
313                 if (is_null($lockpath)) {
314                         $this->writeLog(LOG_INFO, 'No lockpath defined.');
315                         return;
316                 }
317
318                 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
319                 if (PidFile::isRunningProcess($file)) {
320                         if (PidFile::killProcess($file)) {
321                                 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
322                         } else {
323                                 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
324                                 die();
325                         }
326                 }
327
328                 // Now it is safe to create the pid file
329                 PidFile::create($file);
330                 if (!file_exists($file)) {
331                         $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
332                 }
333         }
334
335         /**
336          * @brief write data to the syslog
337          *
338          * @param integer $loglevel The syslog loglevel
339          * @param string $sMessage The syslog message
340          */
341         private function writeLog($loglevel, $sMessage)
342         {
343                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
344                         return;
345                 }
346                 syslog($loglevel, $sMessage);
347         }
348
349         /**
350          * @brief destroy the class, close the syslog connection.
351          */
352         public function __destruct()
353         {
354                 $this->writeLog(LOG_NOTICE, 'stop');
355                 closelog();
356         }
357 }