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\Capability\IManageConfigValues;
40 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
41 use Friendica\Database\Database;
43 use Friendica\Model\User;
44 use Friendica\Network\HTTPException;
45 use Friendica\Util\PidFile;
57 * @var IManageConfigValues
61 * @var IManagePersonalConfigValues
74 * @param App\Mode $appMode
75 * @param IManageConfigValues $config
76 * @param IManagePersonalConfigValues $pConfig
77 * @param Database $dba
78 * @param App\BaseURL $baseURL
82 public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
84 $this->appMode = $appMode;
85 $this->config = $config;
86 $this->pConfig = $pConfig;
88 $this->baseURL = $baseURL;
90 $this->bDebug = (int)$config->get('jabber', 'debug');
92 openlog('auth_ejabberd', LOG_PID, LOG_USER);
94 $this->writeLog(LOG_NOTICE, 'start');
98 * Standard input reading function, executes the auth with the provided
101 * @throws HTTPException\InternalServerErrorException
103 public function readStdin()
105 if (!$this->appMode->isNormal()) {
106 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
110 while (!feof(STDIN)) {
111 // Quit if the database connection went down
112 if (!$this->dba->isConnected()) {
113 $this->writeLog(LOG_ERR, 'the database connection went down');
117 $iHeader = fgets(STDIN, 3);
118 if (empty($iHeader)) {
119 $this->writeLog(LOG_ERR, 'empty stdin');
123 $aLength = unpack('n', $iHeader);
124 $iLength = $aLength['1'];
126 // No data? Then quit
128 $this->writeLog(LOG_ERR, 'we got no data, quitting');
133 $sData = fgets(STDIN, $iLength + 1);
134 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
135 $aCommand = explode(':', $sData);
136 if (is_array($aCommand)) {
137 switch ($aCommand[0]) {
139 // Check the existance of a given username
140 $this->isUser($aCommand);
143 // Check if the givven password is correct
144 $this->auth($aCommand);
147 // We don't accept the setting of passwords here
148 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
149 fwrite(STDOUT, pack('nn', 2, 0));
152 // We don't know the given command
153 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
154 fwrite(STDOUT, pack('nn', 2, 0));
158 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
159 fwrite(STDOUT, pack('nn', 2, 0));
165 * Check if the given username exists
167 * @param array $aCommand The command array
168 * @throws HTTPException\InternalServerErrorException
170 private function isUser(array $aCommand)
172 // Check if there is a username
173 if (!isset($aCommand[1])) {
174 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
175 fwrite(STDOUT, pack('nn', 2, 0));
179 // We only allow one process per hostname. So we set a lock file
180 // Problem: We get the firstname after the first auth - not before
181 $this->setHost($aCommand[2]);
183 // Now we check if the given user is valid
184 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
186 // Does the hostname match? So we try directly
187 if ($this->baseURL->getHostname() == $aCommand[2]) {
188 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
189 $found = $this->dba->exists('user', ['nickname' => $sUser]);
194 // If the hostnames doesn't match or there is some failure, we try to check remotely
196 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
201 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
202 fwrite(STDOUT, pack('nn', 2, 1));
204 // The user isn't okay
205 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
206 fwrite(STDOUT, pack('nn', 2, 0));
211 * Check remote user existance via HTTP(S)
213 * @param string $host The hostname
214 * @param string $user Username
215 * @param boolean $ssl Should the check be done via SSL?
217 * @return boolean Was the user found?
218 * @throws HTTPException\InternalServerErrorException
220 private function checkUser($host, $user, $ssl)
222 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
224 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
226 $curlResult = DI::httpClient()->get($url);
228 if (!$curlResult->isSuccess()) {
232 if ($curlResult->getReturnCode() != 200) {
236 $json = @json_decode($curlResult->getBody());
237 if (!is_object($json)) {
241 return $json->nick == $user;
245 * Authenticate the given user and password
247 * @param array $aCommand The command array
250 private function auth(array $aCommand)
252 // check user authentication
253 if (sizeof($aCommand) != 4) {
254 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
255 fwrite(STDOUT, pack('nn', 2, 0));
259 // We only allow one process per hostname. So we set a lock file
260 // Problem: We get the firstname after the first auth - not before
261 $this->setHost($aCommand[2]);
263 // We now check if the password match
264 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
267 // Does the hostname match? So we try directly
268 if ($this->baseURL->getHostname() == $aCommand[2]) {
270 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
271 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
272 } catch (HTTPException\ForbiddenException $ex) {
273 // User exists, authentication failed
274 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
275 $aUser = User::getByNickname($sUser, ['uid']);
276 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
277 $Error = ($aCommand[3] != $sPassword);
278 } catch (\Throwable $ex) {
279 // User doesn't exist and any other failure case
280 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
287 // If the hostnames doesn't match or there is some failure, we try to check remotely
288 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
289 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
290 fwrite(STDOUT, pack('nn', 2, 0));
292 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
293 fwrite(STDOUT, pack('nn', 2, 1));
298 * Check remote credentials via HTTP(S)
300 * @param string $host The hostname
301 * @param string $user Username
302 * @param string $password Password
303 * @param boolean $ssl Should the check be done via SSL?
305 * @return boolean Are the credentials okay?
307 private function checkCredentials($host, $user, $password, $ssl)
309 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
311 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
314 curl_setopt($ch, CURLOPT_URL, $url);
315 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
316 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
317 curl_setopt($ch, CURLOPT_HEADER, true);
318 curl_setopt($ch, CURLOPT_NOBODY, true);
319 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
320 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
323 $curl_info = @curl_getinfo($ch);
324 $http_code = $curl_info['http_code'];
327 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
329 return $http_code == 200;
333 * Set the hostname for this process
335 * @param string $host The hostname
337 private function setHost($host)
339 if (!empty($this->host)) {
343 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
347 $lockpath = $this->config->get('jabber', 'lockpath');
348 if (is_null($lockpath)) {
349 $this->writeLog(LOG_INFO, 'No lockpath defined.');
353 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
354 if (PidFile::isRunningProcess($file)) {
355 if (PidFile::killProcess($file)) {
356 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
358 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
363 // Now it is safe to create the pid file
364 PidFile::create($file);
365 if (!file_exists($file)) {
366 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
371 * write data to the syslog
373 * @param integer $loglevel The syslog loglevel
374 * @param string $sMessage The syslog message
376 private function writeLog($loglevel, $sMessage)
378 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
381 syslog($loglevel, $sMessage);
385 * destroy the class, close the syslog connection.
387 public function __destruct()
389 $this->writeLog(LOG_NOTICE, 'stop');