]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Merge pull request #8132 from annando/child-user
[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\Database\DBA;
39 use Friendica\DI;
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                 // Check if there is a username
127                 if (!isset($aCommand[1])) {
128                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
129                         fwrite(STDOUT, pack('nn', 2, 0));
130                         return;
131                 }
132
133                 // We only allow one process per hostname. So we set a lock file
134                 // Problem: We get the firstname after the first auth - not before
135                 $this->setHost($aCommand[2]);
136
137                 // Now we check if the given user is valid
138                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
139
140                 // Does the hostname match? So we try directly
141                 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
142                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
143                         $found = DBA::exists('user', ['nickname' => $sUser]);
144                 } else {
145                         $found = false;
146                 }
147
148                 // If the hostnames doesn't match or there is some failure, we try to check remotely
149                 if (!$found) {
150                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);
151                 }
152
153                 if ($found) {
154                         // The user is okay
155                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
156                         fwrite(STDOUT, pack('nn', 2, 1));
157                 } else {
158                         // The user isn't okay
159                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
160                         fwrite(STDOUT, pack('nn', 2, 0));
161                 }
162         }
163
164         /**
165          * @brief Check remote user existance via HTTP(S)
166          *
167          * @param string  $host The hostname
168          * @param string  $user Username
169          * @param boolean $ssl  Should the check be done via SSL?
170          *
171          * @return boolean Was the user found?
172          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203          */
204         private function auth(array $aCommand)
205         {
206                 // check user authentication
207                 if (sizeof($aCommand) != 4) {
208                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
209                         fwrite(STDOUT, pack('nn', 2, 0));
210                         return;
211                 }
212
213                 // We only allow one process per hostname. So we set a lock file
214                 // Problem: We get the firstname after the first auth - not before
215                 $this->setHost($aCommand[2]);
216
217                 // We now check if the password match
218                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
219
220                 // Does the hostname match? So we try directly
221                 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
222                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
223
224                         $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
225                         if (DBA::isResult($aUser)) {
226                                 $uid = $aUser['uid'];
227                                 $success = User::authenticate($aUser, $aCommand[3], true);
228                                 $Error = $success === false;
229                         } else {
230                                 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
231                                 $Error = true;
232                                 $uid = -1;
233                         }
234                         if ($Error) {
235                                 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
236                                 $sPassword = DI::pConfig()->get($uid, 'xmpp', 'password', null, true);
237                                 $Error = ($aCommand[3] != $sPassword);
238                         }
239                 } else {
240                         $Error = true;
241                 }
242
243                 // If the hostnames doesn't match or there is some failure, we try to check remotely
244                 if ($Error) {
245                         $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);
246                 }
247
248                 if ($Error) {
249                         $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
250                         fwrite(STDOUT, pack('nn', 2, 0));
251                 } else {
252                         $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
253                         fwrite(STDOUT, pack('nn', 2, 1));
254                 }
255         }
256
257         /**
258          * @brief Check remote credentials via HTTP(S)
259          *
260          * @param string $host The hostname
261          * @param string $user Username
262          * @param string $password Password
263          * @param boolean $ssl Should the check be done via SSL?
264          *
265          * @return boolean Are the credentials okay?
266          */
267         private function checkCredentials($host, $user, $password, $ssl)
268         {
269                 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
270
271                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
272
273                 $ch = curl_init();
274                 curl_setopt($ch, CURLOPT_URL, $url);
275                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
276                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
277                 curl_setopt($ch, CURLOPT_HEADER, true);
278                 curl_setopt($ch, CURLOPT_NOBODY, true);
279                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
280                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
281
282                 curl_exec($ch);
283                 $curl_info = @curl_getinfo($ch);
284                 $http_code = $curl_info['http_code'];
285                 curl_close($ch);
286
287                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
288
289                 return $http_code == 200;
290         }
291
292         /**
293          * @brief Set the hostname for this process
294          *
295          * @param string $host The hostname
296          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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 }