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;
41 use Friendica\Model\User;
49 * @brief Create the class
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
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 public function readStdin()
70 while (!feof(STDIN)) {
71 // Quit if the database connection went down
72 if (!DBA::connected()) {
73 $this->writeLog(LOG_ERR, 'the database connection went down');
77 $iHeader = fgets(STDIN, 3);
78 $aLength = unpack('n', $iHeader);
79 $iLength = $aLength['1'];
83 $this->writeLog(LOG_ERR, 'we got no data, quitting');
88 $sData = fgets(STDIN, $iLength + 1);
89 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
90 $aCommand = explode(':', $sData);
91 if (is_array($aCommand)) {
92 switch ($aCommand[0]) {
94 // Check the existance of a given username
95 $this->isUser($aCommand);
98 // Check if the givven password is correct
99 $this->auth($aCommand);
102 // We don't accept the setting of passwords here
103 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
104 fwrite(STDOUT, pack('nn', 2, 0));
107 // We don't know the given command
108 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
109 fwrite(STDOUT, pack('nn', 2, 0));
113 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
114 fwrite(STDOUT, pack('nn', 2, 0));
120 * @brief Check if the given username exists
122 * @param array $aCommand The command array
123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125 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 (DI::baseUrl()->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?
173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
175 private function checkUser($host, $user, $ssl)
177 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
179 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
181 $curlResult = Network::curl($url);
183 if (!$curlResult->isSuccess()) {
187 if ($curlResult->getReturnCode() != 200) {
191 $json = @json_decode($curlResult->getBody());
192 if (!is_object($json)) {
196 return $json->nick == $user;
200 * @brief Authenticate the given user and password
202 * @param array $aCommand The command array
203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
205 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 (DI::baseUrl()->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], true);
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
297 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
299 private function setHost($host)
301 if (!empty($this->host)) {
305 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
309 $lockpath = Config::get('jabber', 'lockpath');
310 if (is_null($lockpath)) {
311 $this->writeLog(LOG_INFO, 'No lockpath defined.');
315 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
316 if (PidFile::isRunningProcess($file)) {
317 if (PidFile::killProcess($file)) {
318 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
320 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
325 // Now it is safe to create the pid file
326 PidFile::create($file);
327 if (!file_exists($file)) {
328 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
333 * @brief write data to the syslog
335 * @param integer $loglevel The syslog loglevel
336 * @param string $sMessage The syslog message
338 private function writeLog($loglevel, $sMessage)
340 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
343 syslog($loglevel, $sMessage);
347 * @brief destroy the class, close the syslog connection.
349 public function __destruct()
351 $this->writeLog(LOG_NOTICE, 'stop');