Hubzilla core code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

362 lines
12 KiB

  1. <?php
  2. namespace Zotlabs\Zot;
  3. class Auth {
  4. protected $test;
  5. protected $test_results;
  6. protected $debug_msg;
  7. protected $address;
  8. protected $desturl;
  9. protected $sec;
  10. protected $version;
  11. protected $delegate;
  12. protected $success;
  13. protected $delegate_success;
  14. protected $remote;
  15. protected $remote_service_class;
  16. protected $remote_level;
  17. protected $remote_hub;
  18. protected $dnt;
  19. function __construct($req) {
  20. $this->test = ((array_key_exists('test',$req)) ? intval($req['test']) : 0);
  21. $this->test_results = array('success' => false);
  22. $this->debug_msg = '';
  23. $this->success = false;
  24. $this->address = $req['auth'];
  25. $this->desturl = $req['dest'];
  26. $this->sec = $req['sec'];
  27. $this->version = $req['version'];
  28. $this->delegate = $req['delegate'];
  29. $c = get_sys_channel();
  30. if(! $c) {
  31. logger('unable to obtain response (sys) channel');
  32. $this->Debug('no local channels found.');
  33. $this->Finalise();
  34. }
  35. if(strpbrk($this->sec,'.:')) {
  36. logger('illegal security context');
  37. $this->Debug('illegal security context.');
  38. $this->Finalise();
  39. }
  40. $x = $this->GetHublocs($this->address);
  41. if($x) {
  42. foreach($x as $xx) {
  43. if($this->Verify($c,$xx))
  44. break;
  45. }
  46. }
  47. /**
  48. * @FIXME we really want to save the return_url in the session before we
  49. * visit rmagic. This does however prevent a recursion if you visit
  50. * rmagic directly, as it would otherwise send you back here again.
  51. * But z_root() probably isn't where you really want to go.
  52. */
  53. if(strstr($this->desturl,z_root() . '/rmagic'))
  54. goaway(z_root());
  55. $this->Finalise();
  56. }
  57. function GetHublocs($address) {
  58. // Try and find a hubloc for the person attempting to auth.
  59. // Since we're matching by address, we have to return all entries
  60. // some of which may be from re-installed hubs; and we'll need to
  61. // try each sequentially to see if one can pass the test
  62. $x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash
  63. where hubloc_addr = '%s' order by hubloc_id desc",
  64. dbesc($address)
  65. );
  66. if(! $x) {
  67. // finger them if they can't be found.
  68. $j = Finger::run($address, null);
  69. if ($j['success']) {
  70. import_xchan($j);
  71. $x = q("select * from hubloc left join xchan on xchan_hash = hubloc_hash
  72. where hubloc_addr = '%s' order by hubloc_id desc",
  73. dbesc($address)
  74. );
  75. }
  76. }
  77. if(! $x) {
  78. logger('mod_zot: auth: unable to finger ' . $address);
  79. $this->Debug('no hubloc found for ' . $address . ' and probing failed.');
  80. $this->Finalise();
  81. }
  82. return $x;
  83. }
  84. function Verify($channel,$hubloc) {
  85. logger('auth request received from ' . $hubloc['hubloc_addr'] );
  86. $this->remote = remote_channel();
  87. $this->remote_service_class = '';
  88. $this->remote_level = 0;
  89. $this->remote_hub = $hubloc['hubloc_url'];
  90. $this->dnt = 0;
  91. if(! $this->sec) {
  92. logger('missing security context.');
  93. if($this->test)
  94. $this->Debug('missing security context.');
  95. return false;
  96. }
  97. // check credentials and access
  98. // If they are already authenticated and haven't changed credentials,
  99. // we can save an expensive network round trip and improve performance.
  100. // Also check that they are coming from the same site as they authenticated with originally.
  101. $already_authed = (((remote_channel()) && ($hubloc['hubloc_hash'] == remote_channel())
  102. && ($hubloc['hubloc_url'] === $_SESSION['remote_hub'])) ? true : false);
  103. if($this->delegate && $this->delegate !== $_SESSION['delegate_channel'])
  104. $already_authed = false;
  105. if($already_authed)
  106. return true;
  107. if(local_channel()) {
  108. // tell them to logout if they're logged in locally as anything but the target remote account
  109. // in which case just shut up because they don't need to be doing this at all.
  110. if (\App::$channel['channel_hash'] == $hubloc['xchan_hash']) {
  111. return true;
  112. }
  113. else {
  114. logger('already authenticated locally as somebody else.');
  115. notice( t('Remote authentication blocked. You are logged into this site locally. Please logout and retry.') . EOL);
  116. if($this->test) {
  117. $this->Debug('already logged in locally with a conflicting identity.');
  118. return false;
  119. }
  120. }
  121. return false;
  122. }
  123. // Auth packets MUST use ultra top-secret hush-hush mode - e.g. the entire packet is encrypted using the
  124. // site private key
  125. // The actual channel sending the packet ($c[0]) is not important, but this provides a
  126. // generic zot packet with a sender which can be verified
  127. $x = q("select site_crypto from site where site_url = '%s' limit 1",
  128. dbesc($hubloc['hubloc_url'])
  129. );
  130. $p = zot_build_packet($channel,$type = 'auth_check',
  131. array(array('guid' => $hubloc['hubloc_guid'],'guid_sig' => $hubloc['hubloc_guid_sig'])),
  132. $hubloc['hubloc_sitekey'], (($x) ? $x[0]['site_crypto'] : ''), $this->sec);
  133. $this->Debug('auth check packet created using sitekey ' . $hubloc['hubloc_sitekey']);
  134. $this->Debug('packet contents: ' . $p);
  135. $result = zot_zot($hubloc['hubloc_callback'],$p);
  136. if(! $result['success']) {
  137. logger('auth_check callback failed.');
  138. if($this->test)
  139. $this->Debug('auth check request to your site returned .' . print_r($result, true));
  140. return false;
  141. }
  142. $j = json_decode($result['body'], true);
  143. if(! $j) {
  144. logger('auth_check json data malformed.');
  145. if($this->test)
  146. $this->Debug('json malformed: ' . $result['body']);
  147. return false;
  148. }
  149. $this->Debug('auth check request returned ' . print_r($j, true));
  150. if(! $j['success'])
  151. return false;
  152. // legit response, but we do need to check that this wasn't answered by a man-in-middle
  153. if (! rsa_verify($this->sec . $hubloc['xchan_hash'],base64url_decode($j['confirm']),$hubloc['xchan_pubkey'])) {
  154. logger('final confirmation failed.');
  155. if($this->test)
  156. $this->Debug('final confirmation failed. ' . $sec . print_r($j,true) . print_r($hubloc,true));
  157. return false;
  158. }
  159. if (array_key_exists('service_class',$j))
  160. $this->remote_service_class = $j['service_class'];
  161. if (array_key_exists('level',$j))
  162. $this->remote_level = $j['level'];
  163. if (array_key_exists('DNT',$j))
  164. $this->dnt = $j['DNT'];
  165. // log them in
  166. if ($this->test) {
  167. // testing only - return the success result
  168. $this->test_results['success'] = true;
  169. $this->Debug('Authentication Success!');
  170. $this->Finalise();
  171. }
  172. $_SESSION['authenticated'] = 1;
  173. // check for delegation and if all is well, log them in locally with delegation restrictions
  174. $this->delegate_success = false;
  175. if($this->delegate) {
  176. $r = q("select * from channel left join xchan on channel_hash = xchan_hash where xchan_addr = '%s' limit 1",
  177. dbesc($this->delegate)
  178. );
  179. if ($r && intval($r[0]['channel_id'])) {
  180. $allowed = perm_is_allowed($r[0]['channel_id'],$hubloc['xchan_hash'],'delegate');
  181. if($allowed) {
  182. $_SESSION['delegate_channel'] = $r[0]['channel_id'];
  183. $_SESSION['delegate'] = $hubloc['xchan_hash'];
  184. $_SESSION['account_id'] = intval($r[0]['channel_account_id']);
  185. require_once('include/security.php');
  186. // this will set the local_channel authentication in the session
  187. change_channel($r[0]['channel_id']);
  188. $this->delegate_success = true;
  189. }
  190. }
  191. }
  192. if (! $this->delegate_success) {
  193. // normal visitor (remote_channel) login session credentials
  194. $_SESSION['visitor_id'] = $hubloc['xchan_hash'];
  195. $_SESSION['my_url'] = $hubloc['xchan_url'];
  196. $_SESSION['my_address'] = $this->address;
  197. $_SESSION['remote_service_class'] = $this->remote_service_class;
  198. $_SESSION['remote_level'] = $this->remote_level;
  199. $_SESSION['remote_hub'] = $this->remote_hub;
  200. $_SESSION['DNT'] = $this->dnt;
  201. }
  202. $arr = array('xchan' => $hubloc, 'url' => $this->desturl, 'session' => $_SESSION);
  203. call_hooks('magic_auth_success',$arr);
  204. \App::set_observer($hubloc);
  205. require_once('include/security.php');
  206. \App::set_groups(init_groups_visitor($_SESSION['visitor_id']));
  207. info(sprintf( t('Welcome %s. Remote authentication successful.'),$hubloc['xchan_name']));
  208. logger('mod_zot: auth success from ' . $hubloc['xchan_addr']);
  209. $this->success = true;
  210. return true;
  211. }
  212. function Debug($msg) {
  213. $this->debug_msg .= $msg . EOL;
  214. }
  215. function Finalise() {
  216. if($this->test) {
  217. $this->test_results['message'] = $this->debug_msg;
  218. json_return_and_die($this->test_results);
  219. }
  220. goaway($this->desturl);
  221. }
  222. }
  223. /**
  224. *
  225. * Magic Auth
  226. * ==========
  227. *
  228. * So-called "magic auth" takes place by a special exchange. On the site where the "channel to be authenticated" lives (e.g. $mysite),
  229. * a redirection is made via $mysite/magic to the zot endpoint of the remote site ($remotesite) with special GET parameters.
  230. *
  231. * The endpoint is typically https://$remotesite/post - or whatever was specified as the callback url in prior communications
  232. * (we will bootstrap an address and fetch a zot info packet if possible where no prior communications exist)
  233. *
  234. * Five GET parameters are supplied:
  235. * * auth => the urlencoded webbie (channel@host.domain) of the channel requesting access
  236. * * dest => the desired destination URL (urlencoded)
  237. * * sec => a random string which is also stored on $mysite for use during the verification phase.
  238. * * version => the zot revision
  239. * * delegate => optional urlencoded webbie of a local channel to invoke delegation rights for
  240. *
  241. * * test => (optional 1 or 0 - debugs the authentication exchange and returns a json response instead of redirecting the browser session)
  242. *
  243. * When this packet is received, an "auth-check" zot message is sent to $mysite.
  244. * (e.g. if $_GET['auth'] is foobar@podunk.edu, a zot packet is sent to the podunk.edu zot endpoint, which is typically /post)
  245. * If no information has been recorded about the requesting identity a zot information packet will be retrieved before
  246. * continuing.
  247. *
  248. * The sender of this packet is an arbitrary/random site channel. The recipients will be a single recipient corresponding
  249. * to the guid and guid_sig we have associated with the requesting auth identity
  250. *
  251. * \code{.json}
  252. * {
  253. * "type":"auth_check",
  254. * "sender":{
  255. * "guid":"kgVFf_...",
  256. * "guid_sig":"PT9-TApz...",
  257. * "url":"http:\/\/podunk.edu",
  258. * "url_sig":"T8Bp7j...",
  259. * "sitekey":"aMtgKTiirXrICP..."
  260. * },
  261. * "recipients":{
  262. * {
  263. * "guid":"ZHSqb...",
  264. * "guid_sig":"JsAAXi..."
  265. * }
  266. * }
  267. * "callback":"\/post",
  268. * "version":1,
  269. * "secret":"1eaa661",
  270. * "secret_sig":"eKV968b1..."
  271. * }
  272. * \endcode
  273. *
  274. * auth_check messages MUST use encapsulated encryption. This message is sent to the origination site, which checks the 'secret' to see
  275. * if it is the same as the 'sec' which it passed originally. It also checks the secret_sig which is the secret signed by the
  276. * destination channel's private key and base64url encoded. If everything checks out, a json packet is returned:
  277. *
  278. * \code{.json}
  279. * {
  280. * "success":1,
  281. * "confirm":"q0Ysovd1u...",
  282. * "service_class":(optional)
  283. * "level":(optional)
  284. * "DNT": (optional do-not-track - 1 or 0)
  285. * }
  286. * \endcode
  287. *
  288. * 'confirm' in this case is the base64url encoded RSA signature of the concatenation of 'secret' with the
  289. * base64url encoded whirlpool hash of the requestor's guid and guid_sig; signed with the source channel private key.
  290. * This prevents a man-in-the-middle from inserting a rogue success packet. Upon receipt and successful
  291. * verification of this packet, the destination site will redirect to the original destination URL and indicate a successful remote login.
  292. * Service_class can be used by cooperating sites to provide different access rights based on account rights and subscription plans. It is
  293. * a string whose contents are not defined by protocol. Example: "basic" or "gold".
  294. *
  295. * @param[in,out] \App &$a
  296. */