Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
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.

337 lines
9.2KB

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