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