3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * ejabberd extauth script for the integration with friendica
22 * Originally written for joomla by Dalibor Karlovic <dado@krizevci.info>
23 * modified for Friendica by Michael Vogel <icarus@dabo.de>
26 * Latest version of the original script for joomla is available at:
27 * http://87.230.15.86/~dado/ejabberd/joomla-login
31 * - Change it's owner to whichever user is running the server, ie. ejabberd
32 * $ chown ejabberd:ejabberd /path/to/friendica/bin/auth_ejabberd.php
34 * - Change the access mode so it is readable only to the user ejabberd and has exec
35 * $ chmod 700 /path/to/friendica/bin/auth_ejabberd.php
37 * - Edit your ejabberd.cfg file, comment out your auth_method and add:
38 * {auth_method, external}.
39 * {extauth_program, "/path/to/friendica/bin/auth_ejabberd.php"}.
41 * - Restart your ejabberd service, you should be able to login with your friendica auth info
44 * - if your users have a space or a @ in their nickname, they'll run into trouble
45 * registering with any client so they should be instructed to replace these chars
46 * " " (space) is replaced with "%20"
47 * "@" is replaced with "(a)"
51 namespace Friendica\Security;
55 use Friendica\Core\Config\Capability\IManageConfigValues;
56 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
57 use Friendica\Database\Database;
59 use Friendica\Model\User;
60 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
61 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
62 use Friendica\Network\HTTPException;
63 use Friendica\Util\PidFile;
75 * @var IManageConfigValues
79 * @var IManagePersonalConfigValues
92 * @param App\Mode $appMode
93 * @param IManageConfigValues $config
94 * @param IManagePersonalConfigValues $pConfig
95 * @param Database $dba
96 * @param App\BaseURL $baseURL
100 public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
102 $this->appMode = $appMode;
103 $this->config = $config;
104 $this->pConfig = $pConfig;
106 $this->baseURL = $baseURL;
108 $this->bDebug = (int)$config->get('jabber', 'debug');
110 openlog('auth_ejabberd', LOG_PID, LOG_USER);
112 $this->writeLog(LOG_NOTICE, 'start');
116 * Standard input reading function, executes the auth with the provided
119 * @throws HTTPException\InternalServerErrorException
121 public function readStdin()
123 if (!$this->appMode->isNormal()) {
124 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
128 while (!feof(STDIN)) {
129 // Quit if the database connection went down
130 if (!$this->dba->isConnected()) {
131 $this->writeLog(LOG_ERR, 'the database connection went down');
135 $iHeader = fgets(STDIN, 3);
136 if (empty($iHeader)) {
137 $this->writeLog(LOG_ERR, 'empty stdin');
141 $aLength = unpack('n', $iHeader);
142 $iLength = $aLength['1'];
144 // No data? Then quit
146 $this->writeLog(LOG_ERR, 'we got no data, quitting');
151 $sData = fgets(STDIN, $iLength + 1);
152 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
153 $aCommand = explode(':', $sData);
154 if (is_array($aCommand)) {
155 switch ($aCommand[0]) {
157 // Check the existance of a given username
158 $this->isUser($aCommand);
161 // Check if the givven password is correct
162 $this->auth($aCommand);
165 // We don't accept the setting of passwords here
166 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
167 fwrite(STDOUT, pack('nn', 2, 0));
170 // We don't know the given command
171 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
172 fwrite(STDOUT, pack('nn', 2, 0));
176 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
177 fwrite(STDOUT, pack('nn', 2, 0));
183 * Check if the given username exists
185 * @param array $aCommand The command array
186 * @throws HTTPException\InternalServerErrorException
188 private function isUser(array $aCommand)
190 // Check if there is a username
191 if (!isset($aCommand[1])) {
192 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
193 fwrite(STDOUT, pack('nn', 2, 0));
197 // We only allow one process per hostname. So we set a lock file
198 // Problem: We get the firstname after the first auth - not before
199 $this->setHost($aCommand[2]);
201 // Now we check if the given user is valid
202 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
204 // Does the hostname match? So we try directly
205 if ($this->baseURL->getHostname() == $aCommand[2]) {
206 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
207 $found = $this->dba->exists('user', ['nickname' => $sUser]);
212 // If the hostnames doesn't match or there is some failure, we try to check remotely
214 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
219 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
220 fwrite(STDOUT, pack('nn', 2, 1));
222 // The user isn't okay
223 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
224 fwrite(STDOUT, pack('nn', 2, 0));
229 * Check remote user existance via HTTP(S)
231 * @param string $host The hostname
232 * @param string $user Username
233 * @param boolean $ssl Should the check be done via SSL?
235 * @return boolean Was the user found?
236 * @throws HTTPException\InternalServerErrorException
238 private function checkUser($host, $user, $ssl)
240 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
242 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
244 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::JSON]);
246 if (!$curlResult->isSuccess()) {
250 if ($curlResult->getReturnCode() != 200) {
254 $json = @json_decode($curlResult->getBody());
255 if (!is_object($json)) {
259 return $json->nick == $user;
263 * Authenticate the given user and password
265 * @param array $aCommand The command array
268 private function auth(array $aCommand)
270 // check user authentication
271 if (sizeof($aCommand) != 4) {
272 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
273 fwrite(STDOUT, pack('nn', 2, 0));
277 // We only allow one process per hostname. So we set a lock file
278 // Problem: We get the firstname after the first auth - not before
279 $this->setHost($aCommand[2]);
281 // We now check if the password match
282 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
285 // Does the hostname match? So we try directly
286 if ($this->baseURL->getHostname() == $aCommand[2]) {
288 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
289 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
290 } catch (HTTPException\ForbiddenException $ex) {
291 // User exists, authentication failed
292 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
293 $aUser = User::getByNickname($sUser, ['uid']);
294 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
295 $Error = ($aCommand[3] != $sPassword);
296 } catch (\Throwable $ex) {
297 // User doesn't exist and any other failure case
298 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
305 // If the hostnames doesn't match or there is some failure, we try to check remotely
306 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
307 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
308 fwrite(STDOUT, pack('nn', 2, 0));
310 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
311 fwrite(STDOUT, pack('nn', 2, 1));
316 * Check remote credentials via HTTP(S)
318 * @param string $host The hostname
319 * @param string $user Username
320 * @param string $password Password
321 * @param boolean $ssl Should the check be done via SSL?
323 * @return boolean Are the credentials okay?
325 private function checkCredentials($host, $user, $password, $ssl)
327 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
329 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
332 curl_setopt($ch, CURLOPT_URL, $url);
333 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
334 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
335 curl_setopt($ch, CURLOPT_HEADER, true);
336 curl_setopt($ch, CURLOPT_NOBODY, true);
337 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
338 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
341 $curl_info = @curl_getinfo($ch);
342 $http_code = $curl_info['http_code'];
345 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
347 return $http_code == 200;
351 * Set the hostname for this process
353 * @param string $host The hostname
355 private function setHost($host)
357 if (!empty($this->host)) {
361 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
365 $lockpath = $this->config->get('jabber', 'lockpath');
366 if (is_null($lockpath)) {
367 $this->writeLog(LOG_INFO, 'No lockpath defined.');
371 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
372 if (PidFile::isRunningProcess($file)) {
373 if (PidFile::killProcess($file)) {
374 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
376 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
381 // Now it is safe to create the pid file
382 PidFile::create($file);
383 if (!file_exists($file)) {
384 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
389 * write data to the syslog
391 * @param integer $loglevel The syslog loglevel
392 * @param string $sMessage The syslog message
394 private function writeLog($loglevel, $sMessage)
396 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
399 syslog($loglevel, $sMessage);
403 * destroy the class, close the syslog connection.
405 public function __destruct()
407 $this->writeLog(LOG_NOTICE, 'stop');