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/scripts/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/scripts/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/script/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."/..");
51 require_once "boot.php";
52 require_once "include/dba.php";
54 $a = new App(dirname(__DIR__));
56 @include(".htconfig.php");
57 dba::connect($db_host, $db_user, $db_pass, $db_data);
58 unset($db_host, $db_user, $db_pass, $db_data);
60 $oAuth = new exAuth();
66 * @brief Create the class and do the authentification studd
68 * @param boolean $bDebug Debug mode
70 public function __construct() {
72 $this->bDebug = (int)Config::get('jabber', 'debug');
75 openlog('auth_ejabberd', LOG_PID, LOG_USER);
77 $this->writeLog(LOG_NOTICE, "start");
79 // We are connected to the SQL server.
80 while (!feof(STDIN)) {
81 // Quit if the database connection went down
82 if (!dba::connected()) {
83 $this->writeLog(LOG_ERR, "the database connection went down");
87 $iHeader = fgets(STDIN, 3);
88 $aLength = unpack("n", $iHeader);
89 $iLength = $aLength["1"];
93 $this->writeLog(LOG_ERR, "we got no data, quitting");
98 $sData = fgets(STDIN, $iLength + 1);
99 $this->writeLog(LOG_DEBUG, "received data: ". $sData);
100 $aCommand = explode(":", $sData);
101 if (is_array($aCommand)) {
102 switch ($aCommand[0]) {
104 // Check the existance of a given username
105 $this->isuser($aCommand);
108 // Check if the givven password is correct
109 $this->auth($aCommand);
112 // We don't accept the setting of passwords here
113 $this->writeLog(LOG_NOTICE, "setpass command disabled");
114 fwrite(STDOUT, pack("nn", 2, 0));
117 // We don't know the given command
118 $this->writeLog(LOG_NOTICE, "unknown command ". $aCommand[0]);
119 fwrite(STDOUT, pack("nn", 2, 0));
123 $this->writeLog(LOG_NOTICE, "invalid command string ".$sData);
124 fwrite(STDOUT, pack("nn", 2, 0));
130 * @brief Check if the given username exists
132 * @param array $aCommand The command array
134 private function isuser($aCommand) {
137 // Check if there is a username
138 if (!isset($aCommand[1])) {
139 $this->writeLog(LOG_NOTICE, "invalid isuser command, no username given");
140 fwrite(STDOUT, pack("nn", 2, 0));
144 // Now we check if the given user is valid
145 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
147 // Does the hostname match? So we try directly
148 if ($a->get_hostname() == $aCommand[2]) {
149 $this->writeLog(LOG_INFO, "internal user check for ". $sUser."@".$aCommand[2]);
150 $sQuery = "SELECT `uid` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
151 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
153 $found = DBM::is_result($r);
158 // If the hostnames doesn't match or there is some failure, we try to check remotely
160 $found = $this->check_user($aCommand[2], $aCommand[1], true);
165 $this->writeLog(LOG_NOTICE, "valid user: ". $sUser);
166 fwrite(STDOUT, pack("nn", 2, 1));
168 // The user isn't okay
169 $this->writeLog(LOG_WARNING, "invalid user: ". $sUser);
170 fwrite(STDOUT, pack("nn", 2, 0));
175 * @brief Check remote user existance via HTTP(S)
177 * @param string $host The hostname
178 * @param string $user Username
179 * @param boolean $ssl Should the check be done via SSL?
181 * @return boolean Was the user found?
183 private function check_user($host, $user, $ssl) {
185 $this->writeLog(LOG_INFO, "external user check for ".$user."@".$host);
187 $url = ($ssl ? "https":"http")."://".$host."/noscrape/".$user;
189 $data = z_fetch_url($url);
191 if (!is_array($data))
194 if ($data["return_code"] != "200")
197 $json = @json_decode($data["body"]);
198 if (!is_object($json))
201 return($json->nick == $user);
205 * @brief Authenticate the givven user and password
207 * @param array $aCommand The command array
209 private function auth($aCommand) {
212 // check user authentication
213 if (sizeof($aCommand) != 4) {
214 $this->writeLog(LOG_NOTICE, "invalid auth command, data missing");
215 fwrite(STDOUT, pack("nn", 2, 0));
219 // We now check if the password match
220 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
222 // Does the hostname match? So we try directly
223 if ($a->get_hostname() == $aCommand[2]) {
224 $this->writeLog(LOG_INFO, "internal auth for ".$sUser."@".$aCommand[2]);
226 $sQuery = "SELECT `uid`, `password` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
227 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
228 if ($oResult = q($sQuery)) {
229 $uid = $oResult[0]["uid"];
230 $Error = ($oResult[0]["password"] != hash('whirlpool',$aCommand[3]));
232 $this->writeLog(LOG_WARNING, "invalid query: ". $sQuery);
237 $oConfig = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = 'xmpp' AND `k`='password' LIMIT 1;", intval($uid));
238 $this->writeLog(LOG_INFO, "check against alternate password for ".$sUser."@".$aCommand[2]);
239 $Error = ($aCommand[3] != $oConfig[0]["v"]);
245 // If the hostnames doesn't match or there is some failure, we try to check remotely
247 $Error = !$this->check_credentials($aCommand[2], $aCommand[1], $aCommand[3], true);
251 $this->writeLog(LOG_WARNING, "authentification failed for user ".$sUser."@". $aCommand[2]);
252 fwrite(STDOUT, pack("nn", 2, 0));
254 $this->writeLog(LOG_NOTICE, "authentificated user ".$sUser."@".$aCommand[2]);
255 fwrite(STDOUT, pack("nn", 2, 1));
260 * @brief Check remote credentials via HTTP(S)
262 * @param string $host The hostname
263 * @param string $user Username
264 * @param string $password Password
265 * @param boolean $ssl Should the check be done via SSL?
267 * @return boolean Are the credentials okay?
269 private function check_credentials($host, $user, $password, $ssl) {
270 $url = ($ssl ? "https":"http")."://".$host."/api/account/verify_credentials.json";
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);
281 $header = curl_exec($ch);
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 * @brief write data to the syslog
294 * @param integer $loglevel The syslog loglevel
295 * @param string $sMessage The syslog message
297 private function writeLog($loglevel, $sMessage) {
298 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
301 syslog($loglevel, $sMessage);
305 * @brief destroy the class, close the syslog connection.
307 public function __destruct() {
308 $this->writeLog(LOG_NOTICE, "stop");