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.

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