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\HTTPException;
61 use Friendica\Util\PidFile;
73 * @var IManageConfigValues
77 * @var IManagePersonalConfigValues
90 * @param App\Mode $appMode
91 * @param IManageConfigValues $config
92 * @param IManagePersonalConfigValues $pConfig
93 * @param Database $dba
94 * @param App\BaseURL $baseURL
98 public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
100 $this->appMode = $appMode;
101 $this->config = $config;
102 $this->pConfig = $pConfig;
104 $this->baseURL = $baseURL;
106 $this->bDebug = (int)$config->get('jabber', 'debug');
108 openlog('auth_ejabberd', LOG_PID, LOG_USER);
110 $this->writeLog(LOG_NOTICE, 'start');
114 * Standard input reading function, executes the auth with the provided
117 * @throws HTTPException\InternalServerErrorException
119 public function readStdin()
121 if (!$this->appMode->isNormal()) {
122 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
126 while (!feof(STDIN)) {
127 // Quit if the database connection went down
128 if (!$this->dba->isConnected()) {
129 $this->writeLog(LOG_ERR, 'the database connection went down');
133 $iHeader = fgets(STDIN, 3);
134 if (empty($iHeader)) {
135 $this->writeLog(LOG_ERR, 'empty stdin');
139 $aLength = unpack('n', $iHeader);
140 $iLength = $aLength['1'];
142 // No data? Then quit
144 $this->writeLog(LOG_ERR, 'we got no data, quitting');
149 $sData = fgets(STDIN, $iLength + 1);
150 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
151 $aCommand = explode(':', $sData);
152 if (is_array($aCommand)) {
153 switch ($aCommand[0]) {
155 // Check the existance of a given username
156 $this->isUser($aCommand);
159 // Check if the givven password is correct
160 $this->auth($aCommand);
163 // We don't accept the setting of passwords here
164 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
165 fwrite(STDOUT, pack('nn', 2, 0));
168 // We don't know the given command
169 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
170 fwrite(STDOUT, pack('nn', 2, 0));
174 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
175 fwrite(STDOUT, pack('nn', 2, 0));
181 * Check if the given username exists
183 * @param array $aCommand The command array
184 * @throws HTTPException\InternalServerErrorException
186 private function isUser(array $aCommand)
188 // Check if there is a username
189 if (!isset($aCommand[1])) {
190 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
191 fwrite(STDOUT, pack('nn', 2, 0));
195 // We only allow one process per hostname. So we set a lock file
196 // Problem: We get the firstname after the first auth - not before
197 $this->setHost($aCommand[2]);
199 // Now we check if the given user is valid
200 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
202 // Does the hostname match? So we try directly
203 if ($this->baseURL->getHostname() == $aCommand[2]) {
204 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
205 $found = $this->dba->exists('user', ['nickname' => $sUser]);
210 // If the hostnames doesn't match or there is some failure, we try to check remotely
212 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
217 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
218 fwrite(STDOUT, pack('nn', 2, 1));
220 // The user isn't okay
221 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
222 fwrite(STDOUT, pack('nn', 2, 0));
227 * Check remote user existance via HTTP(S)
229 * @param string $host The hostname
230 * @param string $user Username
231 * @param boolean $ssl Should the check be done via SSL?
233 * @return boolean Was the user found?
234 * @throws HTTPException\InternalServerErrorException
236 private function checkUser($host, $user, $ssl)
238 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
240 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
242 $curlResult = DI::httpClient()->get($url);
244 if (!$curlResult->isSuccess()) {
248 if ($curlResult->getReturnCode() != 200) {
252 $json = @json_decode($curlResult->getBody());
253 if (!is_object($json)) {
257 return $json->nick == $user;
261 * Authenticate the given user and password
263 * @param array $aCommand The command array
266 private function auth(array $aCommand)
268 // check user authentication
269 if (sizeof($aCommand) != 4) {
270 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
271 fwrite(STDOUT, pack('nn', 2, 0));
275 // We only allow one process per hostname. So we set a lock file
276 // Problem: We get the firstname after the first auth - not before
277 $this->setHost($aCommand[2]);
279 // We now check if the password match
280 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
283 // Does the hostname match? So we try directly
284 if ($this->baseURL->getHostname() == $aCommand[2]) {
286 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
287 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
288 } catch (HTTPException\ForbiddenException $ex) {
289 // User exists, authentication failed
290 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
291 $aUser = User::getByNickname($sUser, ['uid']);
292 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
293 $Error = ($aCommand[3] != $sPassword);
294 } catch (\Throwable $ex) {
295 // User doesn't exist and any other failure case
296 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
303 // If the hostnames doesn't match or there is some failure, we try to check remotely
304 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
305 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
306 fwrite(STDOUT, pack('nn', 2, 0));
308 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
309 fwrite(STDOUT, pack('nn', 2, 1));
314 * Check remote credentials via HTTP(S)
316 * @param string $host The hostname
317 * @param string $user Username
318 * @param string $password Password
319 * @param boolean $ssl Should the check be done via SSL?
321 * @return boolean Are the credentials okay?
323 private function checkCredentials($host, $user, $password, $ssl)
325 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
327 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
330 curl_setopt($ch, CURLOPT_URL, $url);
331 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
332 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
333 curl_setopt($ch, CURLOPT_HEADER, true);
334 curl_setopt($ch, CURLOPT_NOBODY, true);
335 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
336 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
339 $curl_info = @curl_getinfo($ch);
340 $http_code = $curl_info['http_code'];
343 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
345 return $http_code == 200;
349 * Set the hostname for this process
351 * @param string $host The hostname
353 private function setHost($host)
355 if (!empty($this->host)) {
359 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
363 $lockpath = $this->config->get('jabber', 'lockpath');
364 if (is_null($lockpath)) {
365 $this->writeLog(LOG_INFO, 'No lockpath defined.');
369 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
370 if (PidFile::isRunningProcess($file)) {
371 if (PidFile::killProcess($file)) {
372 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
374 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
379 // Now it is safe to create the pid file
380 PidFile::create($file);
381 if (!file_exists($file)) {
382 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
387 * write data to the syslog
389 * @param integer $loglevel The syslog loglevel
390 * @param string $sMessage The syslog message
392 private function writeLog($loglevel, $sMessage)
394 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
397 syslog($loglevel, $sMessage);
401 * destroy the class, close the syslog connection.
403 public function __destruct()
405 $this->writeLog(LOG_NOTICE, 'stop');