userauth.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. ** 2014-09-08
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. **
  13. ** This file contains the bulk of the implementation of the
  14. ** user-authentication extension feature. Some parts of the user-
  15. ** authentication code are contained within the SQLite core (in the
  16. ** src/ subdirectory of the main source code tree) but those parts
  17. ** that could reasonable be separated out are moved into this file.
  18. **
  19. ** To compile with the user-authentication feature, append this file to
  20. ** end of an SQLite amalgamation, then add the SQLITE_USER_AUTHENTICATION
  21. ** compile-time option. See the user-auth.txt file in the same source
  22. ** directory as this file for additional information.
  23. */
  24. #ifdef SQLITE_USER_AUTHENTICATION
  25. #ifndef _SQLITEINT_H_
  26. # include "sqliteInt.h"
  27. #endif
  28. /*
  29. ** Prepare an SQL statement for use by the user authentication logic.
  30. ** Return a pointer to the prepared statement on success. Return a
  31. ** NULL pointer if there is an error of any kind.
  32. */
  33. static sqlite3_stmt *sqlite3UserAuthPrepare(
  34. sqlite3 *db,
  35. const char *zFormat,
  36. ...
  37. ){
  38. sqlite3_stmt *pStmt;
  39. char *zSql;
  40. int rc;
  41. va_list ap;
  42. int savedFlags = db->flags;
  43. va_start(ap, zFormat);
  44. zSql = sqlite3_vmprintf(zFormat, ap);
  45. va_end(ap);
  46. if( zSql==0 ) return 0;
  47. db->flags |= SQLITE_WriteSchema;
  48. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  49. db->flags = savedFlags;
  50. sqlite3_free(zSql);
  51. if( rc ){
  52. sqlite3_finalize(pStmt);
  53. pStmt = 0;
  54. }
  55. return pStmt;
  56. }
  57. /*
  58. ** Check to see if the sqlite_user table exists in database zDb.
  59. */
  60. static int userTableExists(sqlite3 *db, const char *zDb){
  61. int rc;
  62. sqlite3_mutex_enter(db->mutex);
  63. sqlite3BtreeEnterAll(db);
  64. if( db->init.busy==0 ){
  65. char *zErr = 0;
  66. sqlite3Init(db, &zErr);
  67. sqlite3DbFree(db, zErr);
  68. }
  69. rc = sqlite3FindTable(db, "sqlite_user", zDb)!=0;
  70. sqlite3BtreeLeaveAll(db);
  71. sqlite3_mutex_leave(db->mutex);
  72. return rc;
  73. }
  74. /*
  75. ** Check to see if database zDb has a "sqlite_user" table and if it does
  76. ** whether that table can authenticate zUser with nPw,zPw. Write one of
  77. ** the UAUTH_* user authorization level codes into *peAuth and return a
  78. ** result code.
  79. */
  80. static int userAuthCheckLogin(
  81. sqlite3 *db, /* The database connection to check */
  82. const char *zDb, /* Name of specific database to check */
  83. u8 *peAuth /* OUT: One of UAUTH_* constants */
  84. ){
  85. sqlite3_stmt *pStmt;
  86. int rc;
  87. *peAuth = UAUTH_Unknown;
  88. if( !userTableExists(db, "main") ){
  89. *peAuth = UAUTH_Admin; /* No sqlite_user table. Everybody is admin. */
  90. return SQLITE_OK;
  91. }
  92. if( db->auth.zAuthUser==0 ){
  93. *peAuth = UAUTH_Fail;
  94. return SQLITE_OK;
  95. }
  96. pStmt = sqlite3UserAuthPrepare(db,
  97. "SELECT pw=sqlite_crypt(?1,pw), isAdmin FROM \"%w\".sqlite_user"
  98. " WHERE uname=?2", zDb);
  99. if( pStmt==0 ) return SQLITE_NOMEM;
  100. sqlite3_bind_blob(pStmt, 1, db->auth.zAuthPW, db->auth.nAuthPW,SQLITE_STATIC);
  101. sqlite3_bind_text(pStmt, 2, db->auth.zAuthUser, -1, SQLITE_STATIC);
  102. rc = sqlite3_step(pStmt);
  103. if( rc==SQLITE_ROW && sqlite3_column_int(pStmt,0) ){
  104. *peAuth = sqlite3_column_int(pStmt, 1) + UAUTH_User;
  105. }else{
  106. *peAuth = UAUTH_Fail;
  107. }
  108. return sqlite3_finalize(pStmt);
  109. }
  110. int sqlite3UserAuthCheckLogin(
  111. sqlite3 *db, /* The database connection to check */
  112. const char *zDb, /* Name of specific database to check */
  113. u8 *peAuth /* OUT: One of UAUTH_* constants */
  114. ){
  115. int rc;
  116. u8 savedAuthLevel;
  117. assert( zDb!=0 );
  118. assert( peAuth!=0 );
  119. savedAuthLevel = db->auth.authLevel;
  120. db->auth.authLevel = UAUTH_Admin;
  121. rc = userAuthCheckLogin(db, zDb, peAuth);
  122. db->auth.authLevel = savedAuthLevel;
  123. return rc;
  124. }
  125. /*
  126. ** If the current authLevel is UAUTH_Unknown, the take actions to figure
  127. ** out what authLevel should be
  128. */
  129. void sqlite3UserAuthInit(sqlite3 *db){
  130. if( db->auth.authLevel==UAUTH_Unknown ){
  131. u8 authLevel = UAUTH_Fail;
  132. sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  133. db->auth.authLevel = authLevel;
  134. if( authLevel<UAUTH_Admin ) db->flags &= ~SQLITE_WriteSchema;
  135. }
  136. }
  137. /*
  138. ** Implementation of the sqlite_crypt(X,Y) function.
  139. **
  140. ** If Y is NULL then generate a new hash for password X and return that
  141. ** hash. If Y is not null, then generate a hash for password X using the
  142. ** same salt as the previous hash Y and return the new hash.
  143. */
  144. void sqlite3CryptFunc(
  145. sqlite3_context *context,
  146. int NotUsed,
  147. sqlite3_value **argv
  148. ){
  149. const char *zIn;
  150. int nIn;
  151. u8 *zData;
  152. u8 *zOut;
  153. char zSalt[16];
  154. int nHash = 32;
  155. zIn = sqlite3_value_blob(argv[0]);
  156. nIn = sqlite3_value_bytes(argv[0]);
  157. if( sqlite3_value_type(argv[1])==SQLITE_BLOB
  158. && sqlite3_value_bytes(argv[1])==nHash+sizeof(zSalt)
  159. ){
  160. memcpy(zSalt, sqlite3_value_blob(argv[1]), sizeof(zSalt));
  161. }else{
  162. sqlite3_randomness(sizeof(zSalt), zSalt);
  163. }
  164. zData = sqlite3_malloc( nIn+sizeof(zSalt) );
  165. zOut = sqlite3_malloc( nHash+sizeof(zSalt) );
  166. if( zOut==0 ){
  167. sqlite3_result_error_nomem(context);
  168. }else{
  169. memcpy(zData, zSalt, sizeof(zSalt));
  170. memcpy(zData+sizeof(zSalt), zIn, nIn);
  171. memcpy(zOut, zSalt, sizeof(zSalt));
  172. sha256(zData, (unsigned int) nIn+sizeof(zSalt), zOut+sizeof(zSalt));
  173. sqlite3_result_blob(context, zOut, nHash+sizeof(zSalt), sqlite3_free);
  174. }
  175. if (zData != 0) sqlite3_free(zData);
  176. }
  177. /*
  178. ** If a database contains the SQLITE_USER table, then the
  179. ** sqlite3_user_authenticate() interface must be invoked with an
  180. ** appropriate username and password prior to enable read and write
  181. ** access to the database.
  182. **
  183. ** Return SQLITE_OK on success or SQLITE_ERROR if the username/password
  184. ** combination is incorrect or unknown.
  185. **
  186. ** If the SQLITE_USER table is not present in the database file, then
  187. ** this interface is a harmless no-op returnning SQLITE_OK.
  188. */
  189. int sqlite3_user_authenticate(
  190. sqlite3 *db, /* The database connection */
  191. const char *zUsername, /* Username */
  192. const char *zPW, /* Password or credentials */
  193. int nPW /* Number of bytes in aPW[] */
  194. ){
  195. int rc;
  196. u8 authLevel = UAUTH_Fail;
  197. db->auth.authLevel = UAUTH_Unknown;
  198. sqlite3_free(db->auth.zAuthUser);
  199. sqlite3_free(db->auth.zAuthPW);
  200. memset(&db->auth, 0, sizeof(db->auth));
  201. db->auth.zAuthUser = sqlite3_mprintf("%s", zUsername);
  202. if( db->auth.zAuthUser==0 ) return SQLITE_NOMEM;
  203. db->auth.zAuthPW = sqlite3_malloc( nPW+1 );
  204. if( db->auth.zAuthPW==0 ) return SQLITE_NOMEM;
  205. memcpy(db->auth.zAuthPW,zPW,nPW);
  206. db->auth.nAuthPW = nPW;
  207. rc = sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  208. db->auth.authLevel = authLevel;
  209. sqlite3ExpirePreparedStatements(db);
  210. if( rc ){
  211. return rc; /* OOM error, I/O error, etc. */
  212. }
  213. if( authLevel<UAUTH_User ){
  214. return SQLITE_AUTH; /* Incorrect username and/or password */
  215. }
  216. return SQLITE_OK; /* Successful login */
  217. }
  218. /*
  219. ** The sqlite3_user_add() interface can be used (by an admin user only)
  220. ** to create a new user. When called on a no-authentication-required
  221. ** database, this routine converts the database into an authentication-
  222. ** required database, automatically makes the added user an
  223. ** administrator, and logs in the current connection as that user.
  224. ** The sqlite3_user_add() interface only works for the "main" database, not
  225. ** for any ATTACH-ed databases. Any call to sqlite3_user_add() by a
  226. ** non-admin user results in an error.
  227. */
  228. int sqlite3_user_add(
  229. sqlite3 *db, /* Database connection */
  230. const char *zUsername, /* Username to be added */
  231. const char *aPW, /* Password or credentials */
  232. int nPW, /* Number of bytes in aPW[] */
  233. int isAdmin /* True to give new user admin privilege */
  234. ){
  235. sqlite3_stmt *pStmt;
  236. int rc;
  237. sqlite3UserAuthInit(db);
  238. if( db->auth.authLevel<UAUTH_Admin ) return SQLITE_AUTH;
  239. if( !userTableExists(db, "main") ){
  240. if( !isAdmin ) return SQLITE_AUTH;
  241. pStmt = sqlite3UserAuthPrepare(db,
  242. "CREATE TABLE sqlite_user(\n"
  243. " uname TEXT PRIMARY KEY,\n"
  244. " isAdmin BOOLEAN,\n"
  245. " pw BLOB\n"
  246. ") WITHOUT ROWID;");
  247. if( pStmt==0 ) return SQLITE_NOMEM;
  248. sqlite3_step(pStmt);
  249. rc = sqlite3_finalize(pStmt);
  250. if( rc ) return rc;
  251. }
  252. pStmt = sqlite3UserAuthPrepare(db,
  253. "INSERT INTO sqlite_user(uname,isAdmin,pw)"
  254. " VALUES(%Q,%d,sqlite_crypt(?1,NULL))",
  255. zUsername, isAdmin!=0);
  256. if( pStmt==0 ) return SQLITE_NOMEM;
  257. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  258. sqlite3_step(pStmt);
  259. rc = sqlite3_finalize(pStmt);
  260. if( rc ) return rc;
  261. if( db->auth.zAuthUser==0 ){
  262. assert( isAdmin!=0 );
  263. sqlite3_user_authenticate(db, zUsername, aPW, nPW);
  264. }
  265. return SQLITE_OK;
  266. }
  267. /*
  268. ** The sqlite3_user_change() interface can be used to change a users
  269. ** login credentials or admin privilege. Any user can change their own
  270. ** login credentials. Only an admin user can change another users login
  271. ** credentials or admin privilege setting. No user may change their own
  272. ** admin privilege setting.
  273. */
  274. int sqlite3_user_change(
  275. sqlite3 *db, /* Database connection */
  276. const char *zUsername, /* Username to change */
  277. const char *aPW, /* Modified password or credentials */
  278. int nPW, /* Number of bytes in aPW[] */
  279. int isAdmin /* Modified admin privilege for the user */
  280. ){
  281. sqlite3_stmt *pStmt;
  282. int rc;
  283. u8 authLevel;
  284. authLevel = db->auth.authLevel;
  285. if( authLevel<UAUTH_User ){
  286. /* Must be logged in to make a change */
  287. return SQLITE_AUTH;
  288. }
  289. if( strcmp(db->auth.zAuthUser, zUsername)!=0 ){
  290. if( db->auth.authLevel<UAUTH_Admin ){
  291. /* Must be an administrator to change a different user */
  292. return SQLITE_AUTH;
  293. }
  294. }else if( isAdmin!=(authLevel==UAUTH_Admin) ){
  295. /* Cannot change the isAdmin setting for self */
  296. return SQLITE_AUTH;
  297. }
  298. db->auth.authLevel = UAUTH_Admin;
  299. if( !userTableExists(db, "main") ){
  300. /* This routine is a no-op if the user to be modified does not exist */
  301. }else{
  302. pStmt = sqlite3UserAuthPrepare(db,
  303. "UPDATE sqlite_user SET isAdmin=%d, pw=sqlite_crypt(?1,NULL)"
  304. " WHERE uname=%Q", isAdmin, zUsername);
  305. if( pStmt==0 ){
  306. rc = SQLITE_NOMEM;
  307. }else{
  308. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  309. sqlite3_step(pStmt);
  310. rc = sqlite3_finalize(pStmt);
  311. }
  312. }
  313. db->auth.authLevel = authLevel;
  314. return rc;
  315. }
  316. /*
  317. ** The sqlite3_user_delete() interface can be used (by an admin user only)
  318. ** to delete a user. The currently logged-in user cannot be deleted,
  319. ** which guarantees that there is always an admin user and hence that
  320. ** the database cannot be converted into a no-authentication-required
  321. ** database.
  322. */
  323. int sqlite3_user_delete(
  324. sqlite3 *db, /* Database connection */
  325. const char *zUsername /* Username to remove */
  326. ){
  327. sqlite3_stmt *pStmt;
  328. if( db->auth.authLevel<UAUTH_Admin ){
  329. /* Must be an administrator to delete a user */
  330. return SQLITE_AUTH;
  331. }
  332. if( strcmp(db->auth.zAuthUser, zUsername)==0 ){
  333. /* Cannot delete self */
  334. return SQLITE_AUTH;
  335. }
  336. if( !userTableExists(db, "main") ){
  337. /* This routine is a no-op if the user to be deleted does not exist */
  338. return SQLITE_OK;
  339. }
  340. pStmt = sqlite3UserAuthPrepare(db,
  341. "DELETE FROM sqlite_user WHERE uname=%Q", zUsername);
  342. if( pStmt==0 ) return SQLITE_NOMEM;
  343. sqlite3_step(pStmt);
  344. return sqlite3_finalize(pStmt);
  345. }
  346. #endif /* SQLITE_USER_AUTHENTICATION */