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;
38 if (sizeof($_SERVER["argv"]) == 0)
41 $directory = dirname($_SERVER["argv"][0]);
43 if (substr($directory, 0, 1) != "/")
44 $directory = $_SERVER["PWD"]."/".$directory;
46 $directory = realpath($directory."/..");
49 require_once("boot.php");
54 $a = new App(dirname(__DIR__));
57 @include(".htconfig.php");
58 require_once("include/dba.php");
59 dba::connect($db_host, $db_user, $db_pass, $db_data);
60 unset($db_host, $db_user, $db_pass, $db_data);
62 $oAuth = new exAuth();
68 * @brief Create the class and do the authentification studd
70 * @param boolean $bDebug Debug mode
72 public function __construct() {
74 $this->bDebug = (int)Config::get('jabber', 'debug');
77 openlog('auth_ejabberd', LOG_PID, LOG_USER);
79 $this->writeLog(LOG_NOTICE, "start");
81 // We are connected to the SQL server.
83 // Quit if the database connection went down
84 if (!dba::connected()) {
85 $this->writeLog(LOG_ERR, "the database connection went down");
89 $iHeader = fgets(STDIN, 3);
90 $aLength = unpack("n", $iHeader);
91 $iLength = $aLength["1"];
95 $this->writeLog(LOG_ERR, "we got no data, quitting");
100 $sData = fgets(STDIN, $iLength + 1);
101 $this->writeLog(LOG_DEBUG, "received data: ". $sData);
102 $aCommand = explode(":", $sData);
103 if (is_array($aCommand)) {
104 switch ($aCommand[0]) {
106 // Check the existance of a given username
107 $this->isuser($aCommand);
110 // Check if the givven password is correct
111 $this->auth($aCommand);
114 // We don't accept the setting of passwords here
115 $this->writeLog(LOG_NOTICE, "setpass command disabled");
116 fwrite(STDOUT, pack("nn", 2, 0));
119 // We don't know the given command
120 $this->writeLog(LOG_NOTICE, "unknown command ". $aCommand[0]);
121 fwrite(STDOUT, pack("nn", 2, 0));
125 $this->writeLog(LOG_NOTICE, "invalid command string ".$sData);
126 fwrite(STDOUT, pack("nn", 2, 0));
132 * @brief Check if the given username exists
134 * @param array $aCommand The command array
136 private function isuser($aCommand) {
139 // Check if there is a username
140 if (!isset($aCommand[1])) {
141 $this->writeLog(LOG_NOTICE, "invalid isuser command, no username given");
142 fwrite(STDOUT, pack("nn", 2, 0));
146 // Now we check if the given user is valid
147 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
149 // Does the hostname match? So we try directly
150 if ($a->get_hostname() == $aCommand[2]) {
151 $this->writeLog(LOG_INFO, "internal user check for ". $sUser."@".$aCommand[2]);
152 $sQuery = "SELECT `uid` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
153 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
155 $found = dbm::is_result($r);
160 // If the hostnames doesn't match or there is some failure, we try to check remotely
162 $found = $this->check_user($aCommand[2], $aCommand[1], true);
167 $this->writeLog(LOG_NOTICE, "valid user: ". $sUser);
168 fwrite(STDOUT, pack("nn", 2, 1));
170 // The user isn't okay
171 $this->writeLog(LOG_WARNING, "invalid user: ". $sUser);
172 fwrite(STDOUT, pack("nn", 2, 0));
177 * @brief Check remote user existance via HTTP(S)
179 * @param string $host The hostname
180 * @param string $user Username
181 * @param boolean $ssl Should the check be done via SSL?
183 * @return boolean Was the user found?
185 private function check_user($host, $user, $ssl) {
187 $this->writeLog(LOG_INFO, "external user check for ".$user."@".$host);
189 $url = ($ssl ? "https":"http")."://".$host."/noscrape/".$user;
191 $data = z_fetch_url($url);
193 if (!is_array($data))
196 if ($data["return_code"] != "200")
199 $json = @json_decode($data["body"]);
200 if (!is_object($json))
203 return($json->nick == $user);
207 * @brief Authenticate the givven user and password
209 * @param array $aCommand The command array
211 private function auth($aCommand) {
214 // check user authentication
215 if (sizeof($aCommand) != 4) {
216 $this->writeLog(LOG_NOTICE, "invalid auth command, data missing");
217 fwrite(STDOUT, pack("nn", 2, 0));
221 // We now check if the password match
222 $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
224 // Does the hostname match? So we try directly
225 if ($a->get_hostname() == $aCommand[2]) {
226 $this->writeLog(LOG_INFO, "internal auth for ".$sUser."@".$aCommand[2]);
228 $sQuery = "SELECT `uid`, `password` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
229 $this->writeLog(LOG_DEBUG, "using query ". $sQuery);
230 if ($oResult = q($sQuery)) {
231 $uid = $oResult[0]["uid"];
232 $Error = ($oResult[0]["password"] != hash('whirlpool',$aCommand[3]));
234 $this->writeLog(LOG_WARNING, "invalid query: ". $sQuery);
239 $oConfig = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = 'xmpp' AND `k`='password' LIMIT 1;", intval($uid));
240 $this->writeLog(LOG_INFO, "check against alternate password for ".$sUser."@".$aCommand[2]);
241 $Error = ($aCommand[3] != $oConfig[0]["v"]);
247 // If the hostnames doesn't match or there is some failure, we try to check remotely
249 $Error = !$this->check_credentials($aCommand[2], $aCommand[1], $aCommand[3], true);
253 $this->writeLog(LOG_WARNING, "authentification failed for user ".$sUser."@". $aCommand[2]);
254 fwrite(STDOUT, pack("nn", 2, 0));
256 $this->writeLog(LOG_NOTICE, "authentificated user ".$sUser."@".$aCommand[2]);
257 fwrite(STDOUT, pack("nn", 2, 1));
262 * @brief Check remote credentials via HTTP(S)
264 * @param string $host The hostname
265 * @param string $user Username
266 * @param string $password Password
267 * @param boolean $ssl Should the check be done via SSL?
269 * @return boolean Are the credentials okay?
271 private function check_credentials($host, $user, $password, $ssl) {
272 $url = ($ssl ? "https":"http")."://".$host."/api/account/verify_credentials.json";
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);
283 $header = curl_exec($ch);
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 write data to the syslog
296 * @param integer $loglevel The syslog loglevel
297 * @param string $sMessage The syslog message
299 private function writeLog($loglevel, $sMessage) {
300 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {
303 syslog($loglevel, $sMessage);
307 * @brief destroy the class, close the syslog connection.
309 public function __destruct() {
310 $this->writeLog(LOG_NOTICE, "stop");