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