Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth_ejabberd.php 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #!/usr/bin/php
  2. <?php
  3. /*
  4. * ejabberd extauth script for the integration with friendica
  5. *
  6. * Originally written for joomla by Dalibor Karlovic <dado@krizevci.info>
  7. * modified for Friendica by Michael Vogel <icarus@dabo.de>
  8. * published under GPL
  9. *
  10. * Latest version of the original script for joomla is available at:
  11. * http://87.230.15.86/~dado/ejabberd/joomla-login
  12. *
  13. * Installation:
  14. *
  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
  17. *
  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
  20. *
  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"}.
  24. *
  25. * - Restart your ejabberd service, you should be able to login with your friendica auth info
  26. *
  27. * Other hints:
  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)"
  32. *
  33. */
  34. if (sizeof($_SERVER["argv"]) == 0)
  35. die();
  36. $directory = dirname($_SERVER["argv"][0]);
  37. if (substr($directory, 0, 1) != "/")
  38. $directory = $_SERVER["PWD"]."/".$directory;
  39. $directory = realpath($directory."/..");
  40. chdir($directory);
  41. require_once("boot.php");
  42. global $a, $db;
  43. if (is_null($a))
  44. $a = new App;
  45. if (is_null($db)) {
  46. @include(".htconfig.php");
  47. require_once("include/dba.php");
  48. $db = new dba($db_host, $db_user, $db_pass, $db_data);
  49. unset($db_host, $db_user, $db_pass, $db_data);
  50. };
  51. // the logfile to which to write, should be writeable by the user which is running the server
  52. $sLogFile = get_config('jabber','logfile');
  53. // set true to debug if needed
  54. $bDebug = get_config('jabber','debug');
  55. $oAuth = new exAuth($sLogFile, $bDebug);
  56. class exAuth {
  57. private $sLogFile;
  58. private $bDebug;
  59. private $rLogFile;
  60. /**
  61. * @brief Create the class and do the authentification studd
  62. *
  63. * @param string $sLogFile The logfile name
  64. * @param boolean $bDebug Debug mode
  65. */
  66. public function __construct($sLogFile, $bDebug) {
  67. global $db;
  68. // setter
  69. $this->sLogFile = $sLogFile;
  70. $this->bDebug = $bDebug;
  71. // Open the logfile if the logfile name is defined
  72. if ($this->sLogFile != '')
  73. $this->rLogFile = fopen($this->sLogFile, "a") or die("Error opening log file: ". $this->sLogFile);
  74. $this->writeLog("[exAuth] start");
  75. // We are connected to the SQL server and are having a log file.
  76. do {
  77. // Quit if the database connection went down
  78. if (!$db->connected()) {
  79. $this->writeDebugLog("[debug] the database connection went down");
  80. return;
  81. }
  82. $iHeader = fgets(STDIN, 3);
  83. $aLength = unpack("n", $iHeader);
  84. $iLength = $aLength["1"];
  85. // No data? Then quit
  86. if ($iLength == 0) {
  87. $this->writeDebugLog("[debug] we got no data");
  88. return;
  89. }
  90. // Fetching the data
  91. $sData = fgets(STDIN, $iLength + 1);
  92. $this->writeDebugLog("[debug] received data: ". $sData);
  93. $aCommand = explode(":", $sData);
  94. if (is_array($aCommand)) {
  95. switch ($aCommand[0]) {
  96. case "isuser":
  97. // Check the existance of a given username
  98. $this->isuser($aCommand);
  99. break;
  100. case "auth":
  101. // Check if the givven password is correct
  102. $this->auth($aCommand);
  103. break;
  104. case "setpass":
  105. // We don't accept the setting of passwords here
  106. $this->writeLog("[exAuth] setpass command disabled");
  107. fwrite(STDOUT, pack("nn", 2, 0));
  108. break;
  109. default:
  110. // We don't know the given command
  111. $this->writeLog("[exAuth] unknown command ". $aCommand[0]);
  112. fwrite(STDOUT, pack("nn", 2, 0));
  113. break;
  114. }
  115. } else {
  116. $this->writeDebugLog("[debug] invalid command string");
  117. fwrite(STDOUT, pack("nn", 2, 0));
  118. }
  119. } while (true);
  120. }
  121. /**
  122. * @brief Check if the given username exists
  123. *
  124. * @param string $aCommand The command string
  125. */
  126. private function isuser($aCommand) {
  127. global $a;
  128. // Check if there is a username
  129. if (!isset($aCommand[1])) {
  130. $this->writeLog("[exAuth] invalid isuser command, no username given");
  131. fwrite(STDOUT, pack("nn", 2, 0));
  132. } else {
  133. // Now we check if the given user is valid
  134. $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
  135. $this->writeDebugLog("[debug] checking isuser for ". $sUser."@".$aCommand[2]);
  136. // If the hostnames doesn't match, we try to check remotely
  137. if ($a->get_hostname() != $aCommand[2])
  138. $found = $this->check_user($aCommand[2], $aCommand[1], true);
  139. else {
  140. $sQuery = "SELECT `uid` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
  141. $this->writeDebugLog("[debug] using query ". $sQuery);
  142. $r = q($sQuery);
  143. $found = dbm::is_result($r);
  144. }
  145. if ($found) {
  146. // The user is okay
  147. $this->writeLog("[exAuth] valid user: ". $sUser);
  148. fwrite(STDOUT, pack("nn", 2, 1));
  149. } else {
  150. // The user isn't okay
  151. $this->writeLog("[exAuth] invalid user: ". $sUser);
  152. fwrite(STDOUT, pack("nn", 2, 0));
  153. }
  154. }
  155. }
  156. /**
  157. * @brief Check remote user existance via HTTP(S)
  158. *
  159. * @param string $host The hostname
  160. * @param string $user Username
  161. * @param boolean $ssl Should the check be done via SSL?
  162. *
  163. * @return boolean Was the user found?
  164. */
  165. private function check_user($host, $user, $ssl) {
  166. $url = ($ssl ? "https":"http")."://".$host."/noscrape/".$user;
  167. $data = z_fetch_url($url);
  168. if (!is_array($data))
  169. return(false);
  170. if ($data["return_code"] != "200")
  171. return(false);
  172. $json = @json_decode($data["body"]);
  173. if (!is_object($json))
  174. return(false);
  175. return($json->nick == $user);
  176. }
  177. /**
  178. * @brief Authenticate the givven user and password
  179. *
  180. * @param string $aCommand The command string
  181. */
  182. private function auth($aCommand) {
  183. global $a;
  184. // check user authentication
  185. if (sizeof($aCommand) != 4) {
  186. $this->writeLog("[exAuth] invalid auth command, data missing");
  187. fwrite(STDOUT, pack("nn", 2, 0));
  188. } else {
  189. // We now check if the password match
  190. $sUser = str_replace(array("%20", "(a)"), array(" ", "@"), $aCommand[1]);
  191. $this->writeDebugLog("[debug] doing auth for ".$sUser."@".$aCommand[2]);
  192. // If the hostnames doesn't match, we try to authenticate remotely
  193. if ($a->get_hostname() != $aCommand[2])
  194. $Error = !$this->check_credentials($aCommand[2], $aCommand[1], $aCommand[3], true);
  195. else {
  196. $sQuery = "SELECT `uid`, `password` FROM `user` WHERE `nickname`='".dbesc($sUser)."'";
  197. $this->writeDebugLog("[debug] using query ". $sQuery);
  198. if ($oResult = q($sQuery)) {
  199. $uid = $oResult[0]["uid"];
  200. $Error = ($oResult[0]["password"] != hash('whirlpool',$aCommand[3]));
  201. } else {
  202. $this->writeLog("[MySQL] invalid query: ". $sQuery);
  203. $Error = true;
  204. $uid = -1;
  205. }
  206. if ($Error) {
  207. $oConfig = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = 'xmpp' AND `k`='password' LIMIT 1;", intval($uid));
  208. $this->writeLog("[exAuth] got password ".$oConfig[0]["v"]);
  209. $Error = ($aCommand[3] != $oConfig[0]["v"]);
  210. }
  211. }
  212. if ($Error) {
  213. $this->writeLog("[exAuth] authentification failed for user ".$sUser."@". $aCommand[2]);
  214. fwrite(STDOUT, pack("nn", 2, 0));
  215. } else {
  216. $this->writeLog("[exAuth] authentificated user ".$sUser."@".$aCommand[2]);
  217. fwrite(STDOUT, pack("nn", 2, 1));
  218. }
  219. }
  220. }
  221. /**
  222. * @brief Check remote credentials via HTTP(S)
  223. *
  224. * @param string $host The hostname
  225. * @param string $user Username
  226. * @param string $password Password
  227. * @param boolean $ssl Should the check be done via SSL?
  228. *
  229. * @return boolean Are the credentials okay?
  230. */
  231. private function check_credentials($host, $user, $password, $ssl) {
  232. $this->writeDebugLog("[debug] check credentials for user ".$user." on ".$host);
  233. $url = ($ssl ? "https":"http")."://".$host."/api/account/verify_credentials.json";
  234. $ch = curl_init();
  235. curl_setopt($ch, CURLOPT_URL, $url);
  236. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  237. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  238. curl_setopt($ch, CURLOPT_HEADER, true);
  239. curl_setopt($ch, CURLOPT_NOBODY, true);
  240. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  241. curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$password);
  242. $header = curl_exec($ch);
  243. $curl_info = @curl_getinfo($ch);
  244. $http_code = $curl_info["http_code"];
  245. curl_close($ch);
  246. $this->writeDebugLog("[debug] got HTTP code ".$http_code);
  247. return ($http_code == 200);
  248. }
  249. /**
  250. * @brief write data to the logfile
  251. *
  252. * @param string $sMessage The logfile message
  253. */
  254. private function writeLog($sMessage) {
  255. if (is_resource($this->rLogFile))
  256. fwrite($this->rLogFile, date("r")." ".$sMessage."\n");
  257. }
  258. /**
  259. * @brief write debug data to the logfile
  260. *
  261. * @param string $sMessage The logfile message
  262. */
  263. private function writeDebugLog($sMessage) {
  264. if ($this->bDebug)
  265. $this->writeLog($sMessage);
  266. }
  267. /**
  268. * @brief destroy the class
  269. */
  270. public function __destruct() {
  271. // close the log file
  272. $this->writeLog("[exAuth] stop");
  273. if (is_resource($this->rLogFile))
  274. fclose($this->rLogFile);
  275. }
  276. }
  277. ?>