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.

auth_ejabberd.php 8.7KB

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