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\Util;
39 use Friendica\Core\Config\IConfig;
40 use Friendica\Core\PConfig\IPConfig;
41 use Friendica\Database\Database;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPException;
72 * @param App\Mode $appMode
73 * @param IConfig $config
74 * @param IPConfig $pConfig
75 * @param Database $dba
76 * @param App\BaseURL $baseURL
79 public function __construct(App\Mode $appMode, IConfig $config, IPConfig $pConfig, Database $dba, App\BaseURL $baseURL)
81 $this->appMode = $appMode;
82 $this->config = $config;
83 $this->pConfig = $pConfig;
85 $this->baseURL = $baseURL;
87 $this->bDebug = (int)$config->get('jabber', 'debug');
89 openlog('auth_ejabberd', LOG_PID, LOG_USER);
91 $this->writeLog(LOG_NOTICE, 'start');
95 * Standard input reading function, executes the auth with the provided
98 * @throws HTTPException\InternalServerErrorException
100 public function readStdin()
102 if (!$this->appMode->isNormal()) {
103 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
107 while (!feof(STDIN)) {
108 // Quit if the database connection went down
109 if (!$this->dba->isConnected()) {
110 $this->writeLog(LOG_ERR, 'the database connection went down');
114 $iHeader = fgets(STDIN, 3);
115 if (empty($iHeader)) {
116 $this->writeLog(LOG_ERR, 'empty stdin');
120 $aLength = unpack('n', $iHeader);
121 $iLength = $aLength['1'];
123 // No data? Then quit
125 $this->writeLog(LOG_ERR, 'we got no data, quitting');
130 $sData = fgets(STDIN, $iLength + 1);
131 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
132 $aCommand = explode(':', $sData);
133 if (is_array($aCommand)) {
134 switch ($aCommand[0]) {
136 // Check the existance of a given username
137 $this->isUser($aCommand);
140 // Check if the givven password is correct
141 $this->auth($aCommand);
144 // We don't accept the setting of passwords here
145 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
146 fwrite(STDOUT, pack('nn', 2, 0));
149 // We don't know the given command
150 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
151 fwrite(STDOUT, pack('nn', 2, 0));
155 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
156 fwrite(STDOUT, pack('nn', 2, 0));
162 * Check if the given username exists
164 * @param array $aCommand The command array
165 * @throws HTTPException\InternalServerErrorException
167 private function isUser(array $aCommand)
169 // Check if there is a username
170 if (!isset($aCommand[1])) {
171 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
172 fwrite(STDOUT, pack('nn', 2, 0));
176 // We only allow one process per hostname. So we set a lock file
177 // Problem: We get the firstname after the first auth - not before
178 $this->setHost($aCommand[2]);
180 // Now we check if the given user is valid
181 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
183 // Does the hostname match? So we try directly
184 if ($this->baseURL->getHostname() == $aCommand[2]) {
185 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
186 $found = $this->dba->exists('user', ['nickname' => $sUser]);
191 // If the hostnames doesn't match or there is some failure, we try to check remotely
193 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
198 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
199 fwrite(STDOUT, pack('nn', 2, 1));
201 // The user isn't okay
202 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
203 fwrite(STDOUT, pack('nn', 2, 0));
208 * Check remote user existance via HTTP(S)
210 * @param string $host The hostname
211 * @param string $user Username
212 * @param boolean $ssl Should the check be done via SSL?
214 * @return boolean Was the user found?
215 * @throws HTTPException\InternalServerErrorException
217 private function checkUser($host, $user, $ssl)
219 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
221 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
223 $curlResult = DI::httpRequest()->get($url);
225 if (!$curlResult->isSuccess()) {
229 if ($curlResult->getReturnCode() != 200) {
233 $json = @json_decode($curlResult->getBody());
234 if (!is_object($json)) {
238 return $json->nick == $user;
242 * Authenticate the given user and password
244 * @param array $aCommand The command array
247 private function auth(array $aCommand)
249 // check user authentication
250 if (sizeof($aCommand) != 4) {
251 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
252 fwrite(STDOUT, pack('nn', 2, 0));
256 // We only allow one process per hostname. So we set a lock file
257 // Problem: We get the firstname after the first auth - not before
258 $this->setHost($aCommand[2]);
260 // We now check if the password match
261 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
264 // Does the hostname match? So we try directly
265 if ($this->baseURL->getHostname() == $aCommand[2]) {
267 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
268 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
269 } catch (HTTPException\ForbiddenException $ex) {
270 // User exists, authentication failed
271 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
272 $aUser = User::getByNickname($sUser, ['uid']);
273 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
274 $Error = ($aCommand[3] != $sPassword);
275 } catch (\Throwable $ex) {
276 // User doesn't exist and any other failure case
277 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
284 // If the hostnames doesn't match or there is some failure, we try to check remotely
285 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
286 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
287 fwrite(STDOUT, pack('nn', 2, 0));
289 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
290 fwrite(STDOUT, pack('nn', 2, 1));
295 * Check remote credentials via HTTP(S)
297 * @param string $host The hostname
298 * @param string $user Username
299 * @param string $password Password
300 * @param boolean $ssl Should the check be done via SSL?
302 * @return boolean Are the credentials okay?
304 private function checkCredentials($host, $user, $password, $ssl)
306 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
308 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
311 curl_setopt($ch, CURLOPT_URL, $url);
312 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
313 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
314 curl_setopt($ch, CURLOPT_HEADER, true);
315 curl_setopt($ch, CURLOPT_NOBODY, true);
316 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
317 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
320 $curl_info = @curl_getinfo($ch);
321 $http_code = $curl_info['http_code'];
324 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
326 return $http_code == 200;
330 * Set the hostname for this process
332 * @param string $host The hostname
334 private function setHost($host)
336 if (!empty($this->host)) {
340 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
344 $lockpath = $this->config->get('jabber', 'lockpath');
345 if (is_null($lockpath)) {
346 $this->writeLog(LOG_INFO, 'No lockpath defined.');
350 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
351 if (PidFile::isRunningProcess($file)) {
352 if (PidFile::killProcess($file)) {
353 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
355 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
360 // Now it is safe to create the pid file
361 PidFile::create($file);
362 if (!file_exists($file)) {
363 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
368 * write data to the syslog
370 * @param integer $loglevel The syslog loglevel
371 * @param string $sMessage The syslog message
373 private function writeLog($loglevel, $sMessage)
375 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
378 syslog($loglevel, $sMessage);
382 * destroy the class, close the syslog connection.
384 public function __destruct()
386 $this->writeLog(LOG_NOTICE, 'stop');