4 * ejabberd extauth script for the integration with friendica
6 * Originally written for joomla by Dalibor Karlovic <dado@krizevci.info>
7 * modified for Friendica by Michael Vogel <icarus@dabo.de>
10 * Latest version of the original script for joomla is available at:
11 * http://87.230.15.86/~dado/ejabberd/joomla-login
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
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
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"}.
25 * - Restart your ejabberd service, you should be able to login with your friendica auth info
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)"
35 namespace Friendica\Security;
39 use Friendica\Core\Config\IConfig;
40 use Friendica\Core\PConfig\IPConfig;
41 use Friendica\Database\Database;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPException;
45 use Friendica\Util\PidFile;
74 * @param App\Mode $appMode
75 * @param IConfig $config
76 * @param IPConfig $pConfig
77 * @param Database $dba
78 * @param App\BaseURL $baseURL
81 public function __construct(App\Mode $appMode, IConfig $config, IPConfig $pConfig, Database $dba, App\BaseURL $baseURL)
83 $this->appMode = $appMode;
84 $this->config = $config;
85 $this->pConfig = $pConfig;
87 $this->baseURL = $baseURL;
89 $this->bDebug = (int)$config->get('jabber', 'debug');
91 openlog('auth_ejabberd', LOG_PID, LOG_USER);
93 $this->writeLog(LOG_NOTICE, 'start');
97 * Standard input reading function, executes the auth with the provided
100 * @throws HTTPException\InternalServerErrorException
102 public function readStdin()
104 if (!$this->appMode->isNormal()) {
105 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
109 while (!feof(STDIN)) {
110 // Quit if the database connection went down
111 if (!$this->dba->isConnected()) {
112 $this->writeLog(LOG_ERR, 'the database connection went down');
116 $iHeader = fgets(STDIN, 3);
117 if (empty($iHeader)) {
118 $this->writeLog(LOG_ERR, 'empty stdin');
122 $aLength = unpack('n', $iHeader);
123 $iLength = $aLength['1'];
125 // No data? Then quit
127 $this->writeLog(LOG_ERR, 'we got no data, quitting');
132 $sData = fgets(STDIN, $iLength + 1);
133 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
134 $aCommand = explode(':', $sData);
135 if (is_array($aCommand)) {
136 switch ($aCommand[0]) {
138 // Check the existance of a given username
139 $this->isUser($aCommand);
142 // Check if the givven password is correct
143 $this->auth($aCommand);
146 // We don't accept the setting of passwords here
147 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
148 fwrite(STDOUT, pack('nn', 2, 0));
151 // We don't know the given command
152 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
153 fwrite(STDOUT, pack('nn', 2, 0));
157 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
158 fwrite(STDOUT, pack('nn', 2, 0));
164 * Check if the given username exists
166 * @param array $aCommand The command array
167 * @throws HTTPException\InternalServerErrorException
169 private function isUser(array $aCommand)
171 // Check if there is a username
172 if (!isset($aCommand[1])) {
173 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
174 fwrite(STDOUT, pack('nn', 2, 0));
178 // We only allow one process per hostname. So we set a lock file
179 // Problem: We get the firstname after the first auth - not before
180 $this->setHost($aCommand[2]);
182 // Now we check if the given user is valid
183 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
185 // Does the hostname match? So we try directly
186 if ($this->baseURL->getHostname() == $aCommand[2]) {
187 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
188 $found = $this->dba->exists('user', ['nickname' => $sUser]);
193 // If the hostnames doesn't match or there is some failure, we try to check remotely
195 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
200 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
201 fwrite(STDOUT, pack('nn', 2, 1));
203 // The user isn't okay
204 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
205 fwrite(STDOUT, pack('nn', 2, 0));
210 * Check remote user existance via HTTP(S)
212 * @param string $host The hostname
213 * @param string $user Username
214 * @param boolean $ssl Should the check be done via SSL?
216 * @return boolean Was the user found?
217 * @throws HTTPException\InternalServerErrorException
219 private function checkUser($host, $user, $ssl)
221 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
223 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
225 $curlResult = DI::httpRequest()->get($url);
227 if (!$curlResult->isSuccess()) {
231 if ($curlResult->getReturnCode() != 200) {
235 $json = @json_decode($curlResult->getBody());
236 if (!is_object($json)) {
240 return $json->nick == $user;
244 * Authenticate the given user and password
246 * @param array $aCommand The command array
249 private function auth(array $aCommand)
251 // check user authentication
252 if (sizeof($aCommand) != 4) {
253 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
254 fwrite(STDOUT, pack('nn', 2, 0));
258 // We only allow one process per hostname. So we set a lock file
259 // Problem: We get the firstname after the first auth - not before
260 $this->setHost($aCommand[2]);
262 // We now check if the password match
263 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
266 // Does the hostname match? So we try directly
267 if ($this->baseURL->getHostname() == $aCommand[2]) {
269 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
270 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
271 } catch (HTTPException\ForbiddenException $ex) {
272 // User exists, authentication failed
273 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
274 $aUser = User::getByNickname($sUser, ['uid']);
275 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
276 $Error = ($aCommand[3] != $sPassword);
277 } catch (\Throwable $ex) {
278 // User doesn't exist and any other failure case
279 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
286 // If the hostnames doesn't match or there is some failure, we try to check remotely
287 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
288 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
289 fwrite(STDOUT, pack('nn', 2, 0));
291 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
292 fwrite(STDOUT, pack('nn', 2, 1));
297 * Check remote credentials via HTTP(S)
299 * @param string $host The hostname
300 * @param string $user Username
301 * @param string $password Password
302 * @param boolean $ssl Should the check be done via SSL?
304 * @return boolean Are the credentials okay?
306 private function checkCredentials($host, $user, $password, $ssl)
308 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
310 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
313 curl_setopt($ch, CURLOPT_URL, $url);
314 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
315 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
316 curl_setopt($ch, CURLOPT_HEADER, true);
317 curl_setopt($ch, CURLOPT_NOBODY, true);
318 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
319 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
322 $curl_info = @curl_getinfo($ch);
323 $http_code = $curl_info['http_code'];
326 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
328 return $http_code == 200;
332 * Set the hostname for this process
334 * @param string $host The hostname
336 private function setHost($host)
338 if (!empty($this->host)) {
342 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
346 $lockpath = $this->config->get('jabber', 'lockpath');
347 if (is_null($lockpath)) {
348 $this->writeLog(LOG_INFO, 'No lockpath defined.');
352 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
353 if (PidFile::isRunningProcess($file)) {
354 if (PidFile::killProcess($file)) {
355 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
357 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
362 // Now it is safe to create the pid file
363 PidFile::create($file);
364 if (!file_exists($file)) {
365 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
370 * write data to the syslog
372 * @param integer $loglevel The syslog loglevel
373 * @param string $sMessage The syslog message
375 private function writeLog($loglevel, $sMessage)
377 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
380 syslog($loglevel, $sMessage);
384 * destroy the class, close the syslog connection.
386 public function __destruct()
388 $this->writeLog(LOG_NOTICE, 'stop');