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.

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