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