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 $aLength = unpack('n', $iHeader);
77 $iLength = $aLength['1'];
81 $this->writeLog(LOG_ERR, 'we got no data, quitting');
86 $sData = fgets(STDIN, $iLength + 1);
87 $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);
88 $aCommand = explode(':', $sData);
89 if (is_array($aCommand)) {
90 switch ($aCommand[0]) {
92 // Check the existance of a given username
93 $this->isUser($aCommand);
96 // Check if the givven password is correct
97 $this->auth($aCommand);
100 // We don't accept the setting of passwords here
101 $this->writeLog(LOG_NOTICE, 'setpass command disabled');
102 fwrite(STDOUT, pack('nn', 2, 0));
105 // We don't know the given command
106 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);
107 fwrite(STDOUT, pack('nn', 2, 0));
111 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);
112 fwrite(STDOUT, pack('nn', 2, 0));
118 * Check if the given username exists
120 * @param array $aCommand The command array
121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123 private function isUser(array $aCommand)
125 // Check if there is a username
126 if (!isset($aCommand[1])) {
127 $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');
128 fwrite(STDOUT, pack('nn', 2, 0));
132 // We only allow one process per hostname. So we set a lock file
133 // Problem: We get the firstname after the first auth - not before
134 $this->setHost($aCommand[2]);
136 // Now we check if the given user is valid
137 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
139 // Does the hostname match? So we try directly
140 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
141 $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);
142 $found = DBA::exists('user', ['nickname' => $sUser]);
147 // If the hostnames doesn't match or there is some failure, we try to check remotely
149 $found = $this->checkUser($aCommand[2], $aCommand[1], true);
154 $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);
155 fwrite(STDOUT, pack('nn', 2, 1));
157 // The user isn't okay
158 $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);
159 fwrite(STDOUT, pack('nn', 2, 0));
164 * Check remote user existance via HTTP(S)
166 * @param string $host The hostname
167 * @param string $user Username
168 * @param boolean $ssl Should the check be done via SSL?
170 * @return boolean Was the user found?
171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
173 private function checkUser($host, $user, $ssl)
175 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);
177 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;
179 $curlResult = Network::curl($url);
181 if (!$curlResult->isSuccess()) {
185 if ($curlResult->getReturnCode() != 200) {
189 $json = @json_decode($curlResult->getBody());
190 if (!is_object($json)) {
194 return $json->nick == $user;
198 * Authenticate the given user and password
200 * @param array $aCommand The command array
201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203 private function auth(array $aCommand)
205 // check user authentication
206 if (sizeof($aCommand) != 4) {
207 $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');
208 fwrite(STDOUT, pack('nn', 2, 0));
212 // We only allow one process per hostname. So we set a lock file
213 // Problem: We get the firstname after the first auth - not before
214 $this->setHost($aCommand[2]);
216 // We now check if the password match
217 $sUser = str_replace(['%20', '(a)'], [' ', '@'], $aCommand[1]);
219 // Does the hostname match? So we try directly
220 if (DI::baseUrl()->getHostname() == $aCommand[2]) {
221 $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);
223 $aUser = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'], ['nickname' => $sUser]);
224 if (DBA::isResult($aUser)) {
225 $uid = $aUser['uid'];
226 $success = User::authenticate($aUser, $aCommand[3], true);
227 $Error = $success === false;
229 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);
234 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);
235 $sPassword = DI::pConfig()->get($uid, 'xmpp', 'password', null, true);
236 $Error = ($aCommand[3] != $sPassword);
242 // If the hostnames doesn't match or there is some failure, we try to check remotely
244 $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);
248 $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);
249 fwrite(STDOUT, pack('nn', 2, 0));
251 $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);
252 fwrite(STDOUT, pack('nn', 2, 1));
257 * Check remote credentials via HTTP(S)
259 * @param string $host The hostname
260 * @param string $user Username
261 * @param string $password Password
262 * @param boolean $ssl Should the check be done via SSL?
264 * @return boolean Are the credentials okay?
266 private function checkCredentials($host, $user, $password, $ssl)
268 $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host);
270 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true';
273 curl_setopt($ch, CURLOPT_URL, $url);
274 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
275 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
276 curl_setopt($ch, CURLOPT_HEADER, true);
277 curl_setopt($ch, CURLOPT_NOBODY, true);
278 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
279 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);
282 $curl_info = @curl_getinfo($ch);
283 $http_code = $curl_info['http_code'];
286 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);
288 return $http_code == 200;
292 * Set the hostname for this process
294 * @param string $host The hostname
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 private function setHost($host)
299 if (!empty($this->host)) {
303 $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host);
307 $lockpath = DI::config()->get('jabber', 'lockpath');
308 if (is_null($lockpath)) {
309 $this->writeLog(LOG_INFO, 'No lockpath defined.');
313 $file = $lockpath . DIRECTORY_SEPARATOR . $host;
314 if (PidFile::isRunningProcess($file)) {
315 if (PidFile::killProcess($file)) {
316 $this->writeLog(LOG_INFO, 'Old process was successfully killed');
318 $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process.");
323 // Now it is safe to create the pid file
324 PidFile::create($file);
325 if (!file_exists($file)) {
326 $this->writeLog(LOG_WARNING, 'Logfile ' . $file . " couldn't be created.");
331 * write data to the syslog
333 * @param integer $loglevel The syslog loglevel
334 * @param string $sMessage The syslog message
336 private function writeLog($loglevel, $sMessage)
338 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
341 syslog($loglevel, $sMessage);
345 * destroy the class, close the syslog connection.
347 public function __destruct()
349 $this->writeLog(LOG_NOTICE, 'stop');