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.

312 lines
8.6KB

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