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/include/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/include/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/include/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)"
36 use Friendica\Core\Config;
37 use Friendica\Database\DBM;
39 if (sizeof($_SERVER["argv"]) == 0)
42 $directory = dirname($_SERVER["argv"][0]);
44 if (substr($directory, 0, 1) != "/")
45 $directory = $_SERVER["PWD"]."/".$directory;
47 $directory = realpath($directory."/..");
50 require_once("boot.php");
55 $a = new App(dirname(__DIR__));
58 @include(".htconfig.php");
59 require_once("include/dba.php");
60 dba::connect($db_host, $db_user, $db_pass, $db_data);
61 unset($db_host, $db_user, $db_pass, $db_data);
63 $oAuth = new exAuth();
69 * @brief Create the class and do the authentification studd
71 * @param boolean $bDebug Debug mode
73 public function __construct() {
75 $this->bDebug = (int)Config::get('jabber', 'debug');
78 openlog('auth_ejabberd', LOG_PID, LOG_USER);
80 $this->writeLog(LOG_NOTICE, "start");
82 // We are connected to the SQL server.
83 while (!feof(STDIN)) {
84 // Quit if the database connection went down
85 if (!dba::connected()) {
86 $this->writeLog(LOG_ERR, "the database connection went down");
90 $iHeader = fgets(STDIN, 3);
91 $aLength = unpack("n", $iHeader);
92 $iLength = $aLength["1"];
96 $this->writeLog(LOG_ERR, "we got no data, quitting");
101 $sData = fgets(STDIN, $iLength + 1);
102 $this->writeLog(LOG_DEBUG, "received data: ". $sData);
103 $aCommand = explode(":", $sData);
104 if (is_array($aCommand)) {
105 switch ($aCommand[0]) {
107 // Check the existance of a given username
108 $this->isuser($aCommand);
111 // Check if the givven password is correct
112 $this->auth($aCommand);
115 // We don't accept the setting of passwords here
116 $this->writeLog(LOG_NOTICE, "setpass command disabled");
117 fwrite(STDOUT, pack("nn", 2, 0));
120 // We don't know the given command
121 $this->writeLog(LOG_NOTICE, "unknown command ". $aCommand[0]);
122 fwrite(STDOUT, pack("nn", 2, 0));
126 $this->writeLog(LOG_NOTICE, "invalid command string ".$sData);
127 fwrite(STDOUT, pack("nn", 2, 0));
133 * @brief Check if the given username exists
135 * @param array $aCommand The command array
137 private function isuser($aCommand) {
140 // Check if there is a username
141 if (!isset($aCommand[1])) {
142 $this->writeLog(LOG_NOTICE, "invalid isuser command, no username given");
143 fwrite(STDOUT, pack("nn", 2, 0));
147 // Now we check if the given user is valid
148 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
150 // Does the hostname match? So we try directly
151 if ($a->get_hostname() == $aCommand[2]) {
152 $this->writeLog(LOG_INFO, "internal user check for ". $sUser."@".$aCommand[2]);
153 $sQuery = "SELECT `uid` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
154 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
156 $found = DBM::is_result($r);
161 // If the hostnames doesn't match or there is some failure, we try to check remotely
163 $found = $this->check_user($aCommand[2], $aCommand[1], true);
168 $this->writeLog(LOG_NOTICE, "valid user: ". $sUser);
169 fwrite(STDOUT, pack("nn", 2, 1));
171 // The user isn't okay
172 $this->writeLog(LOG_WARNING, "invalid user: ". $sUser);
173 fwrite(STDOUT, pack("nn", 2, 0));
178 * @brief Check remote user existance via HTTP(S)
180 * @param string $host The hostname
181 * @param string $user Username
182 * @param boolean $ssl Should the check be done via SSL?
184 * @return boolean Was the user found?
186 private function check_user($host, $user, $ssl) {
188 $this->writeLog(LOG_INFO, "external user check for ".$user."@".$host);
190 $url = ($ssl ? "https":"http")."://".$host."/noscrape/".$user;
192 $data = z_fetch_url($url);
194 if (!is_array($data))
197 if ($data["return_code"] != "200")
200 $json = @json_decode($data["body"]);
201 if (!is_object($json))
204 return($json->nick == $user);
208 * @brief Authenticate the givven user and password
210 * @param array $aCommand The command array
212 private function auth($aCommand) {
215 // check user authentication
216 if (sizeof($aCommand) != 4) {
217 $this->writeLog(LOG_NOTICE, "invalid auth command, data missing");
218 fwrite(STDOUT, pack("nn", 2, 0));
222 // We now check if the password match
223 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
225 // Does the hostname match? So we try directly
226 if ($a->get_hostname() == $aCommand[2]) {
227 $this->writeLog(LOG_INFO, "internal auth for ".$sUser."@".$aCommand[2]);
229 $sQuery = "SELECT `uid`, `password` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
230 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
231 if ($oResult = q($sQuery)) {
232 $uid = $oResult[0]["uid"];
233 $Error = ($oResult[0]["password"] != hash('whirlpool',$aCommand[3]));
235 $this->writeLog(LOG_WARNING, "invalid query: ". $sQuery);
240 $oConfig = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = 'xmpp' AND `k`='password' LIMIT 1;", intval($uid));
241 $this->writeLog(LOG_INFO, "check against alternate password for ".$sUser."@".$aCommand[2]);
242 $Error = ($aCommand[3] != $oConfig[0]["v"]);
248 // If the hostnames doesn't match or there is some failure, we try to check remotely
250 $Error = !$this->check_credentials($aCommand[2], $aCommand[1], $aCommand[3], true);
254 $this->writeLog(LOG_WARNING, "authentification failed for user ".$sUser."@". $aCommand[2]);
255 fwrite(STDOUT, pack("nn", 2, 0));
257 $this->writeLog(LOG_NOTICE, "authentificated user ".$sUser."@".$aCommand[2]);
258 fwrite(STDOUT, pack("nn", 2, 1));
263 * @brief Check remote credentials via HTTP(S)
265 * @param string $host The hostname
266 * @param string $user Username
267 * @param string $password Password
268 * @param boolean $ssl Should the check be done via SSL?
270 * @return boolean Are the credentials okay?
272 private function check_credentials($host, $user, $password, $ssl) {
273 $url = ($ssl ? "https":"http")."://".$host."/api/account/verify_credentials.json";
276 curl_setopt($ch, CURLOPT_URL, $url);
277 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
278 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
279 curl_setopt($ch, CURLOPT_HEADER, true);
280 curl_setopt($ch, CURLOPT_NOBODY, true);
281 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
282 curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$password);
284 $header = curl_exec($ch);
285 $curl_info = @curl_getinfo($ch);
286 $http_code = $curl_info["http_code"];
289 $this->writeLog(LOG_INFO, "external auth for ".$user."@".$host." returned ".$http_code);
291 return ($http_code == 200);
295 * @brief write data to the syslog
297 * @param integer $loglevel The syslog loglevel
298 * @param string $sMessage The syslog message
300 private function writeLog($loglevel, $sMessage) {
301 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
304 syslog($loglevel, $sMessage);
308 * @brief destroy the class, close the syslog connection.
310 public function __destruct() {
311 $this->writeLog(LOG_NOTICE, "stop");