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.

315 lines
8.7KB

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