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