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)"
35 if (sizeof($_SERVER["argv"]) == 0)
38 $directory = dirname($_SERVER["argv"][0]);
40 if (substr($directory, 0, 1) != "/")
41 $directory = $_SERVER["PWD"]."/".$directory;
43 $directory = realpath($directory."/..");
46 require_once("boot.php");
54 @include(".htconfig.php");
55 require_once("include/dba.php");
56 $db = new dba($db_host, $db_user, $db_pass, $db_data);
57 unset($db_host, $db_user, $db_pass, $db_data);
60 // the logfile to which to write, should be writeable by the user which is running the server
61 $sLogFile = get_config('jabber','logfile');
63 // set true to debug if needed
64 $bDebug = get_config('jabber','debug');
66 $oAuth = new exAuth($sLogFile, $bDebug);
75 * @brief Create the class and do the authentification studd
77 * @param string $sLogFile The logfile name
78 * @param boolean $bDebug Debug mode
80 public function __construct($sLogFile, $bDebug) {
84 $this->sLogFile = $sLogFile;
85 $this->bDebug = $bDebug;
87 // Open the logfile if the logfile name is defined
88 if ($this->sLogFile != '')
89 $this->rLogFile = fopen($this->sLogFile, "a") or die("Error opening log file: ". $this->sLogFile);
91 $this->writeLog("[exAuth] start");
93 // We are connected to the SQL server and are having a log file.
95 // Quit if the database connection went down
96 if (!$db->connected()) {
97 $this->writeDebugLog("[debug] the database connection went down");
101 $iHeader = fgets(STDIN, 3);
102 $aLength = unpack("n", $iHeader);
103 $iLength = $aLength["1"];
105 // No data? Then quit
107 $this->writeDebugLog("[debug] we got no data");
112 $sData = fgets(STDIN, $iLength + 1);
113 $this->writeDebugLog("[debug] received data: ". $sData);
114 $aCommand = explode(":", $sData);
115 if (is_array($aCommand)) {
116 switch ($aCommand[0]) {
118 // Check the existance of a given username
119 $this->isuser($aCommand);
122 // Check if the givven password is correct
123 $this->auth($aCommand);
126 // We don't accept the setting of passwords here
127 $this->writeLog("[exAuth] setpass command disabled");
128 fwrite(STDOUT, pack("nn", 2, 0));
131 // We don't know the given command
132 $this->writeLog("[exAuth] unknown command ". $aCommand[0]);
133 fwrite(STDOUT, pack("nn", 2, 0));
137 $this->writeDebugLog("[debug] invalid command string");
138 fwrite(STDOUT, pack("nn", 2, 0));
144 * @brief Check if the given username exists
146 * @param string $aCommand The command string
148 private function isuser($aCommand) {
151 // Check if there is a username
152 if (!isset($aCommand[1])) {
153 $this->writeLog("[exAuth] invalid isuser command, no username given");
154 fwrite(STDOUT, pack("nn", 2, 0));
156 // Now we check if the given user is valid
157 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
158 $this->writeDebugLog("[debug] checking isuser for ". $sUser."@".$aCommand[2]);
160 // If the hostnames doesn't match, we try to check remotely
161 if ($a->get_hostname() != $aCommand[2])
162 $found = $this->check_user($aCommand[2], $aCommand[1], true);
164 $sQuery = "SELECT `uid` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
165 $this->writeDebugLog("[debug] using query ". $sQuery);
167 $found = dbm::is_result($r);
171 $this->writeLog("[exAuth] valid user: ". $sUser);
172 fwrite(STDOUT, pack("nn", 2, 1));
174 // The user isn't okay
175 $this->writeLog("[exAuth] invalid user: ". $sUser);
176 fwrite(STDOUT, pack("nn", 2, 0));
182 * @brief Check remote user existance via HTTP(S)
184 * @param string $host The hostname
185 * @param string $user Username
186 * @param boolean $ssl Should the check be done via SSL?
188 * @return boolean Was the user found?
190 private function check_user($host, $user, $ssl) {
192 $url = ($ssl ? "https":"http")."://".$host."/noscrape/".$user;
194 $data = z_fetch_url($url);
196 if (!is_array($data))
199 if ($data["return_code"] != "200")
202 $json = @json_decode($data["body"]);
203 if (!is_object($json))
206 return($json->nick == $user);
210 * @brief Authenticate the givven user and password
212 * @param string $aCommand The command string
214 private function auth($aCommand) {
217 // check user authentication
218 if (sizeof($aCommand) != 4) {
219 $this->writeLog("[exAuth] invalid auth command, data missing");
220 fwrite(STDOUT, pack("nn", 2, 0));
222 // We now check if the password match
223 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
224 $this->writeDebugLog("[debug] doing auth for ".$sUser."@".$aCommand[2]);
226 // If the hostnames doesn't match, we try to authenticate remotely
227 if ($a->get_hostname() != $aCommand[2])
228 $Error = !$this->check_credentials($aCommand[2], $aCommand[1], $aCommand[3], true);
230 $sQuery = "SELECT `uid`, `password` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
231 $this->writeDebugLog("[debug] using query ". $sQuery);
232 if ($oResult = q($sQuery)) {
233 $uid = $oResult[0]["uid"];
234 $Error = ($oResult[0]["password"] != hash('whirlpool',$aCommand[3]));
236 $this->writeLog("[MySQL] invalid query: ". $sQuery);
241 $oConfig = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = 'xmpp' AND `k`='password' LIMIT 1;", intval($uid));
242 $this->writeLog("[exAuth] got password ".$oConfig[0]["v"]);
243 $Error = ($aCommand[3] != $oConfig[0]["v"]);
247 $this->writeLog("[exAuth] authentification failed for user ".$sUser."@". $aCommand[2]);
248 fwrite(STDOUT, pack("nn", 2, 0));
250 $this->writeLog("[exAuth] authentificated user ".$sUser."@".$aCommand[2]);
251 fwrite(STDOUT, pack("nn", 2, 1));
257 * @brief 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 check_credentials($host, $user, $password, $ssl) {
267 $this->writeDebugLog("[debug] check credentials for user ".$user." on ".$host);
269 $url = ($ssl ? "https":"http")."://".$host."/api/account/verify_credentials.json";
272 curl_setopt($ch, CURLOPT_URL, $url);
273 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
274 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
275 curl_setopt($ch, CURLOPT_HEADER, true);
276 curl_setopt($ch, CURLOPT_NOBODY, true);
277 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
278 curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$password);
280 $header = curl_exec($ch);
281 $curl_info = @curl_getinfo($ch);
282 $http_code = $curl_info["http_code"];
285 $this->writeDebugLog("[debug] got HTTP code ".$http_code);
287 return ($http_code == 200);
291 * @brief write data to the logfile
293 * @param string $sMessage The logfile message
295 private function writeLog($sMessage) {
296 if (is_resource($this->rLogFile))
297 fwrite($this->rLogFile, date("r")." ".$sMessage."\n");
301 * @brief write debug data to the logfile
303 * @param string $sMessage The logfile message
305 private function writeDebugLog($sMessage) {
307 $this->writeLog($sMessage);
311 * @brief destroy the class
313 public function __destruct() {
314 // close the log file
315 $this->writeLog("[exAuth] stop");
317 if (is_resource($this->rLogFile))
318 fclose($this->rLogFile);