]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Move post/curl/fetchUrl/fetchUrlFull to own class "Network\HTTPRequest"
[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\Database\DBA;
38 use Friendica\DI;
39 use Friendica\Model\User;
40 use Friendica\Network\HTTPRequest;
41
42 class ExAuth
43 {
44         private $bDebug;
45         private $host;
46
47         /**
48          * Create the class
49          *
50          */
51         public function __construct()
52         {
53                 $this->bDebug = (int) DI::config()->get('jabber', 'debug');
54
55                 openlog('auth_ejabberd', LOG_PID, LOG_USER);
56
57                 $this->writeLog(LOG_NOTICE, 'start');
58         }
59
60         /**
61          * 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                         if (empty($iHeader)) {
78                                 $this->writeLog(LOG_ERR, 'empty stdin');
79                                 return;
80                         }
81
82                         $aLength = unpack('n', $iHeader);
83                         $iLength = $aLength['1'];
84
85                         // No data? Then quit
86                         if ($iLength == 0) {
87                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');
88                                 return;
89                         }
90
91                         // Fetching the data
92                         $sData = fgets(STDIN, $iLength + 1);
93                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
94                         $aCommand = explode(':', $sData);
95                         if (is_array($aCommand)) {
96                                 switch ($aCommand[0]) {
97                                         case 'isuser':
98                                                 // Check the existance of a given username
99                                                 $this->isUser($aCommand);
100                                                 break;
101                                         case 'auth':
102                                                 // Check if the givven password is correct
103                                                 $this->auth($aCommand);
104                                                 break;
105                                         case 'setpass':
106                                                 // We don't accept the setting of passwords here
107                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
108                                                 fwrite(STDOUT, pack('nn', 2, 0));
109                                                 break;
110                                         default:
111                                                 // We don't know the given command
112                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
113                                                 fwrite(STDOUT, pack('nn', 2, 0));
114                                                 break;
115                                 }
116                         } else {
117                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
118                                 fwrite(STDOUT, pack('nn', 2, 0));
119                         }
120                 }
121         }
122
123         /**
124          * Check if the given username exists
125          *
126          * @param array $aCommand The command array
127          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128          */
129         private function isUser(array $aCommand)
130         {
131                 // Check if there is a username
132                 if (!isset($aCommand[1])) {
133                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
134                         fwrite(STDOUT, pack('nn', 2, 0));
135                         return;
136                 }
137
138                 // We only allow one process per hostname. So we set a lock file
139                 // Problem: We get the firstname after the first auth - not before
140                 $this->setHost($aCommand[2]);
141
142                 // Now we check if the given user is valid
143                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
144
145                 // Does the hostname match? So we try directly
146                 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
147                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
148                         $found = DBA::exists('user', ['nickname' => $sUser]);
149                 } else {
150                         $found = false;
151                 }
152
153                 // If the hostnames doesn't match or there is some failure, we try to check remotely
154                 if (!$found) {
155                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);
156                 }
157
158                 if ($found) {
159                         // The user is okay
160                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
161                         fwrite(STDOUT, pack('nn', 2, 1));
162                 } else {
163                         // The user isn't okay
164                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
165                         fwrite(STDOUT, pack('nn', 2, 0));
166                 }
167         }
168
169         /**
170          * Check remote user existance via HTTP(S)
171          *
172          * @param string  $host The hostname
173          * @param string  $user Username
174          * @param boolean $ssl  Should the check be done via SSL?
175          *
176          * @return boolean Was the user found?
177          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
178          */
179         private function checkUser($host, $user, $ssl)
180         {
181                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
182
183                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
184
185                 $curlResult = HTTPRequest::curl($url);
186
187                 if (!$curlResult->isSuccess()) {
188                         return false;
189                 }
190
191                 if ($curlResult->getReturnCode() != 200) {
192                         return false;
193                 }
194
195                 $json = @json_decode($curlResult->getBody());
196                 if (!is_object($json)) {
197                         return false;
198                 }
199
200                 return $json->nick == $user;
201         }
202
203         /**
204          * Authenticate the given user and password
205          *
206          * @param array $aCommand The command array
207          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208          */
209         private function auth(array $aCommand)
210         {
211                 // check user authentication
212                 if (sizeof($aCommand) != 4) {
213                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
214                         fwrite(STDOUT, pack('nn', 2, 0));
215                         return;
216                 }
217
218                 // We only allow one process per hostname. So we set a lock file
219                 // Problem: We get the firstname after the first auth - not before
220                 $this->setHost($aCommand[2]);
221
222                 // We now check if the password match
223                 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
224
225                 // Does the hostname match? So we try directly
226                 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
227                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
228
229                         $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
230                         if (DBA::isResult($aUser)) {
231                                 $uid = $aUser['uid'];
232                                 $success = User::authenticate($aUser, $aCommand[3], true);
233                                 $Error = $success === false;
234                         } else {
235                                 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
236                                 $Error = true;
237                                 $uid = -1;
238                         }
239                         if ($Error) {
240                                 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
241                                 $sPassword = DI::pConfig()->get($uid, 'xmpp', 'password', null, true);
242                                 $Error = ($aCommand[3] != $sPassword);
243                         }
244                 } else {
245                         $Error = true;
246                 }
247
248                 // If the hostnames doesn't match or there is some failure, we try to check remotely
249                 if ($Error) {
250                         $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);
251                 }
252
253                 if ($Error) {
254                         $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
255                         fwrite(STDOUT, pack('nn', 2, 0));
256                 } else {
257                         $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
258                         fwrite(STDOUT, pack('nn', 2, 1));
259                 }
260         }
261
262         /**
263          * Check remote credentials via HTTP(S)
264          *
265          * @param string $host The hostname
266          * @param string $user Username
267          * @param string $password Password
268          * @param boolean $ssl Should the check be done via SSL?
269          *
270          * @return boolean Are the credentials okay?
271          */
272         private function checkCredentials($host, $user, $password, $ssl)
273         {
274                 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
275
276                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
277
278                 $ch = curl_init();
279                 curl_setopt($ch, CURLOPT_URL, $url);
280                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
281                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
282                 curl_setopt($ch, CURLOPT_HEADER, true);
283                 curl_setopt($ch, CURLOPT_NOBODY, true);
284                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
285                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
286
287                 curl_exec($ch);
288                 $curl_info = @curl_getinfo($ch);
289                 $http_code = $curl_info['http_code'];
290                 curl_close($ch);
291
292                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
293
294                 return $http_code == 200;
295         }
296
297         /**
298          * Set the hostname for this process
299          *
300          * @param string $host The hostname
301          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302          */
303         private function setHost($host)
304         {
305                 if (!empty($this->host)) {
306                         return;
307                 }
308
309                 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
310
311                 $this->host = $host;
312
313                 $lockpath = DI::config()->get('jabber', 'lockpath');
314                 if (is_null($lockpath)) {
315                         $this->writeLog(LOG_INFO, 'No lockpath defined.');
316                         return;
317                 }
318
319                 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
320                 if (PidFile::isRunningProcess($file)) {
321                         if (PidFile::killProcess($file)) {
322                                 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
323                         } else {
324                                 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
325                                 die();
326                         }
327                 }
328
329                 // Now it is safe to create the pid file
330                 PidFile::create($file);
331                 if (!file_exists($file)) {
332                         $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
333                 }
334         }
335
336         /**
337          * write data to the syslog
338          *
339          * @param integer $loglevel The syslog loglevel
340          * @param string $sMessage The syslog message
341          */
342         private function writeLog($loglevel, $sMessage)
343         {
344                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
345                         return;
346                 }
347                 syslog($loglevel, $sMessage);
348         }
349
350         /**
351          * destroy the class, close the syslog connection.
352          */
353         public function __destruct()
354         {
355                 $this->writeLog(LOG_NOTICE, 'stop');
356                 closelog();
357         }
358 }