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