apiauthaction.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Base class for API actions that require authentication
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category API
  23. * @package StatusNet
  24. * @author Adrian Lang <mail@adrianlang.de>
  25. * @author Brenda Wallace <shiny@cpan.org>
  26. * @author Craig Andrews <candrews@integralblue.com>
  27. * @author Dan Moore <dan@moore.cx>
  28. * @author Evan Prodromou <evan@status.net>
  29. * @author mEDI <medi@milaro.net>
  30. * @author Sarven Capadisli <csarven@status.net>
  31. * @author Zach Copley <zach@status.net>
  32. * @copyright 2009-2010 StatusNet, Inc.
  33. * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
  34. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  35. * @link http://status.net/
  36. */
  37. /* External API usage documentation. Please update when you change how this method works. */
  38. /*! @page authentication Authentication
  39. StatusNet supports HTTP Basic Authentication and OAuth for API calls.
  40. @warning Currently, users who have created accounts without setting a
  41. password via OpenID, Facebook Connect, etc., cannot use the API until
  42. they set a password with their account settings panel.
  43. @section HTTP Basic Auth
  44. @section OAuth
  45. */
  46. if (!defined('GNUSOCIAL')) { exit(1); }
  47. /**
  48. * Actions extending this class will require auth
  49. *
  50. * @category API
  51. * @package StatusNet
  52. * @author Zach Copley <zach@status.net>
  53. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  54. * @link http://status.net/
  55. */
  56. class ApiAuthAction extends ApiAction
  57. {
  58. var $auth_user_nickname = null;
  59. var $auth_user_password = null;
  60. /**
  61. * Take arguments for running, looks for an OAuth request,
  62. * and outputs basic auth header if needed
  63. *
  64. * @param array $args $_REQUEST args
  65. *
  66. * @return boolean success flag
  67. *
  68. */
  69. protected function prepare(array $args=array())
  70. {
  71. parent::prepare($args);
  72. // NOTE: $this->scoped and $this->auth_user has to get set in
  73. // prepare(), not handle(), as subclasses use them in prepares.
  74. // Allow regular login session
  75. if (common_logged_in()) {
  76. $this->scoped = Profile::current();
  77. $this->auth_user = $this->scoped->getUser();
  78. if (!$this->auth_user->hasRight(Right::API)) {
  79. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  80. throw new AuthorizationException(_('Not allowed to use API.'));
  81. }
  82. // Let's run this in the same way as if we've just authenticated the user (basic/oauth auth)
  83. Event::handle('EndSetApiUser', array($this->auth_user));
  84. $this->access = self::READ_WRITE;
  85. } else {
  86. $oauthReq = $this->getOAuthRequest();
  87. if ($oauthReq instanceof OAuthRequest) {
  88. $this->checkOAuthRequest($oauthReq);
  89. } else {
  90. // If not using OAuth, check if there is a basic auth
  91. // and require it if the current action requires it.
  92. $this->checkBasicAuthUser($this->requiresAuth());
  93. }
  94. // NOTE: Make sure we're scoped properly based on the auths!
  95. if (isset($this->auth_user) && $this->auth_user instanceof User) {
  96. $this->scoped = $this->auth_user->getProfile();
  97. } else {
  98. $this->scoped = null;
  99. }
  100. }
  101. // legacy user transferral
  102. // TODO: remove when sure no extended classes need it
  103. $this->user = $this->auth_user;
  104. // Reject API calls with the wrong access level
  105. if ($this->isReadOnly($args) == false) {
  106. if ($this->access != self::READ_WRITE) {
  107. // TRANS: Client error 401.
  108. $msg = _('API resource requires read-write access, ' .
  109. 'but you only have read access.');
  110. $this->clientError($msg, 401);
  111. }
  112. }
  113. return true;
  114. }
  115. /**
  116. * Determine whether the request is an OAuth request.
  117. * This is to avoid doign any unnecessary DB lookups.
  118. *
  119. * @return mixed the OAuthRequest or false
  120. */
  121. function getOAuthRequest()
  122. {
  123. ApiOAuthAction::cleanRequest();
  124. $req = OAuthRequest::from_request();
  125. $consumer = $req->get_parameter('oauth_consumer_key');
  126. $accessToken = $req->get_parameter('oauth_token');
  127. // XXX: Is it good enough to assume it's not meant to be an
  128. // OAuth request if there is no consumer or token? --Z
  129. if (empty($consumer) || empty($accessToken)) {
  130. return false;
  131. }
  132. return $req;
  133. }
  134. /**
  135. * Verifies the OAuth request signature, sets the auth user
  136. * and access type (read-only or read-write)
  137. *
  138. * @param OAuthRequest $request the OAuth Request
  139. *
  140. * @return nothing
  141. */
  142. function checkOAuthRequest($request)
  143. {
  144. $datastore = new ApiGNUsocialOAuthDataStore();
  145. $server = new OAuthServer($datastore);
  146. $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
  147. $server->add_signature_method($hmac_method);
  148. try {
  149. $server->verify_request($request);
  150. $consumer = $request->get_parameter('oauth_consumer_key');
  151. $access_token = $request->get_parameter('oauth_token');
  152. $app = Oauth_application::getByConsumerKey($consumer);
  153. if (empty($app)) {
  154. common_log(
  155. LOG_WARNING,
  156. 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
  157. $consumer
  158. );
  159. // TRANS: OAuth exception thrown when no application is found for a given consumer key.
  160. throw new OAuthException(_('No application for that consumer key.'));
  161. }
  162. // set the source attr
  163. if ($app->name != 'anonymous') {
  164. $this->source = $app->name;
  165. }
  166. $appUser = Oauth_application_user::getKV('token', $access_token);
  167. if (!empty($appUser)) {
  168. // If access_type == 0 we have either a request token
  169. // or a bad / revoked access token
  170. if ($appUser->access_type != 0) {
  171. // Set the access level for the api call
  172. $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
  173. ? self::READ_WRITE : self::READ_ONLY;
  174. // Set the auth user
  175. if (Event::handle('StartSetApiUser', array(&$user))) {
  176. $user = User::getKV('id', $appUser->profile_id);
  177. }
  178. if ($user instanceof User) {
  179. if (!$user->hasRight(Right::API)) {
  180. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  181. throw new AuthorizationException(_('Not allowed to use API.'));
  182. }
  183. $this->auth_user = $user;
  184. Event::handle('EndSetApiUser', array($this->auth_user));
  185. } else {
  186. // If $user is not a real User, let's force it to null.
  187. $this->auth_user = null;
  188. }
  189. // FIXME: setting the value returned by common_current_user()
  190. // There should probably be a better method for this. common_set_user()
  191. // does lots of session stuff.
  192. global $_cur;
  193. $_cur = $this->auth_user;
  194. $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
  195. "application '%s' (id: %d) with %s access.";
  196. common_log(
  197. LOG_INFO,
  198. sprintf(
  199. $msg,
  200. $this->auth_user->nickname,
  201. $this->auth_user->id,
  202. $app->name,
  203. $app->id,
  204. ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
  205. )
  206. );
  207. } else {
  208. // TRANS: OAuth exception given when an incorrect access token was given for a user.
  209. throw new OAuthException(_('Bad access token.'));
  210. }
  211. } else {
  212. // Also should not happen.
  213. // TRANS: OAuth exception given when no user was found for a given token (no token was found).
  214. throw new OAuthException(_('No user for that token.'));
  215. }
  216. } catch (OAuthException $e) {
  217. $this->logAuthFailure($e->getMessage());
  218. common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
  219. $this->clientError($e->getMessage(), 401);
  220. }
  221. }
  222. /**
  223. * Does this API resource require authentication?
  224. *
  225. * @return boolean true
  226. */
  227. public function requiresAuth()
  228. {
  229. return true;
  230. }
  231. /**
  232. * Check for a user specified via HTTP basic auth. If there isn't
  233. * one, try to get one by outputting the basic auth header.
  234. *
  235. * @return boolean true or false
  236. */
  237. function checkBasicAuthUser($required = true)
  238. {
  239. $this->basicAuthProcessHeader();
  240. $realm = common_config('api', 'realm');
  241. if (empty($realm)) {
  242. $realm = common_config('site', 'name') . ' API';
  243. }
  244. if (empty($this->auth_user_nickname) && $required) {
  245. header('WWW-Authenticate: Basic realm="' . $realm . '"');
  246. // show error if the user clicks 'cancel'
  247. // TRANS: Client error thrown when authentication fails because a user clicked "Cancel".
  248. $this->clientError(_('Could not authenticate you.'), 401);
  249. } elseif ($required) {
  250. // $this->auth_user_nickname - i.e. PHP_AUTH_USER - will have a value since it was not empty
  251. $user = common_check_user($this->auth_user_nickname,
  252. $this->auth_user_password);
  253. Event::handle('StartSetApiUser', array(&$user));
  254. if ($user instanceof User) {
  255. if (!$user->hasRight(Right::API)) {
  256. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  257. throw new AuthorizationException(_('Not allowed to use API.'));
  258. }
  259. $this->auth_user = $user;
  260. Event::handle('EndSetApiUser', array($this->auth_user));
  261. } else {
  262. $this->auth_user = null;
  263. }
  264. // By default, basic auth users have rw access
  265. $this->access = self::READ_WRITE;
  266. if (!$this->auth_user instanceof User) {
  267. $msg = sprintf(
  268. "basic auth nickname = %s",
  269. $this->auth_user_nickname
  270. );
  271. $this->logAuthFailure($msg);
  272. // We must present WWW-Authenticate in accordance to HTTP status code 401
  273. header('WWW-Authenticate: Basic realm="' . $realm . '"');
  274. // TRANS: Client error thrown when authentication fails.
  275. $this->clientError(_('Could not authenticate you.'), 401);
  276. }
  277. } else {
  278. // all get rw access for actions that don't require auth
  279. $this->access = self::READ_WRITE;
  280. }
  281. }
  282. /**
  283. * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
  284. * param to support basic auth when PHP is running in CGI mode.
  285. *
  286. * @return void
  287. */
  288. function basicAuthProcessHeader()
  289. {
  290. $authHeaders = array('AUTHORIZATION',
  291. 'HTTP_AUTHORIZATION',
  292. 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
  293. $authorization_header = null;
  294. foreach ($authHeaders as $header) {
  295. if (isset($_SERVER[$header])) {
  296. $authorization_header = $_SERVER[$header];
  297. break;
  298. }
  299. }
  300. if (isset($_SERVER['PHP_AUTH_USER'])) {
  301. $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
  302. $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
  303. } elseif (isset($authorization_header)
  304. && strstr(substr($authorization_header, 0, 5), 'Basic')) {
  305. // Decode the HTTP_AUTHORIZATION header on php-cgi server self
  306. // on fcgid server the header name is AUTHORIZATION
  307. $auth_hash = base64_decode(substr($authorization_header, 6));
  308. list($this->auth_user_nickname,
  309. $this->auth_user_password) = explode(':', $auth_hash);
  310. // Set all to null on a empty basic auth request
  311. if (empty($this->auth_user_nickname)) {
  312. $this->auth_user_nickname = null;
  313. $this->auth_password = null;
  314. }
  315. }
  316. }
  317. /**
  318. * Log an API authentication failure. Collect the proxy and IP
  319. * and log them
  320. *
  321. * @param string $logMsg additional log message
  322. */
  323. function logAuthFailure($logMsg)
  324. {
  325. list($proxy, $ip) = common_client_ip();
  326. $msg = sprintf(
  327. 'API auth failure (proxy = %1$s, ip = %2$s) - ',
  328. $proxy,
  329. $ip
  330. );
  331. common_log(LOG_WARNING, $msg . $logMsg);
  332. }
  333. }