3 * @copyright Copyright (C) 2010-2023, 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\HTTPException;
62 use Friendica\Util\PidFile;
74 * @var IManageConfigValues
78 * @var IManagePersonalConfigValues
91 * @param App\Mode $appMode
92 * @param IManageConfigValues $config
93 * @param IManagePersonalConfigValues $pConfig
94 * @param Database $dba
95 * @param App\BaseURL $baseURL
99 public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
101 $this->appMode = $appMode;
102 $this->config = $config;
103 $this->pConfig = $pConfig;
105 $this->baseURL = $baseURL;
107 $this->bDebug = (int)$config->get('jabber', 'debug');
109 openlog('auth_ejabberd', LOG_PID, LOG_USER);
111 $this->writeLog(LOG_NOTICE, 'start');
115 * Standard input reading function, executes the auth with the provided
118 * @throws HTTPException\InternalServerErrorException
120 public function readStdin()
122 if (!$this->appMode->isNormal()) {
123 $this->writeLog(LOG_ERR, 'The node isn\'t ready.');
127 while (!feof(STDIN)) {
128 // Quit if the database connection went down
129 if (!$this->dba->isConnected()) {
130 $this->writeLog(LOG_ERR, 'the database connection went down');
134 $iHeader = fgets(STDIN, 3);
135 if (empty($iHeader)) {
136 $this->writeLog(LOG_ERR, 'empty stdin');
140 $aLength = unpack('n', $iHeader);
141 $iLength = $aLength['1'];
143 // No data? Then quit
145 $this->writeLog(LOG_ERR, 'we got no data, quitting');
150 $sData = fgets(STDIN, $iLength + 1);
151 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
152 $aCommand = explode(':', $sData);
153 if (is_array($aCommand)) {
154 switch ($aCommand[0]) {
156 // Check the existance of a given username
157 $this->isUser($aCommand);
160 // Check if the givven password is correct
161 $this->auth($aCommand);
164 // We don't accept the setting of passwords here
165 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
166 fwrite(STDOUT, pack('nn', 2, 0));
169 // We don't know the given command
170 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
171 fwrite(STDOUT, pack('nn', 2, 0));
175 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
176 fwrite(STDOUT, pack('nn', 2, 0));
182 * Check if the given username exists
184 * @param array $aCommand The command array
185 * @throws HTTPException\InternalServerErrorException
187 private function isUser(array $aCommand)
189 // Check if there is a username
190 if (!isset($aCommand[1])) {
191 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
192 fwrite(STDOUT, pack('nn', 2, 0));
196 // We only allow one process per hostname. So we set a lock file
197 // Problem: We get the firstname after the first auth - not before
198 $this->setHost($aCommand[2]);
200 // Now we check if the given user is valid
201 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
203 // Does the hostname match? So we try directly
204 if ($this->baseURL->getHostname() == $aCommand[2]) {
205 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
206 $found = $this->dba->exists('user', ['nickname' => $sUser]);
211 // If the hostnames doesn't match or there is some failure, we try to check remotely
213 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
218 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
219 fwrite(STDOUT, pack('nn', 2, 1));
221 // The user isn't okay
222 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
223 fwrite(STDOUT, pack('nn', 2, 0));
228 * Check remote user existance via HTTP(S)
230 * @param string $host The hostname
231 * @param string $user Username
232 * @param boolean $ssl Should the check be done via SSL?
234 * @return boolean Was the user found?
235 * @throws HTTPException\InternalServerErrorException
237 private function checkUser($host, $user, $ssl)
239 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
241 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
243 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
245 if (!$curlResult->isSuccess()) {
249 if ($curlResult->getReturnCode() != 200) {
253 $json = @json_decode($curlResult->getBody());
254 if (!is_object($json)) {
258 return $json->nick == $user;
262 * Authenticate the given user and password
264 * @param array $aCommand The command array
267 private function auth(array $aCommand)
269 // check user authentication
270 if (sizeof($aCommand) != 4) {
271 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
272 fwrite(STDOUT, pack('nn', 2, 0));
276 // We only allow one process per hostname. So we set a lock file
277 // Problem: We get the firstname after the first auth - not before
278 $this->setHost($aCommand[2]);
280 // We now check if the password match
281 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
284 // Does the hostname match? So we try directly
285 if ($this->baseURL->getHostname() == $aCommand[2]) {
287 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
288 User::getIdFromPasswordAuthentication($sUser, $aCommand[3], true);
289 } catch (HTTPException\ForbiddenException $ex) {
290 // User exists, authentication failed
291 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
292 $aUser = User::getByNickname($sUser, ['uid']);
293 $sPassword = $this->pConfig->get($aUser['uid'], 'xmpp', 'password', null, true);
294 $Error = ($aCommand[3] != $sPassword);
295 } catch (\Throwable $ex) {
296 // User doesn't exist and any other failure case
297 $this->writeLog(LOG_WARNING, $ex->getMessage() . ': ' . $sUser);
304 // If the hostnames doesn't match or there is some failure, we try to check remotely
305 if ($Error && !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true)) {
306 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
307 fwrite(STDOUT, pack('nn', 2, 0));
309 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
310 fwrite(STDOUT, pack('nn', 2, 1));
315 * Check remote credentials via HTTP(S)
317 * @param string $host The hostname
318 * @param string $user Username
319 * @param string $password Password
320 * @param boolean $ssl Should the check be done via SSL?
322 * @return boolean Are the credentials okay?
324 private function checkCredentials($host, $user, $password, $ssl)
326 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
328 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
331 curl_setopt($ch, CURLOPT_URL, $url);
332 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
333 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
334 curl_setopt($ch, CURLOPT_HEADER, true);
335 curl_setopt($ch, CURLOPT_NOBODY, true);
336 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
337 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
340 $curl_info = @curl_getinfo($ch);
341 $http_code = $curl_info['http_code'];
344 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
346 return $http_code == 200;
350 * Set the hostname for this process
352 * @param string $host The hostname
354 private function setHost($host)
356 if (!empty($this->host)) {
360 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
364 $lockpath = $this->config->get('jabber', 'lockpath');
365 if (is_null($lockpath)) {
366 $this->writeLog(LOG_INFO, 'No lockpath defined.');
370 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
371 if (PidFile::isRunningProcess($file)) {
372 if (PidFile::killProcess($file)) {
373 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
375 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
380 // Now it is safe to create the pid file
381 PidFile::create($file);
382 if (!file_exists($file)) {
383 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
388 * write data to the syslog
390 * @param integer $loglevel The syslog loglevel
391 * @param string $sMessage The syslog message
393 private function writeLog($loglevel, $sMessage)
395 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
398 syslog($loglevel, $sMessage);
402 * destroy the class, close the syslog connection.
404 public function __destruct()
406 $this->writeLog(LOG_NOTICE, 'stop');