]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Fix mods/README.md format
[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 require_once 'include/dba.php';
43
44 class ExAuth
45 {
46         private $bDebug;
47         private $host;
48
49         /**
50          * @brief Create the class
51          *
52          * @param boolean $bDebug Debug mode
53          */
54         public function __construct()
55         {
56                 $this->bDebug = (int) Config::get('jabber', 'debug');
57
58                 openlog('auth_ejabberd', LOG_PID, LOG_USER);
59
60                 $this->writeLog(LOG_NOTICE, 'start');
61         }
62
63         /**
64          * @brief Standard input reading function, executes the auth with the provided
65          * parameters
66          *
67          * @return null
68          */
69         public function readStdin()
70         {
71                 while (!feof(STDIN)) {
72                         // Quit if the database connection went down
73                         if (!DBA::connected()) {
74                                 $this->writeLog(LOG_ERR, 'the database connection went down');
75                                 return;
76                         }
77
78                         $iHeader = fgets(STDIN, 3);
79                         $aLength = unpack('n', $iHeader);
80                         $iLength = $aLength['1'];
81
82                         // No data? Then quit
83                         if ($iLength == 0) {
84                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');
85                                 return;
86                         }
87
88                         // Fetching the data
89                         $sData = fgets(STDIN, $iLength + 1);
90                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
91                         $aCommand = explode(':', $sData);
92                         if (is_array($aCommand)) {
93                                 switch ($aCommand[0]) {
94                                         case 'isuser':
95                                                 // Check the existance of a given username
96                                                 $this->isUser($aCommand);
97                                                 break;
98                                         case 'auth':
99                                                 // Check if the givven password is correct
100                                                 $this->auth($aCommand);
101                                                 break;
102                                         case 'setpass':
103                                                 // We don't accept the setting of passwords here
104                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
105                                                 fwrite(STDOUT, pack('nn', 2, 0));
106                                                 break;
107                                         default:
108                                                 // We don't know the given command
109                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
110                                                 fwrite(STDOUT, pack('nn', 2, 0));
111                                                 break;
112                                 }
113                         } else {
114                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
115                                 fwrite(STDOUT, pack('nn', 2, 0));
116                         }
117                 }
118         }
119
120         /**
121          * @brief Check if the given username exists
122          *
123          * @param array $aCommand The command array
124          */
125         private function isUser(array $aCommand)
126         {
127                 $a = get_app();
128
129                 // Check if there is a username
130                 if (!isset($aCommand[1])) {
131                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
132                         fwrite(STDOUT, pack('nn', 2, 0));
133                         return;
134                 }
135
136                 // We only allow one process per hostname. So we set a lock file
137                 // Problem: We get the firstname after the first auth - not before
138                 $this->setHost($aCommand[2]);
139
140                 // Now we check if the given user is valid
141                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
142
143                 // Does the hostname match? So we try directly
144                 if ($a->getHostName() == $aCommand[2]) {
145                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
146                         $found = DBA::exists('user', ['nickname' => $sUser]);
147                 } else {
148                         $found = false;
149                 }
150
151                 // If the hostnames doesn't match or there is some failure, we try to check remotely
152                 if (!$found) {
153                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);
154                 }
155
156                 if ($found) {
157                         // The user is okay
158                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
159                         fwrite(STDOUT, pack('nn', 2, 1));
160                 } else {
161                         // The user isn't okay
162                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
163                         fwrite(STDOUT, pack('nn', 2, 0));
164                 }
165         }
166
167         /**
168          * @brief Check remote user existance via HTTP(S)
169          *
170          * @param string $host The hostname
171          * @param string $user Username
172          * @param boolean $ssl Should the check be done via SSL?
173          *
174          * @return boolean Was the user found?
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          */
205         private function auth(array $aCommand)
206         {
207                 $a = get_app();
208
209                 // check user authentication
210                 if (sizeof($aCommand) != 4) {
211                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
212                         fwrite(STDOUT, pack('nn', 2, 0));
213                         return;
214                 }
215
216                 // We only allow one process per hostname. So we set a lock file
217                 // Problem: We get the firstname after the first auth - not before
218                 $this->setHost($aCommand[2]);
219
220                 // We now check if the password match
221                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
222
223                 // Does the hostname match? So we try directly
224                 if ($a->getHostName() == $aCommand[2]) {
225                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
226
227                         $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
228                         if (DBA::isResult($aUser)) {
229                                 $uid = $aUser['uid'];
230                                 $success = User::authenticate($aUser, $aCommand[3]);
231                                 $Error = $success === 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                         $this->writeLog(LOG_INFO, 'No lockpath defined.');
313                         return;
314                 }
315
316                 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
317                 if (PidFile::isRunningProcess($file)) {
318                         if (PidFile::killProcess($file)) {
319                                 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
320                         } else {
321                                 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
322                                 die();
323                         }
324                 }
325
326                 // Now it is safe to create the pid file
327                 PidFile::create($file);
328                 if (!file_exists($file)) {
329                         $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
330                 }
331         }
332
333         /**
334          * @brief write data to the syslog
335          *
336          * @param integer $loglevel The syslog loglevel
337          * @param string $sMessage The syslog message
338          */
339         private function writeLog($loglevel, $sMessage)
340         {
341                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
342                         return;
343                 }
344                 syslog($loglevel, $sMessage);
345         }
346
347         /**
348          * @brief destroy the class, close the syslog connection.
349          */
350         public function __destruct()
351         {
352                 $this->writeLog(LOG_NOTICE, 'stop');
353                 closelog();
354         }
355 }