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;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPException;
73 * @param App\Mode $appMode
74 * @param IConfig $config
75 * @param IPConfig $pConfig
76 * @param Database $dba
77 * @param App\BaseURL $baseURL
80 public function __construct(App\Mode $appMode, IConfig $config, IPConfig $pConfig, Database $dba, App\BaseURL $baseURL)
82 $this->appMode = $appMode;
83 $this->config = $config;
84 $this->pConfig = $pConfig;
86 $this->baseURL = $baseURL;
88 $this->bDebug = (int)$config->get('jabber', 'debug');
90 openlog('auth_ejabberd', LOG_PID, LOG_USER);
92 $this->writeLog(LOG_NOTICE, 'start');
96 * Standard input reading function, executes the auth with the provided
99 * @throws HTTPException\InternalServerErrorException
101 public function readStdin()
103 if (!$this->appMode->isNormal()) {
104 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
108 while (!feof(STDIN)) {
109 // Quit if the database connection went down
110 if (!$this->dba->isConnected()) {
111 $this->writeLog(LOG_ERR, 'the database connection went down');
115 $iHeader = fgets(STDIN, 3);
116 if (empty($iHeader)) {
117 $this->writeLog(LOG_ERR, 'empty stdin');
121 $aLength = unpack('n', $iHeader);
122 $iLength = $aLength['1'];
124 // No data? Then quit
126 $this->writeLog(LOG_ERR, 'we got no data, quitting');
131 $sData = fgets(STDIN, $iLength + 1);
132 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
133 $aCommand = explode(':', $sData);
134 if (is_array($aCommand)) {
135 switch ($aCommand[0]) {
137 // Check the existance of a given username
138 $this->isUser($aCommand);
141 // Check if the givven password is correct
142 $this->auth($aCommand);
145 // We don't accept the setting of passwords here
146 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
147 fwrite(STDOUT, pack('nn', 2, 0));
150 // We don't know the given command
151 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
152 fwrite(STDOUT, pack('nn', 2, 0));
156 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
157 fwrite(STDOUT, pack('nn', 2, 0));
163 * Check if the given username exists
165 * @param array $aCommand The command array
166 * @throws HTTPException\InternalServerErrorException
168 private function isUser(array $aCommand)
170 // Check if there is a username
171 if (!isset($aCommand[1])) {
172 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
173 fwrite(STDOUT, pack('nn', 2, 0));
177 // We only allow one process per hostname. So we set a lock file
178 // Problem: We get the firstname after the first auth - not before
179 $this->setHost($aCommand[2]);
181 // Now we check if the given user is valid
182 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
184 // Does the hostname match? So we try directly
185 if ($this->baseURL->getHostname() == $aCommand[2]) {
186 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
187 $found = $this->dba->exists('user', ['nickname' => $sUser]);
192 // If the hostnames doesn't match or there is some failure, we try to check remotely
194 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
199 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
200 fwrite(STDOUT, pack('nn', 2, 1));
202 // The user isn't okay
203 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
204 fwrite(STDOUT, pack('nn', 2, 0));
209 * Check remote user existance via HTTP(S)
211 * @param string $host The hostname
212 * @param string $user Username
213 * @param boolean $ssl Should the check be done via SSL?
215 * @return boolean Was the user found?
216 * @throws HTTPException\InternalServerErrorException
218 private function checkUser($host, $user, $ssl)
220 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
222 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
224 $curlResult = DI::httpRequest()->get($url);
226 if (!$curlResult->isSuccess()) {
230 if ($curlResult->getReturnCode() != 200) {
234 $json = @json_decode($curlResult->getBody());
235 if (!is_object($json)) {
239 return $json->nick == $user;
243 * Authenticate the given user and password
245 * @param array $aCommand The command array
248 private function auth(array $aCommand)
250 // check user authentication
251 if (sizeof($aCommand) != 4) {
252 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
253 fwrite(STDOUT, pack('nn', 2, 0));
257 // We only allow one process per hostname. So we set a lock file
258 // Problem: We get the firstname after the first auth - not before
259 $this->setHost($aCommand[2]);
261 // We now check if the password match
262 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
265 // Does the hostname match? So we try directly
266 if ($this->baseURL->getHostname() == $aCommand[2]) {
268 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
269 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
270 } catch (HTTPException\ForbiddenException $ex) {
271 // User exists, authentication failed
272 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
273 $aUser = User::getByNickname($sUser, ['uid']);
274 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
275 $Error = ($aCommand[3] != $sPassword);
276 } catch (\Throwable $ex) {
277 // User doesn't exist and any other failure case
278 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
285 // If the hostnames doesn't match or there is some failure, we try to check remotely
286 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
287 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
288 fwrite(STDOUT, pack('nn', 2, 0));
290 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
291 fwrite(STDOUT, pack('nn', 2, 1));
296 * Check remote credentials via HTTP(S)
298 * @param string $host The hostname
299 * @param string $user Username
300 * @param string $password Password
301 * @param boolean $ssl Should the check be done via SSL?
303 * @return boolean Are the credentials okay?
305 private function checkCredentials($host, $user, $password, $ssl)
307 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
309 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
312 curl_setopt($ch, CURLOPT_URL, $url);
313 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
314 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
315 curl_setopt($ch, CURLOPT_HEADER, true);
316 curl_setopt($ch, CURLOPT_NOBODY, true);
317 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
318 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
321 $curl_info = @curl_getinfo($ch);
322 $http_code = $curl_info['http_code'];
325 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
327 return $http_code == 200;
331 * Set the hostname for this process
333 * @param string $host The hostname
335 private function setHost($host)
337 if (!empty($this->host)) {
341 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
345 $lockpath = $this->config->get('jabber', 'lockpath');
346 if (is_null($lockpath)) {
347 $this->writeLog(LOG_INFO, 'No lockpath defined.');
351 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
352 if (PidFile::isRunningProcess($file)) {
353 if (PidFile::killProcess($file)) {
354 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
356 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
361 // Now it is safe to create the pid file
362 PidFile::create($file);
363 if (!file_exists($file)) {
364 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
369 * write data to the syslog
371 * @param integer $loglevel The syslog loglevel
372 * @param string $sMessage The syslog message
374 private function writeLog($loglevel, $sMessage)
376 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
379 syslog($loglevel, $sMessage);
383 * destroy the class, close the syslog connection.
385 public function __destruct()
387 $this->writeLog(LOG_NOTICE, 'stop');