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