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