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;
37 use Friendica\Database\DBA;
39 use Friendica\Model\User;
50 public function __construct()
52 $this->bDebug = (int) DI::config()->get('jabber', 'debug');
54 openlog('auth_ejabberd', LOG_PID, LOG_USER);
56 $this->writeLog(LOG_NOTICE, 'start');
60 * Standard input reading function, executes the auth with the provided
64 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
66 public function readStdin()
68 while (!feof(STDIN)) {
69 // Quit if the database connection went down
70 if (!DBA::connected()) {
71 $this->writeLog(LOG_ERR, 'the database connection went down');
75 $iHeader = fgets(STDIN, 3);
76 if (empty($iHeader)) {
77 $this->writeLog(LOG_ERR, 'empty stdin');
81 $aLength = unpack('n', $iHeader);
82 $iLength = $aLength['1'];
86 $this->writeLog(LOG_ERR, 'we got no data, quitting');
91 $sData = fgets(STDIN, $iLength + 1);
92 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
93 $aCommand = explode(':', $sData);
94 if (is_array($aCommand)) {
95 switch ($aCommand[0]) {
97 // Check the existance of a given username
98 $this->isUser($aCommand);
101 // Check if the givven password is correct
102 $this->auth($aCommand);
105 // We don't accept the setting of passwords here
106 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
107 fwrite(STDOUT, pack('nn', 2, 0));
110 // We don't know the given command
111 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
112 fwrite(STDOUT, pack('nn', 2, 0));
116 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
117 fwrite(STDOUT, pack('nn', 2, 0));
123 * Check if the given username exists
125 * @param array $aCommand The command array
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 private function isUser(array $aCommand)
130 // Check if there is a username
131 if (!isset($aCommand[1])) {
132 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
133 fwrite(STDOUT, pack('nn', 2, 0));
137 // We only allow one process per hostname. So we set a lock file
138 // Problem: We get the firstname after the first auth - not before
139 $this->setHost($aCommand[2]);
141 // Now we check if the given user is valid
142 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
144 // Does the hostname match? So we try directly
145 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
146 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
147 $found = DBA::exists('user', ['nickname' => $sUser]);
152 // If the hostnames doesn't match or there is some failure, we try to check remotely
154 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
159 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
160 fwrite(STDOUT, pack('nn', 2, 1));
162 // The user isn't okay
163 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
164 fwrite(STDOUT, pack('nn', 2, 0));
169 * Check remote user existance via HTTP(S)
171 * @param string $host The hostname
172 * @param string $user Username
173 * @param boolean $ssl Should the check be done via SSL?
175 * @return boolean Was the user found?
176 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
178 private function checkUser($host, $user, $ssl)
180 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
182 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
184 $curlResult = Network::curl($url);
186 if (!$curlResult->isSuccess()) {
190 if ($curlResult->getReturnCode() != 200) {
194 $json = @json_decode($curlResult->getBody());
195 if (!is_object($json)) {
199 return $json->nick == $user;
203 * Authenticate the given user and password
205 * @param array $aCommand The command array
206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208 private function auth(array $aCommand)
210 // check user authentication
211 if (sizeof($aCommand) != 4) {
212 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
213 fwrite(STDOUT, pack('nn', 2, 0));
217 // We only allow one process per hostname. So we set a lock file
218 // Problem: We get the firstname after the first auth - not before
219 $this->setHost($aCommand[2]);
221 // We now check if the password match
222 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
224 // Does the hostname match? So we try directly
225 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
226 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
228 $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
229 if (DBA::isResult($aUser)) {
230 $uid = $aUser['uid'];
231 $success = User::authenticate($aUser, $aCommand[3], true);
232 $Error = $success === false;
234 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
239 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
240 $sPassword = DI::pConfig()->get($uid, 'xmpp', 'password', null, true);
241 $Error = ($aCommand[3] != $sPassword);
247 // If the hostnames doesn't match or there is some failure, we try to check remotely
249 $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);
253 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
254 fwrite(STDOUT, pack('nn', 2, 0));
256 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
257 fwrite(STDOUT, pack('nn', 2, 1));
262 * Check remote credentials via HTTP(S)
264 * @param string $host The hostname
265 * @param string $user Username
266 * @param string $password Password
267 * @param boolean $ssl Should the check be done via SSL?
269 * @return boolean Are the credentials okay?
271 private function checkCredentials($host, $user, $password, $ssl)
273 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
275 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
278 curl_setopt($ch, CURLOPT_URL, $url);
279 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
280 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
281 curl_setopt($ch, CURLOPT_HEADER, true);
282 curl_setopt($ch, CURLOPT_NOBODY, true);
283 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
284 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
287 $curl_info = @curl_getinfo($ch);
288 $http_code = $curl_info['http_code'];
291 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
293 return $http_code == 200;
297 * Set the hostname for this process
299 * @param string $host The hostname
300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302 private function setHost($host)
304 if (!empty($this->host)) {
308 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
312 $lockpath = DI::config()->get('jabber', 'lockpath');
313 if (is_null($lockpath)) {
314 $this->writeLog(LOG_INFO, 'No lockpath defined.');
318 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
319 if (PidFile::isRunningProcess($file)) {
320 if (PidFile::killProcess($file)) {
321 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
323 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
328 // Now it is safe to create the pid file
329 PidFile::create($file);
330 if (!file_exists($file)) {
331 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
336 * write data to the syslog
338 * @param integer $loglevel The syslog loglevel
339 * @param string $sMessage The syslog message
341 private function writeLog($loglevel, $sMessage)
343 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
346 syslog($loglevel, $sMessage);
350 * destroy the class, close the syslog connection.
352 public function __destruct()
354 $this->writeLog(LOG_NOTICE, 'stop');