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\Core\Config;
38 use Friendica\Core\PConfig;
39 use Friendica\Database\DBA;
40 use Friendica\Model\User;
48 * @brief Create the class
50 * @param boolean $bDebug Debug mode
52 public function __construct()
54 $this->bDebug = (int) Config::get('jabber', 'debug');
56 openlog('auth_ejabberd', LOG_PID, LOG_USER);
58 $this->writeLog(LOG_NOTICE, 'start');
62 * @brief Standard input reading function, executes the auth with the provided
67 public function readStdin()
69 while (!feof(STDIN)) {
70 // Quit if the database connection went down
71 if (!DBA::connected()) {
72 $this->writeLog(LOG_ERR, 'the database connection went down');
76 $iHeader = fgets(STDIN, 3);
77 $aLength = unpack('n', $iHeader);
78 $iLength = $aLength['1'];
82 $this->writeLog(LOG_ERR, 'we got no data, quitting');
87 $sData = fgets(STDIN, $iLength + 1);
88 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
89 $aCommand = explode(':', $sData);
90 if (is_array($aCommand)) {
91 switch ($aCommand[0]) {
93 // Check the existance of a given username
94 $this->isUser($aCommand);
97 // Check if the givven password is correct
98 $this->auth($aCommand);
101 // We don't accept the setting of passwords here
102 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
103 fwrite(STDOUT, pack('nn', 2, 0));
106 // We don't know the given command
107 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
108 fwrite(STDOUT, pack('nn', 2, 0));
112 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
113 fwrite(STDOUT, pack('nn', 2, 0));
119 * @brief Check if the given username exists
121 * @param array $aCommand The command array
123 private function isUser(array $aCommand)
127 // Check if there is a username
128 if (!isset($aCommand[1])) {
129 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
130 fwrite(STDOUT, pack('nn', 2, 0));
134 // We only allow one process per hostname. So we set a lock file
135 // Problem: We get the firstname after the first auth - not before
136 $this->setHost($aCommand[2]);
138 // Now we check if the given user is valid
139 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
141 // Does the hostname match? So we try directly
142 if ($a->getHostName() == $aCommand[2]) {
143 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
144 $found = DBA::exists('user', ['nickname' => $sUser]);
149 // If the hostnames doesn't match or there is some failure, we try to check remotely
151 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
156 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
157 fwrite(STDOUT, pack('nn', 2, 1));
159 // The user isn't okay
160 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
161 fwrite(STDOUT, pack('nn', 2, 0));
166 * @brief Check remote user existance via HTTP(S)
168 * @param string $host The hostname
169 * @param string $user Username
170 * @param boolean $ssl Should the check be done via SSL?
172 * @return boolean Was the user found?
174 private function checkUser($host, $user, $ssl)
176 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
178 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
180 $curlResult = Network::curl($url);
182 if (!$curlResult->isSuccess()) {
186 if ($curlResult->getReturnCode() != 200) {
190 $json = @json_decode($curlResult->getBody());
191 if (!is_object($json)) {
195 return $json->nick == $user;
199 * @brief Authenticate the given user and password
201 * @param array $aCommand The command array
203 private function auth(array $aCommand)
207 // check user authentication
208 if (sizeof($aCommand) != 4) {
209 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
210 fwrite(STDOUT, pack('nn', 2, 0));
214 // We only allow one process per hostname. So we set a lock file
215 // Problem: We get the firstname after the first auth - not before
216 $this->setHost($aCommand[2]);
218 // We now check if the password match
219 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
221 // Does the hostname match? So we try directly
222 if ($a->getHostName() == $aCommand[2]) {
223 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
225 $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
226 if (DBA::isResult($aUser)) {
227 $uid = $aUser['uid'];
228 $success = User::authenticate($aUser, $aCommand[3]);
229 $Error = $success === false;
231 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
236 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
237 $sPassword = PConfig::get($uid, 'xmpp', 'password', null, true);
238 $Error = ($aCommand[3] != $sPassword);
244 // If the hostnames doesn't match or there is some failure, we try to check remotely
246 $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);
250 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
251 fwrite(STDOUT, pack('nn', 2, 0));
253 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
254 fwrite(STDOUT, pack('nn', 2, 1));
259 * @brief Check remote credentials via HTTP(S)
261 * @param string $host The hostname
262 * @param string $user Username
263 * @param string $password Password
264 * @param boolean $ssl Should the check be done via SSL?
266 * @return boolean Are the credentials okay?
268 private function checkCredentials($host, $user, $password, $ssl)
270 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
272 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
275 curl_setopt($ch, CURLOPT_URL, $url);
276 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
277 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
278 curl_setopt($ch, CURLOPT_HEADER, true);
279 curl_setopt($ch, CURLOPT_NOBODY, true);
280 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
281 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
284 $curl_info = @curl_getinfo($ch);
285 $http_code = $curl_info['http_code'];
288 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
290 return $http_code == 200;
294 * @brief Set the hostname for this process
296 * @param string $host The hostname
298 private function setHost($host)
300 if (!empty($this->host)) {
304 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
308 $lockpath = Config::get('jabber', 'lockpath');
309 if (is_null($lockpath)) {
310 $this->writeLog(LOG_INFO, 'No lockpath defined.');
314 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
315 if (PidFile::isRunningProcess($file)) {
316 if (PidFile::killProcess($file)) {
317 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
319 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
324 // Now it is safe to create the pid file
325 PidFile::create($file);
326 if (!file_exists($file)) {
327 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
332 * @brief write data to the syslog
334 * @param integer $loglevel The syslog loglevel
335 * @param string $sMessage The syslog message
337 private function writeLog($loglevel, $sMessage)
339 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
342 syslog($loglevel, $sMessage);
346 * @brief destroy the class, close the syslog connection.
348 public function __destruct()
350 $this->writeLog(LOG_NOTICE, 'stop');