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.

3236 lines
108 KiB

26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
  1. #!@PERL@
  2. # ****************************
  3. package MySQLaccess;
  4. #use strict;
  5. use File::Temp qw(tempfile tmpnam);
  6. use Fcntl;
  7. BEGIN {
  8. # ****************************
  9. # static information...
  10. $VERSION = "2.06, 20 Dec 2000";
  11. $0 =~ m%/([^/]+)$%o;
  12. $script = $1;
  13. $script = 'MySQLAccess' unless $script;
  14. $script_conf = "$script.conf";
  15. $script_log = $ENV{'HOME'}."/$script.log";
  16. # ****************************
  17. # information on MySQL
  18. $MYSQL = '@bindir@/mysql'; # path to mysql executable
  19. $SERVER = '3.21';
  20. $MYSQL_OPT = ' --batch --unbuffered';
  21. $ACCESS_DB = 'mysql'; # name of DB with grant-tables
  22. $ACCESS_H = 'host'; #
  23. $ACCESS_U = 'user'; #
  24. $ACCESS_D = 'db'; #
  25. # Add/Edit privileges
  26. $ACCESS_H_TMP = 'host_tmp';
  27. $ACCESS_U_TMP = 'user_tmp';
  28. $ACCESS_D_TMP = 'db_tmp';
  29. $ACCESS_H_BCK = 'host_backup';
  30. $ACCESS_U_BCK = 'user_backup';
  31. $ACCESS_D_BCK = 'db_backup';
  32. $DIFF = '/usr/bin/diff';
  33. $MYSQLDUMP = '@bindir@/mysqldump';
  34. #path to mysqldump executable
  35. $MYSQLADMIN= 'http://foobar.com/MySQLadmin';
  36. #URL of CGI for manipulating
  37. #the temporary grant-tables
  38. }
  39. END {
  40. unlink $MYSQL_CNF if defined $MYSQL_CNF and not $DEBUG;
  41. }
  42. $INFO = <<"_INFO";
  43. --------------------------------------------------------------------------
  44. mysqlaccess (Version $VERSION)
  45. ~~~~~~~~~~~
  46. Copyright (C) 1997,1998 Yves.Carlier\@rug.ac.be
  47. University of Ghent (RUG), Belgium
  48. Administratieve Informatieverwerking (AIV)
  49. report the access-privileges for a USER from a HOST to a DB
  50. Many thanks go to <monty\@mysql.com> and <psmith\@BayNetworks.COM>
  51. for their suggestions, debugging and patches.
  52. use `$script -?' to get more information on available options.
  53. From version 2.0x, $script can also be used through a WEB-browser
  54. if it is ran as a CGI-script. (See the release-notes)
  55. --------------------------------------------------------------------------
  56. _INFO
  57. $OPTIONS = <<_OPTIONS;
  58. Usage: $script [host [user [db]]] OPTIONS
  59. -?, --help display this helpscreen and exit
  60. -v, --version print information on the program `$script'
  61. -u, --user=# username for logging in to the db
  62. -p, --password=# validate password for user
  63. -h, --host=# name or IP-number of the host
  64. -d, --db=# name of the database
  65. -U, --superuser=# connect as superuser
  66. -P, --spassword=# password for superuser
  67. -H, --rhost=# remote MySQL-server to connect to
  68. --old_server connect to old MySQL-server (before v3.21) which
  69. does not yet know how to handle full where clauses.
  70. -b, --brief single-line tabular report
  71. -t, --table report in table-format
  72. --relnotes print release-notes
  73. --plan print suggestions/ideas for future releases
  74. --howto some examples of how to run `$script'
  75. --debug=N enter debuglevel N (0..3)
  76. --copy reload temporary grant-tables from original ones
  77. --preview show differences in privileges after making
  78. changes in (temporary) grant-tables
  79. --commit copy grant-rules from temporary tables to grant-tables
  80. (!don't forget to do an mysqladmin reload)
  81. --rollback undo the last changes to the grant-tables.
  82. Note:
  83. + At least the user and the db must be given (even with wildcards)
  84. + If no host is given, `localhost' is assumed
  85. + Wilcards (*,?,%,_) are allowed for host, user and db, but be sure
  86. to escape them from your shell!! (ie type \\* or '*')
  87. _OPTIONS
  88. $RELEASE = <<'_RELEASE';
  89. Release Notes:
  90. -------------
  91. 0.1-beta1: internal
  92. - first trial.
  93. 0.1-beta2: (1997-02-27)
  94. - complete rewrite of the granting-rules, based on the documentation
  95. found in de FAQ.
  96. - IP-number and name for a host are equiv.
  97. 0.1-beta3: (1997-03-10)
  98. - more information
  99. - 'localhost' and the name/ip of the local machine are now equiv.
  100. 0.1-beta4: (1997-03-11)
  101. - inform the user if he has not enough priv. to read the mysql db
  102. 1.0-beta1: (1997-03-12)
  103. suggestions by Monty:
  104. - connect as superuser with superpassword.
  105. - mysqlaccess could also notice if all tables are empty. This means
  106. that all user have full access!
  107. - It would be nice if one could optionally start mysqlaccess without
  108. any options just the arguments 'user db' or 'host user db', where
  109. host is 'localhost' if one uses only two arguments.
  110. 1.0-beta2: (1997-03-14)
  111. - bugfix: translation to reg.expr of \_ and \%.
  112. - bugfix: error in matching regular expression and string given
  113. by user which resulted in
  114. 'test_123' being matched with 'test'
  115. 1.0-beta3: (1997-03-14)
  116. - bugfix: the user-field should not be treated as a sql-regexpr,
  117. but as a plain string.
  118. - bugfix: the host-table should not be used if the host isn't empty in db
  119. or if the host isn't emty in user
  120. (Monty)
  121. 1.0-beta4: (1997-03-14)
  122. - bugfix: in an expression "$i = $j or $k", the '=' binds tighter than the or
  123. which results in problems...
  124. (by Monty)
  125. - running mysqlaccess with "perl -w" gives less warnings... ;-)
  126. 1.0-beta5: (1997-04-04)
  127. - bugfix: The table sorting was only being applied to the "user" table; all
  128. the tables need to be sorted. Rewrote the sort algorithm, and
  129. the table walk algorithm (no temp file anymore), and various
  130. other cleanups. I believe the access calculation is 100% correct.
  131. (by Paul D. Smith <psmith\@baynetworks.com>)
  132. - Allow the debug level to be set on the cmd line with --debug=N.
  133. (by Paul D. Smith <psmith\@baynetworks.com>)
  134. - More -w cleanups; should be totally -w-clean.
  135. (by Paul D. Smith <psmith\@baynetworks.com>)
  136. 1.1-beta1: (1997-04-xx)
  137. 1.1-beta2: (1997-04-11)
  138. - new options:
  139. --all_users : report access-rights for all possible users
  140. --all_dbs : report access-rights for all possible dbs
  141. --all_hosts : report access-rights for all possible hosts
  142. --brief : as brief as possible, don't mention notes,warnings and rules
  143. --password : validate password for user
  144. - layout: long messages are wrapped on the report.
  145. - functionality:
  146. more descriptive notes and warnings
  147. wildcards (*,?) are allowed in the user,host and db options
  148. setting xxxx=* is equiv to using option --all_xxxx
  149. note: make sure you escape your wildcards, so they don't get
  150. interpreted by the shell. use \* or '*'
  151. - bugfix: Fieldnames which should be skipped on the output can now have
  152. a first capital letter.
  153. - bugfix: any option with a '.' (eg ip-number) was interpreted as
  154. a wildcard-expression.
  155. - bugfix: When no entry was found in the db-table, the default accessrights are
  156. N, instead of the faulty Y in a previous version.
  157. 1.1-beta-3 : (1997-04-xx)
  158. 1.1-beta-4 : (1997-04-xx)
  159. 1.1-beta-5 : (1997-04-xx)
  160. 1.1 : (1997-04-28)
  161. - new options:
  162. --rhost : name of mysql-server to connect to
  163. --plan : print suggestions/ideas for future releases
  164. --relnotes : display release-notes
  165. --howto : display examples on how to use mysqlaccess
  166. --brief : single-line tabular output
  167. - functionality/bugfix:
  168. * removed options --all_users,--all_dbs,--all_hosts, which
  169. were redundant with the wildcard-expressions for the corresponding
  170. options. They made the processing of the commandline too painful
  171. and confusing ;-)
  172. (suggested by psmith)
  173. * redefined the option --brief, which now gives a single-line
  174. tabular output
  175. * Now we check if the right version of the mysql-client is used,
  176. since we might use an option not yet implemented in an
  177. older version (--unbuffered, since 3.0.18)
  178. Also the error-messages the mysql-client reports are
  179. better interpreted ;-)
  180. * Wildcards can now be given following the SQL-expression
  181. (%,_) and the Regular-expression (*,?) syntax.
  182. - speed: we now open a bidirectional pipe to the mysql-client, and keep
  183. it open throughout the whole run. Queries are written to,
  184. and the answers read from the pipe.
  185. (suggested by monty)
  186. - bugfixes:
  187. * the Rules were not properly reset over iterations
  188. * when in different tables the field-names were not identical,
  189. eg. Select_priv and select_priv, they were considered as
  190. definitions of 2 different access-rights.
  191. * the IP-number of a host with a name containing wildcards should
  192. not be searched for in Name2IP and IP2Name.
  193. * various other small things, pointed out by <monty> and <psmith>
  194. 1.2 : (1997-05-13)
  195. - bugfix:
  196. * Fixed bug in acl with anonymous user: Now if one gets accepted by the
  197. user table as a empty user name, the user name is set to '' when
  198. checking against the 'db' and 'host' tables. (Bug fixed in MySQL3.20.19)
  199. 1.2-1 : (1997-xx-xx)
  200. - bugfix:
  201. * hashes should be initialized with () instead of {} <psmith>
  202. * "my" variable $name masks earlier declaration in same scope,
  203. using perl 5.004 <????>
  204. 1.2-2 : (1997-06-10)
  205. 2.0p1-3 : (1997-10-xx)
  206. - new
  207. * packages
  208. * log-file for debug-output : /tmp/mysqlaccess.log
  209. * default values are read from a configuration file $script.conf
  210. first this file is looked for in the current directory; if not
  211. found it is looked for in /etc/
  212. Note that when default-values are given, these can't get overriden
  213. by empty (blanc) values!
  214. * CGI-BIN version with HTML and forms interface. Simply place the
  215. script in an ScriptAliased directory, make the configuration file
  216. available in the that directory or in /etc, and point your browser
  217. to the right URL.
  218. * copy the grant-rules to temporary tables, where you are safe to
  219. play with them.
  220. * preview changes in privileges after changing grant-rules,
  221. before taking them into production
  222. * copy the new grant-rules from the temporary tables back to the
  223. grant-tables.
  224. * Undo all changes made in the grant-tables (1-level undo).
  225. -new options:
  226. * --table : as opposite of the --brief option.
  227. * --copy : (re)load temporary grant-tables from original ones.
  228. * --preview : preview changes in privileges after changing
  229. some or more entries in the grant-tables.
  230. * --commit : copy grant-rules from temporary tables to grant-tables
  231. (!don't forget to do an mysqladmin reload)
  232. * --rollback: undo the last changes to the grant-tables.
  233. - bugfix:
  234. * if the table db is empty, mysqlaccess freezed
  235. (by X Zhu <X.Zhu@Bradford.ac.uk>)
  236. 2.0 : (1997-10-09)
  237. - fixed some "-w" warnings.
  238. - complain when certain programs and paths can't be found.
  239. 2.01 : (1997-12-12)
  240. - bugfix:
  241. * rules for db-table where not calculated and reported correctly.
  242. 2.02 : (1998-01-xx)
  243. - bugfix:
  244. * Privileges of the user-table were not AND-ed properly with the
  245. other privileges. (reported by monty)
  246. - new option:
  247. * --old_server: mysqlaccess will now use a full where clause when
  248. retrieving information from the MySQL-server. If
  249. you are connecting to an old server (before v3.21)
  250. then use the option --old_server.
  251. 2.03 : (1998-02-27)
  252. - bugfix:
  253. * in Host::MatchTemplate: incorrect match if host-field was left empty.
  254. 2.04-alpha1 : (2000-02-11)
  255. Closes vulnerability due to former implementation requiring passwords
  256. to be passed on the command line.
  257. - functionality
  258. Option values for --password -p -spassword -P may now be omitted from
  259. command line, in which case the values will be prompted for.
  260. (fix supplied by Steve Harvey <sgh@vex.net>)
  261. 2.05: (2000-02-17) Monty
  262. Moved the log file from /tmp to ~
  263. 2.06: Don't print '+++USING FULL WHERE CLAUSE+++'
  264. _RELEASE
  265. $TODO = <<_TODO;
  266. Plans:
  267. -----
  268. -a full where clause is use now. How can we handle older servers?
  269. -add some more functionality for DNS.
  270. -select the warnings more carefuly.
  271. >> I think that the warnings should either be enhanced to _really_
  272. >> understand and report real problems accurately, or restricted to
  273. >> only printing things that it knows with 100% certainty. <psmith)
  274. >> Why do I have both '%' and 'any_other_host' in there? Isn't that
  275. >> the same thing? I think it's because I have an actual host '%' in
  276. >> one of my tables. Probably the script should catch that and not
  277. >> duplicate output. <psmith>
  278. _TODO
  279. # From the FAQ: the Grant-algorithm
  280. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  281. # The host table is mainly to maintain a list of "secure" servers.
  282. # At TCX hosts contain a list of all machines on local network. These are granted
  283. # all privileges.
  284. # Technically the user grant is calculated by:
  285. #
  286. # 1.First sort all entries by host by putting host without wildcards first,
  287. # after this host with wildcards and entries with host = ".
  288. # Under each host sort user by the same criterias.
  289. # 2.Get grant for user from the "db" table.
  290. # 3.If hostname is "empty" for the found entry, AND the privileges with
  291. # the privileges for the host in "host" table.
  292. # (Remove all which is not "Y" in both)
  293. # 4.OR (add) the privileges for the user from the "user" table.
  294. # (add all privileges which is "Y" in "user")
  295. #
  296. # When matching, use the first found match.
  297. #
  298. # -----------------------------------------------------------------------------------
  299. $HOWTO = <<_HOWTO;
  300. Examples of how to call $script:
  301. ~~~~~~~~
  302. 1)Calling $script with 2 arguments:
  303. \$ $script root mysql
  304. ->report rights of user root logged on at the local host in db mysql
  305. Access-rights
  306. for USER 'root', from HOST 'localhost', to DB 'mysql'
  307. +-----------------+---+ +-----------------+---+
  308. | select_priv | Y | | drop_priv | Y |
  309. | insert_priv | Y | | reload_priv | Y |
  310. | update_priv | Y | | shutdown_priv | Y |
  311. | delete_priv | Y | | process_priv | Y |
  312. | create_priv | Y | | file_priv | Y |
  313. +-----------------+---+ +-----------------+---+
  314. BEWARE: Everybody can access your DB as user 'root'
  315. : WITHOUT supplying a password. Be very careful about it!!
  316. The following rules are used:
  317. db : 'No matching rule'
  318. host : 'Not processed: host-field is not empty in db-table.'
  319. user : 'localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'
  320. 2)Calling $script with 3 arguments:
  321. \$ $script foo.bar nobody Foo
  322. ->report rights of user root logged in at machine foobar to db Foo
  323. Access-rights
  324. for USER 'nobody', from HOST 'foo.bar', to DB 'Foo'
  325. +-----------------+---+ +-----------------+---+
  326. | select_priv | Y | | drop_priv | N |
  327. | insert_priv | Y | | reload_priv | N |
  328. | update_priv | Y | | shutdown_priv | N |
  329. | delete_priv | Y | | process_priv | N |
  330. | create_priv | N | | file_priv | N |
  331. +-----------------+---+ +-----------------+---+
  332. BEWARE: Everybody can access your DB as user 'nobody'
  333. : WITHOUT supplying a password. Be very careful about it!!
  334. The following rules are used:
  335. db : 'foo.bar','Foo','nobody','Y','Y','Y','N','N','N'
  336. host : 'Not processed: host-field is not empty in db-table.'
  337. user : 'foo.bar','nobody','','N','N','N','Y','N','N','N','N','N','N'
  338. 3)Using wildcards:
  339. \$ $script \\* nobody Foo --brief
  340. ->report access-rights of user nobody from all machines to db Foo,
  341. and use a matrix-report.
  342. Sel Ins Upd Del Crea Drop Reld Shut Proc File Host,User,DB
  343. ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- --------------------
  344. Y Y Y Y N N N N N N localhost,nobody,Foo
  345. N N N N N N N N N N %,nobody,Foo
  346. N N N N N N N N N N any_other_host,nobody,Foo
  347. _HOWTO
  348. # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
  349. # START OF THE PROGRAM #
  350. # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
  351. use Getopt::Long;
  352. use Sys::Hostname;
  353. use IPC::Open3;
  354. # ****************************
  355. # debugging flag
  356. # can be set to 0,1,2,3
  357. # a higher value gives more info
  358. # ! this can also be set on the command-line
  359. $DEBUG = 0;
  360. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>8
  361. # Normaly nothing should be changed beneeth this line
  362. # ****************************
  363. # no caching on STDOUT
  364. $|=1;
  365. $MYSQL_CNF = tmpnam();
  366. %MYSQL_CNF = (client => { },
  367. mysql => { },
  368. mysqldump => { },
  369. );
  370. $NEW_USER = 'ANY_NEW_USER';
  371. $NEW_DB = 'ANY_NEW_DB' ;
  372. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
  373. # mysqlaccess: #
  374. # ~~~~~~~~~~~ #
  375. # Lets get to it, #
  376. # and start the program by processing the parameters #
  377. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #
  378. ($CMD,$CGI) = GetMode();
  379. # ****************************
  380. # the copyright message should
  381. # always be printed (once)
  382. MySQLaccess::Report::Print_Header();
  383. # *****************************
  384. # Read configuration-file
  385. MySQLaccess::Debug::Print(1, "Reading configuration file...");
  386. if (-f "./$script_conf") {
  387. require "./$script_conf";
  388. }
  389. elsif (-f "/etc/$script_conf") {
  390. require "/etc/$script_conf";
  391. }
  392. # ****************************
  393. # Read in all parameters
  394. if ($MySQLaccess::CMD) { #command-line version
  395. # ----------------------------
  396. # Get options from commandline
  397. $Getopt::Long::ignorecase=0; #case sensitive options
  398. if ( grep(/\-\?/,@ARGV) ) { MySQLaccess::Report::Print_Usage(); exit 0; }
  399. GetOptions("help" => \$Param{'help'}
  400. ,"host|h=s" => \$Param{'host'}
  401. ,"user|u=s" => \$Param{'user'}
  402. ,"password|p:s" => \$Param{'password'}
  403. ,"db|d=s" => \$Param{'db'}
  404. ,"superuser|U=s" => \$Param{'superuser'}
  405. ,"spassword|P:s" => \$Param{'spassword'}
  406. ,"rhost|H=s" => \$Param{'rhost'}
  407. ,"old_server" => \$Param{'old_server'}
  408. ,"debug=i" => \$Param{'DEBUG'}
  409. ,"brief|b" => \$Param{'brief'}
  410. ,"table|t" => \$Param{'table'}
  411. ,"relnotes" => \$Param{'relnotes'}
  412. ,"plan" => \$Param{'plan'}
  413. ,"howto" => \$Param{'howto'}
  414. ,"version|v" => \$Param{'version'}
  415. ,"preview" => \$Param{'preview'}
  416. ,"copy" => \$Param{'copy'}
  417. ,"commit" => \$Param{'commit'}
  418. ,'rollback' => \$Param{'rollback'}
  419. );
  420. # -----------------------------
  421. # set DEBUG
  422. $DEBUG = $Param{'DEBUG'} if ($Param{'DEBUG'}>=$DEBUG);
  423. # -----------------------------
  424. # check for things which aren't
  425. # declared as options:
  426. # 2 arguments: (user,db) -> ('localhost','user','db')
  427. if ($#ARGV == 1) {
  428. MySQLaccess::Debug::Print(2,"$script called with 2 arguments:");
  429. $Param{'host'} = $Param{'host'} || 'localhost';
  430. $Param{'user'} = $ARGV[0] || $Param{'user'};
  431. $Param{'db'} = $ARGV[1] || $Param{'db'};
  432. }
  433. # 3 arguments: (host,user,db)
  434. if ($#ARGV == 2) {
  435. MySQLaccess::Debug::Print(2,"$script called with 3 arguments:");
  436. $Param{'host'} = $ARGV[0] || $Param{'host'};
  437. $Param{'user'} = $ARGV[1] || $Param{'user'};
  438. $Param{'db'} = $ARGV[2] || $Param{'db'};
  439. }
  440. # -------------------------------------
  441. # prompt for user password if requested
  442. if ( defined($Param{'password'}) && length($Param{'password'}) == 0 ) {
  443. $Param{'password'} = PromptPass(
  444. "Password for MySQL user $Param{'user'}: ");
  445. }
  446. }
  447. if ($MySQLaccess::CGI) { #CGI-version
  448. require CGI;
  449. $Q = new CGI;
  450. $Param{'help'} = $Q->param('help') ;
  451. $Param{'host'} = $Q->param('host') || $Q->param('h') || $Param{'host'};
  452. $Param{'user'} = $Q->param('user') || $Q->param('u') || $Param{'user'};
  453. $Param{'db'} = $Q->param('db') || $Q->param('d') || $Param{'db'};
  454. $Param{'password'} = $Q->param('password') || $Q->param('p') || $Param{'password'};
  455. $Param{'superuser'} = $Q->param('superuser') || $Q->param('U') || $Param{'superuser'};
  456. $Param{'spassword'} = $Q->param('spassword') || $Q->param('P') || $Param{'spassword'};
  457. $Param{'rhost'} = $Q->param('rhost') || $Q->param('H') || $Param{'rhost'};
  458. $Param{'old_server'}= $Q->param('old_server')|| $Param{'old_server'};
  459. $Param{'debug'} = $Q->param('debug') || $Param{'debug'};
  460. $Param{'brief'} = $Q->param('brief') || $Param{'brief'};
  461. $Param{'table'} = $Q->param('table') || $Param{'table'};
  462. $Param{'relnotes'} = $Q->param('relnotes');
  463. $Param{'plan'} = $Q->param('plan');
  464. $Param{'howto'} = $Q->param('howto');
  465. $Param{'version'} = $Q->param('version') ? $Q->param('version') : $Q->param('v');
  466. $Param{'edit'} = $Q->param('edit');
  467. $Param{'preview'} = $Q->param('preview');
  468. $Param{'copy'} = $Q->param('copy');
  469. $Param{'commit'} = $Q->param('commit');
  470. $Param{'rollback'} = $Q->param('rollback');
  471. # -----------------------------
  472. # set DEBUG
  473. $DEBUG = $Q->param('debug') if ($Q->param('debug')>=$DEBUG);
  474. }
  475. # ----------------------
  476. # brief and table-format
  477. # exclude each-other
  478. # table-format is prefered
  479. if (defined($Param{'table'})) { undef($Param{'brief'}); }
  480. if (defined($Param{'preview'}) or
  481. defined($Param{'copy'}) or
  482. defined($Param{'commit'}) or
  483. defined($Param{'rollback'}) ) { $Param{'edit'}='on'; }
  484. # ----------------------
  485. # if no host is given
  486. # assume we mean 'localhost'
  487. if (!defined($Param{'host'})) { $Param{'host'}='localhost'; }
  488. # ----------------------
  489. # perform some checks
  490. # -> eliminate 'broken pipe' error
  491. push(@MySQLaccess::Grant::Error,'not_found_mysql') if !(-x $MYSQL);
  492. push(@MySQLaccess::Grant::Error,'not_found_diff') if !(-x $DIFF);
  493. push(@MySQLaccess::Grant::Error,'not_found_mysqldump') if !(-x $MYSQLDUMP);
  494. if (@MySQLaccess::Grant::Error) {
  495. MySQLaccess::Report::Print_Error_Messages() ;
  496. exit 0;
  497. }
  498. #-----------------------
  499. # get info/help if necc.
  500. $print_usage=1;
  501. if ( defined($Param{'version'}) ) {
  502. MySQLaccess::Report::Print_Version();
  503. $print_usage=0;
  504. MySQLaccess::Report::Print_Footer();
  505. MySQLaccess::DB::CloseConnection();
  506. exit 0;
  507. # exit 0;
  508. }
  509. if ( defined($Param{'relnotes'}) ) {
  510. MySQLaccess::Report::Print_Relnotes();
  511. $print_usage=0;
  512. MySQLaccess::Report::Print_Footer();
  513. MySQLaccess::DB::CloseConnection();
  514. exit 0;
  515. # exit 0;
  516. }
  517. if ( defined($Param{'plan'}) ) {
  518. MySQLaccess::Report::Print_Plans();
  519. $print_usage=0;
  520. MySQLaccess::Report::Print_Footer();
  521. MySQLaccess::DB::CloseConnection();
  522. exit 0;
  523. # exit 0;
  524. }
  525. if ( defined($Param{'howto'}) ) {
  526. MySQLaccess::Report::Print_HowTo();
  527. $print_usage=0;
  528. MySQLaccess::Report::Print_Footer();
  529. MySQLaccess::DB::CloseConnection();
  530. exit 0;
  531. # exit 0;
  532. }
  533. # -----------------------------
  534. # generate a help-screen in CMD-mode
  535. # or a blanc form in CGI-mode
  536. if ( defined($Param{'help'})
  537. or !defined($Param{'user'})
  538. or !defined($Param{'host'})
  539. or !defined($Param{'db'})
  540. ) {
  541. push(@MySQLaccess::Grant::Error,'user_required') unless defined($Param{'user'});
  542. push(@MySQLaccess::Grant::Error,'db_required') unless defined($Param{'db'});
  543. push(@MySQLaccess::Grant::Error,'host_required') unless defined($Param{'host'});
  544. MySQLaccess::Report::Print_Usage() if $print_usage;
  545. exit 0;
  546. }
  547. # ----------------------------
  548. # get hostname and local-ip
  549. # for localhost
  550. $localhost = MySQLaccess::Host::LocalHost();
  551. $local_ip = MySQLaccess::Host::Name2IP($localhost);
  552. $MySQLaccess::Host::localhost = MySQLaccess::Host::LocalHost();
  553. $MySQLaccess::Host::local_ip = MySQLaccess::Host::Name2IP($localhost);
  554. MySQLaccess::Debug::Print(3, "localhost name=$localhost, ip=$local_ip");
  555. #-----------------------------------
  556. # version of MySQL-server to connect
  557. # to determine use of full where clause
  558. $MySQLaccess::Host::SERVER = $Param{'old_server'} ? '3.20' : $SERVER;
  559. #---------------------------------
  560. # create the config file for mysql and mysqldump
  561. # to avoid passing authentication info on the command line
  562. #
  563. MergeConfigFiles();
  564. die "Unsafe config file found: $unsafeConfig\n" if $unsafeConfig;
  565. if (defined($Param{'superuser'})) {
  566. $MYSQL_CNF{'mysql'}{'user'} = $Param{'superuser'};
  567. $MYSQL_CNF{'mysqldump'}{'user'} = $Param{'superuser'};
  568. }
  569. if (defined($Param{'spassword'})) {
  570. if ( $CMD && length($Param{'spassword'}) == 0 ) {
  571. $Param{'spassword'} =
  572. PromptPass("Password for MySQL superuser $Param{'superuser'}: ");
  573. }
  574. if ( length($Param{'spassword'}) > 0 ) {
  575. $MYSQL_CNF{'mysql'}{'password'} = $Param{'spassword'};
  576. $MYSQL_CNF{'mysqldump'}{'password'} = $Param{'spassword'};
  577. }
  578. }
  579. WriteTempConfigFile();
  580. #---------------------------------
  581. # Inform user if he has not enough
  582. # privileges to read the access-db
  583. if ( $nerror=MySQLaccess::DB::OpenConnection() ) {
  584. MySQLaccess::Report::Print_Error_Access($nerror);
  585. exit 0;
  586. }
  587. # -----------------------
  588. # Read MySQL ACL-files
  589. if ($nerror=MySQLaccess::Grant::ReadTables()) {
  590. MySQLaccess::Report::Print_Error_Access($nerror);
  591. exit 0;
  592. };
  593. if ($Param{'edit'} and $nerror=MySQLaccess::Grant::ReadTables('tmp')) {
  594. MySQLaccess::Report::Print_Error_Access($nerror);
  595. exit 0;
  596. }
  597. #---------------------------------
  598. # reload temporay grant-tables
  599. # with data from original ones
  600. if ( defined($Param{'copy'}) ) {
  601. $nerror=MySQLaccess::DB::LoadTmpTables();
  602. if ($nerror) {
  603. MySQLaccess::Report::Print_Error_Access($nerror);
  604. exit 0;
  605. }
  606. my $msg = "The grant-rules are copied from the grant-tables to\n"
  607. . "the temporary tables.";
  608. MySQLaccess::Report::Print_Message([$msg]);
  609. # MySQLaccess::Report::Print_Footer();
  610. # MySQLaccess::DB::CloseConnection();
  611. # exit 0;
  612. }
  613. #---------------------------------
  614. # preview result of changes in the
  615. # grant-tables
  616. if ( defined($Param{'preview'}) ) {
  617. $aref=MySQLaccess::Grant::Diff_Privileges();
  618. MySQLaccess::Report::Print_Diff_ACL($aref);
  619. # MySQLaccess::Report::Print_Footer();
  620. # MySQLaccess::DB::CloseConnection();
  621. # exit 0;
  622. }
  623. #---------------------------------
  624. # reload grant-tables
  625. # with data from temporary tables
  626. if ( defined($Param{'commit'}) ) {
  627. if ($nerror = MySQLaccess::DB::CommitGrantTables()) {
  628. MySQLaccess::Report::Print_Error_Access($nerror);
  629. exit 0;
  630. }
  631. my $msg = "The grant-rules have been copied from the temporary tables\n"
  632. . "to the grant-tables.";
  633. my $msg1= "Don't forget to do an 'mysqladmin reload' before these\n"
  634. . "changes take effect.";
  635. my $msg2= "A backup-version of your original grant-rules are saved in the\n"
  636. . "backup-tables, so you can always perform a 1-level rollback.";
  637. MySQLaccess::Report::Print_Message([$msg,$msg1,$msg2]);
  638. # MySQLaccess::Report::Print_Footer();
  639. # MySQLaccess::DB::CloseConnection();
  640. # exit 0;
  641. }
  642. #---------------------------------
  643. # restore previous grant-rules
  644. # with data from backup tables
  645. if ( defined($Param{'rollback'}) ) {
  646. if ($nerror = MySQLaccess::DB::RollbackGrantTables()) {
  647. MySQLaccess::Report::Print_Error_Access($nerror);
  648. exit 0;
  649. }
  650. my $msg = "The old grant-rules have been copied back from the backup tables\n"
  651. . "to the grant-tables.";
  652. my $msg1= "Don't forget to do an 'mysqladmin reload' before these\n"
  653. . "changes take effect.";
  654. MySQLaccess::Report::Print_Message([$msg,$msg1]);
  655. # MySQLaccess::Report::Print_Footer();
  656. # MySQLaccess::DB::CloseConnection();
  657. # exit 0;
  658. }
  659. #----------------------------------
  660. # show edit-taskbar
  661. if ( defined($Param{'edit'})) {
  662. if ($MySQLaccess::CGI ) {
  663. MySQLaccess::Report::Print_Edit();
  664. $print_usage=0;
  665. MySQLaccess::Report::Print_Footer();
  666. MySQLaccess::DB::CloseConnection();
  667. exit 0;
  668. }
  669. else {
  670. MySQLaccess::Report::Print_Edit();
  671. $print_usage=0;
  672. MySQLaccess::Report::Print_Footer();
  673. MySQLaccess::DB::CloseConnection();
  674. exit 0;
  675. }
  676. }
  677. # -----------------------------
  678. # Build list of users,dbs,hosts
  679. # to process...
  680. @all_dbs = @{MySQLaccess::DB::Get_All_dbs($Param{'db'})};
  681. @all_users = @{MySQLaccess::DB::Get_All_users($Param{'user'})};
  682. @all_hosts = @{MySQLaccess::DB::Get_All_hosts($Param{'host'})};
  683. #if EDIT-mode
  684. #@all_dbs_tmp = @{MySQLaccess::DB::Get_All_dbs($Param{'db'},'tmp')};
  685. #@all_users_tmp = @{MySQLaccess::DB::Get_All_users($Param{'user'},'tmp')};
  686. #@all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts($Param{'host'},'tmp')};
  687. # -----------------------------
  688. # Report access-rights for each
  689. # tuple (host,user,db)
  690. #$headers=0;
  691. my %Access = ();
  692. foreach $host (@all_hosts) {
  693. foreach $user (@all_users) {
  694. foreach $db (@all_dbs) {
  695. MySQLaccess::Grant::Initialize();
  696. %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);
  697. MySQLaccess::Report::Print_Access_rights($host,$user,$db,\%Access);
  698. }
  699. }
  700. }
  701. # -----------------------------
  702. # End script
  703. MySQLaccess::Report::Print_Footer();
  704. MySQLaccess::DB::CloseConnection();
  705. exit 0;
  706. #############################################################
  707. # FUNCTIONS #
  708. ###############
  709. sub GetMode {
  710. my $cmd=0;
  711. my $cgi=0;
  712. if (defined($ENV{'HTTP_HOST'})) { $cmd=0; $cgi=1; }
  713. else { $cmd=1; $cgi=0; }
  714. return ($cmd,$cgi);
  715. }
  716. # ================================
  717. # sub PromptPass
  718. # prompt tty for a password
  719. # ================================
  720. sub PromptPass {
  721. my ($prompt) = @_;
  722. my $password;
  723. $ENV{PATH} = "/bin:/usr/bin";
  724. $ENV{IFS} = " \t\n";
  725. $ENV{SHELL} = "/bin/sh";
  726. system "stty -echo";
  727. print $prompt;
  728. chomp($password = <STDIN>);
  729. print "\n";
  730. system "stty echo";
  731. $password;
  732. }
  733. # =================================
  734. # sub CheckUnsafeFile
  735. # tell if a config file containing a password is unsafe
  736. # =================================
  737. sub CheckUnsafeFile {
  738. my ($fname) = @_;
  739. my ($dev, $ino, $mode, $nlink,
  740. $uid, $gid, $rdev, $size,
  741. $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);
  742. if ( $uid != $< ) { # unsafe if owned by other than current user
  743. return 1;
  744. }
  745. if ( $mode & 066 ) { # unsafe if accessible by other
  746. return 1;
  747. }
  748. $fname =~ s#/[^/]+$##;
  749. if ( (length $fname) > 0 ) {
  750. return CheckUnsafeDir($fname);
  751. }
  752. return 0;
  753. }
  754. # =================================
  755. # sub CheckUnsafeDir
  756. # tell if a directory is unsafe
  757. # =================================
  758. sub CheckUnsafeDir {
  759. my ($fname) = @_;
  760. my ($dev, $ino, $mode, $nlink,
  761. $uid, $gid, $rdev, $size,
  762. $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);
  763. # not owned by me or root
  764. if ( ($uid != $<) && ($uid != 0) ) {
  765. return 1;
  766. }
  767. if ( $mode & 022 ) { # unsafe if writable by other
  768. return 1 unless $mode & 01000; # but sticky bit ok
  769. }
  770. $fname =~ s#/[^/]+$##;
  771. if ( (length $fname) > 0 ) {
  772. return CheckUnsafeDir($fname);
  773. }
  774. return 0;
  775. }
  776. # =================================
  777. # sub MergeConfigFile
  778. # merge data from .cnf file
  779. # =================================
  780. sub MergeConfigFile {
  781. my ($fname) = @_;
  782. my ($group, $item, $value);
  783. if ( open CNF, $fname ) {
  784. while (<CNF>) {
  785. s/^\s+//;
  786. next if /^[#;]/;
  787. if ( /\[\s*(\w+)\s*]/ ) {
  788. $group = $1;
  789. $group =~ tr/A-Z/a-z/;
  790. if ( !exists $MYSQL_CNF{$group} ) {
  791. undef $group;
  792. }
  793. } elsif ( defined $group ) {
  794. ($item, $value) = /((?:\w|-)+)\s*=\s*(\S+)/;
  795. # don't unquote backslashes as we just write it back out
  796. if ( defined $item ) {
  797. if ( $item =~ /^password$/ ) {
  798. if ( CheckUnsafeFile($fname) ) {
  799. $unsafeConfig = $fname;
  800. }
  801. }
  802. if ( $group eq 'client' ) {
  803. $MYSQL_CNF{'mysql'}{$item} = $value;
  804. $MYSQL_CNF{'mysqldump'}{$item} = $value;
  805. } else {
  806. $MYSQL_CNF{$group}{$item} = $value;
  807. }
  808. }
  809. }
  810. }
  811. close(CNF);
  812. }
  813. }
  814. # =================================
  815. # sub MergeConfigFiles
  816. # merge options from config files
  817. # NOTE: really should do two separate merges for each
  818. # client to exactly duplicate order of resulting argument lists
  819. # =================================
  820. sub MergeConfigFiles {
  821. my ($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) = getpwuid $<;
  822. MergeConfigFile("/etc/my.cnf");
  823. MergeConfigFile("$dir/.my.cnf");
  824. }
  825. # =================================
  826. # sub WriteTempConfigFile
  827. # write
  828. # =================================
  829. sub WriteTempConfigFile {
  830. sysopen CNFFILE, $MYSQL_CNF, O_RDWR|O_CREAT|O_EXCL, 0700
  831. or die "sysopen $MYSQL_CNF: $!";
  832. # groups may be in any order, generic groups such as [client] assumed
  833. # here to be empty
  834. foreach $group (keys %MYSQL_CNF) {
  835. print CNFFILE "[$group]\n";
  836. foreach $item (keys %{$MYSQL_CNF{$group}}) {
  837. if ( defined $MYSQL_CNF{$group}{$item} ) {
  838. print CNFFILE "$item=$MYSQL_CNF{$group}{$item}\n";
  839. } else {
  840. print CNFFILE "$item\n";
  841. }
  842. }
  843. print CNFFILE "\n";
  844. }
  845. close(CNFFILE);
  846. }
  847. ######################################################################
  848. package MySQLaccess::DB;
  849. ###########
  850. BEGIN {
  851. $DEBUG = 2;
  852. $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG);
  853. # Error-messages from the MySQL client
  854. %ACCESS_ERR= ('Access_denied' => 'Access denied'
  855. ,'Dbaccess_denied' => 'Access to database denied'
  856. ,'Unrecognized_option' => 'unrecognized option'
  857. ,'Unknown_table' => "Can't find file:"
  858. ,'unknown_error' => '^ERROR:'
  859. );
  860. }
  861. # ######################################
  862. # Connecting to the MYSQL DB
  863. # ======================================
  864. # sub OpenConnection
  865. # Open an connection to the mysql-db
  866. # questions to MYSQL_Q
  867. # answers from MYSQL_A
  868. # ======================================
  869. sub OpenConnection {
  870. my $pid;
  871. MySQLaccess::Debug::Print(2,"OpenConnection:");
  872. # check path to mysql-client executable
  873. if (! -f $MySQLaccess::MYSQL) {
  874. if ($MySQLaccess::CMD) { die "Could not find MySQL-client '$MySQLaccess::MYSQL'"; }
  875. if ($MySQLaccess::CGI) {
  876. print "<center>\n<font color=Red>\n";
  877. print "ERROR: Could not find MySQL-client '$MySQLaccess::MYSQL'";
  878. print "</center>\n</font>\n";
  879. exit 0;
  880. }
  881. }
  882. # path to mysql executable
  883. my $connect = "$MySQLaccess::MYSQL --defaults-file=$MySQLaccess::MYSQL_CNF";
  884. $connect .= " $MySQLaccess::MYSQL_OPT";
  885. # superuser, spassword transmitted via defaults-file
  886. if (defined($MySQLaccess::Param{'rhost'})) { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; }
  887. # other options??
  888. # grant-database
  889. $connect .= " $MySQLaccess::ACCESS_DB";
  890. # open connection (not using /bin/sh -c)
  891. MySQLaccess::Debug::Print(2,"Connecting to: $connect");
  892. $pid=IPC::Open3::open3(\*MYSQL_Q,\*MYSQL_A,"",split /\s+/,$connect);
  893. MySQLaccess::Debug::Print(2,"PID of open pipe: $pid");
  894. # check connection
  895. print MYSQL_Q "select 'ok';\n";
  896. $answer = <MYSQL_A>; #answer from mysql
  897. MySQLaccess::Debug::Print(2,"Answer: $answer\n");
  898. foreach $nerror (sort(keys(%ACCESS_ERR))) {
  899. MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  900. if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) {
  901. MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  902. return $nerror;
  903. }
  904. }
  905. if (0) {
  906. # check server-version
  907. print MYSQL_Q "select 'ok';\n";
  908. $answer = <MYSQL_A>; #answer from mysql
  909. MySQLaccess::Debug::Print(2,"Answer: $answer\n");
  910. foreach $nerror (sort(keys(%ACCESS_ERR))) {
  911. MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  912. if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) {
  913. MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  914. return $nerror;
  915. }
  916. }
  917. }
  918. my $skip=<MYSQL_A>;
  919. return 0;
  920. }
  921. # ======================================
  922. # sub CloseConnection
  923. # Close the connection to the mysql-db
  924. # ======================================
  925. sub CloseConnection {
  926. close MYSQL_Q;
  927. close MYSQL_A;
  928. }
  929. # ===========================================================
  930. # sub CreateTable($table)
  931. # Create temporary/backup table
  932. # ===========================================================
  933. sub CreateTable {
  934. my $pid;
  935. my ($table,$force) = @_;
  936. my %tables = ( $MySQLaccess::ACCESS_U_TMP => $MySQLaccess::ACCESS_U,
  937. $MySQLaccess::ACCESS_H_TMP => $MySQLaccess::ACCESS_H,
  938. $MySQLaccess::ACCESS_D_TMP => $MySQLaccess::ACCESS_D,
  939. $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,
  940. $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,
  941. $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,
  942. $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,
  943. $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,
  944. $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,
  945. );
  946. my $tbl;
  947. my $query="";
  948. my $delim;
  949. my $skip;
  950. my $create;
  951. my @known_tables=();
  952. # print STDERR "CreateTable($table)\n";
  953. MySQLaccess::Debug::Print(1,"CreateTable($table):");
  954. ## error-handling
  955. return 'Unknown_table' unless defined($tables{$table});
  956. ## build list of known/existing tables;
  957. ## if 'force' existing table is dropped first
  958. if (defined($force) and $force) {
  959. @known_tables = Show_Tables();
  960. if (grep(/^$table$/,@known_tables)) {
  961. $query = "DROP TABLE $table;";
  962. }
  963. }
  964. ## path to mysqldump executable
  965. my $connect = $MySQLaccess::MYSQLDUMP;
  966. $connect .= " --defaults-file=$MySQLaccess::MYSQL_CNF --no-data";
  967. # superuser, spassword transmitted via defaults-file
  968. if (defined($MySQLaccess::Param{'rhost'})) { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; }
  969. $connect .= " $MySQLaccess::ACCESS_DB";
  970. $connect .= " $tables{$table}";
  971. ## get creation-data for original table
  972. $create = '';
  973. my $mysqldump = $connect;
  974. $mysqldump =~ s/ \$TABLE / $tbl /;
  975. # open connection (not using /bin/sh -c)
  976. MySQLaccess::Debug::Print(2,"Connecting to: $connect");
  977. $pid=IPC::Open3::open3(\*DONTCARE,\*CREATE,"",split /\s+/,$mysqldump);
  978. MySQLaccess::Debug::Print(2,"PID of open pipe: $pid");
  979. #open(CREATE,"$mysqldump");
  980. @create = <CREATE>;
  981. $create = "@create";
  982. foreach $nerror (sort(keys(%ACCESS_ERR))) {
  983. MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  984. if (grep(/$ACCESS_ERR{$nerror}/i,$create)) {
  985. MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  986. return $nerror;
  987. }
  988. }
  989. close(CREATE);
  990. close(DONTCARE);
  991. ## manipulate result for creation-data for temporary table
  992. $create =~ s/CREATE TABLE $tables{$table} \(/CREATE TABLE $table \(/;
  993. ## recreate temporary table
  994. $query .= "$create\n";
  995. $query .= "select 'ok';";
  996. ## execute query
  997. print MYSQL_Q "$query\n";
  998. # print STDERR $query;
  999. $answer = <MYSQL_A>; #answer from mysql
  1000. # print STDERR "A>",$answer;
  1001. MySQLaccess::Debug::Print(2,"Answer: $answer\n");
  1002. foreach $nerror (sort(keys(%ACCESS_ERR))) {
  1003. # print STDERR "->$nerror?";
  1004. MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  1005. if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) {
  1006. # print STDERR "Yes!";
  1007. MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  1008. return $nerror;
  1009. }
  1010. }
  1011. $delim = <MYSQL_A>; # read header
  1012. if ($delim ne "ok\n") {
  1013. while (($line=<MYSQL_A>) ne "ok\n")
  1014. { MySQLaccess::Debug::Print(3," A> $line"); }
  1015. $skip = <MYSQL_A>; # skip result 'ok'
  1016. }
  1017. # print STDERR "CreateTable done\n";
  1018. return 0;
  1019. }
  1020. # ===========================================================
  1021. # sub CopyTable()
  1022. # Copy the structure and the data of a table to another table
  1023. # ===========================================================
  1024. sub CopyTable {
  1025. my ($from,$to,$force) = @_;
  1026. my @known_tables = Show_Tables();
  1027. my $query = "";
  1028. my $nerror= 0;
  1029. my $skip;
  1030. # print STDERR "CopyTable($from,$to)\n";
  1031. MySQLaccess::Debug::Print(1,"MySQLaccess::DB::CopyTable($from,$to)");
  1032. ## error-handling
  1033. if (!grep(/^$from$/,@known_tables)) { return 'Unknown_table'; }
  1034. ## copy structure
  1035. ## if forced
  1036. if (defined($force) and $force) {
  1037. return $nerror if ($nerror=CreateTable($to,$force));
  1038. # print STDERR "Structure copied\n";
  1039. }
  1040. ## copy data
  1041. $query .= "DELETE FROM $to;";
  1042. $query .= "INSERT INTO $to SELECT * FROM $from;";
  1043. $query .= "SELECT 'ok';\n";
  1044. MySQLaccess::Debug::Print(2,"Query: $query");
  1045. ## execute query
  1046. print MYSQL_Q "$query\n";
  1047. # print STDERR $query;
  1048. ## check for errors...
  1049. my $answer = <MYSQL_A>; #answer from mysql
  1050. # print STDERR $answer;
  1051. MySQLaccess::Debug::Print(2,"Answer: $answer\n");
  1052. foreach $nerror (sort(keys(%ACCESS_ERR))) {
  1053. MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}");
  1054. if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) {
  1055. MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]");
  1056. return $nerror;
  1057. }
  1058. }
  1059. my $delim = <MYSQL_A>; # read header
  1060. # print STDERR $delim;
  1061. if ($delim ne "ok\n") {
  1062. while (($line=<MYSQL_A>) ne "ok\n")
  1063. { MySQLaccess::Debug::Print(3," A> $line"); }
  1064. $skip = <MYSQL_A>; # skip result 'ok'
  1065. }
  1066. return 0;
  1067. }
  1068. # ===========================================================
  1069. # sub LoadTmpTables()
  1070. # (Re)load temporary tables with entries of ACL-tables
  1071. # ===========================================================
  1072. sub LoadTmpTables {
  1073. my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,
  1074. $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,
  1075. $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,
  1076. );
  1077. my $tbl;
  1078. my $nerror;
  1079. # print STDERR "LoadTmpTables:\n";
  1080. MySQLaccess::Debug::Print(1,"LoadTmpTables():");
  1081. foreach $tbl (keys(%tables)) {
  1082. # print STDERR "$tbl -> $tables{$tbl}\n";
  1083. MySQLaccess::Debug::Print(2,"Loading table $tbl -> $tables{$tbl}.");
  1084. return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1085. }
  1086. return 0;
  1087. }
  1088. # ===========================================================
  1089. # sub BackupGrantTables()
  1090. # Make a backup of the original grant-tables
  1091. # ===========================================================
  1092. sub BackupGrantTables {
  1093. my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,
  1094. $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,
  1095. $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,
  1096. );
  1097. my $tbl;
  1098. my $nerror;
  1099. # print STDERR "BackupGrantTables:\n";
  1100. MySQLaccess::Debug::Print(1,"BackupGrantTables():");
  1101. foreach $tbl (keys(%tables)) {
  1102. # print STDERR "$tbl -> $tables{$tbl}\n";
  1103. MySQLaccess::Debug::Print(2,"Backup table $tbl -> $tables{$tbl}.");
  1104. return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1105. }
  1106. return 0;
  1107. }
  1108. # ===========================================================
  1109. # sub RollbackGrantTables()
  1110. # Rollback the backup of the grant-tables
  1111. # ===========================================================
  1112. sub RollbackGrantTables {
  1113. my %tables = ( $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,
  1114. $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,
  1115. $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,
  1116. );
  1117. my $tbl;
  1118. my $nerror;
  1119. # print STDERR "RollbackGrantTables:\n";
  1120. MySQLaccess::Debug::Print(1,"RollbackGrantTables():");
  1121. foreach $tbl (keys(%tables)) {
  1122. # print STDERR "$tbl -> $tables{$tbl}\n";
  1123. MySQLaccess::Debug::Print(2,"Rollback table $tbl -> $tables{$tbl}.");
  1124. return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));
  1125. }
  1126. return 0;
  1127. }
  1128. # ===========================================================
  1129. # sub CommitGrantTables()
  1130. # Copy grant-rules from temporary tables to the ACL-tables
  1131. # ===========================================================
  1132. sub CommitGrantTables {
  1133. my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,
  1134. $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,
  1135. $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,
  1136. );
  1137. my $tbl;
  1138. my $query;
  1139. my $delim;
  1140. my $skip;
  1141. my $create;
  1142. print STDERR "CommitGrantTables()\n";
  1143. MySQLaccess::Debug::Print(1,"CommitGrantTables():");
  1144. ## Make backup of original grant-tables
  1145. MySQLaccess::Debug::Print(2,"Making backup of original grant-tables...");
  1146. BackupGrantTables();
  1147. ## Copy data from temporay tables to grant-tables
  1148. foreach $tbl (keys(%tables)) {
  1149. print STDERR "$tbl -> $tables{$tbl}\n";
  1150. MySQLaccess::Debug::Print(2,"Loading data $tables{$tbl} -> $tbl.");
  1151. return $nerror if ($nerror=CopyTable($tables{$tbl},$tbl));
  1152. }
  1153. return 0;
  1154. }
  1155. # ===========================================================
  1156. # sub Show_Fields($table):
  1157. # return (a reference to) a hash which holds the names
  1158. # of all relevant grant-fields, with their index in the record,
  1159. # and (a reference to) an array which holds the fieldnames.
  1160. # ===========================================================
  1161. sub Show_Fields {
  1162. my ($table) = @_;
  1163. my %skip = ('host' => [0,1]
  1164. ,'user' => [0,1,2]
  1165. ,'db' => [0,1,2]
  1166. );
  1167. my %Struct = ();
  1168. my @Struct = ();
  1169. my $query = "show fields from $table;select 'ok';\n";
  1170. my $i=0;
  1171. my $line;
  1172. #print STDERR $query;
  1173. MySQLaccess::Debug::Print(1,"Show_Fields($table):");
  1174. MySQLaccess::Debug::Print(2,"SQL: $query");
  1175. print MYSQL_Q "$query";
  1176. my $skip = <MYSQL_A>; #skip header
  1177. while (($line=<MYSQL_A>) ne "ok\n")
  1178. {
  1179. #print STDERR ">",$line;
  1180. chop($line);
  1181. MySQLaccess::Debug::Print(2," $table>: $line");
  1182. my ($field,$type,$null,$key,$default,$extra) = split(' ',$line);
  1183. $field = ucfirst($field);
  1184. MySQLaccess::Debug::Print(3, " <split: $field - $type - $null - $key - $default - $extra");
  1185. if (! grep(/$i/,@{$skip{$table}}) ){
  1186. $Struct{$field} = $i; #hash
  1187. push(@Struct,$field); #array
  1188. MySQLaccess::Debug::Print(3," ==> added column[$i]: $field ($Struct{$field})");
  1189. }
  1190. else {
  1191. MySQLaccess::Debug::Print(3," ==> skipped column[$i], value=[$field]");
  1192. }
  1193. $i++;
  1194. }
  1195. $skip=<MYSQL_A>; # Get ok row (found already ok header)
  1196. MySQLaccess::Debug::Print(2, "Array:");
  1197. foreach $field (@Struct) { MySQLaccess::Debug::Print(2,"+ $field"); }
  1198. MySQLaccess::Debug::Print(2,"Hash:");
  1199. foreach $field (keys(%Struct)) { MySQLaccess::Debug::Print(2,"+ $field -> $Struct{$field}"); }
  1200. return (\%Struct,\@Struct);
  1201. }
  1202. # ===========================================================
  1203. # sub Show_Tables():
  1204. # return (a reference to) an array which holds all
  1205. # known tables.
  1206. # ===========================================================
  1207. sub Show_Tables {
  1208. my @Tables = ();
  1209. my $query = "show tables;select 'ok';\n";
  1210. my $i=0;
  1211. my $line;
  1212. MySQLaccess::Debug::Print(1,"Show_Tables():");
  1213. MySQLaccess::Debug::Print(2,"SQL: $query");
  1214. print MYSQL_Q "$query";
  1215. my $skip = <MYSQL_A>; #skip header
  1216. while (($line=<MYSQL_A>) ne "ok\n")
  1217. {
  1218. chop($line);
  1219. push(@Tables,$line); #array
  1220. MySQLaccess::Debug::Print(3," ==> added table: $line");
  1221. }
  1222. $skip=<MYSQL_A>; # Get ok row (found already ok header)
  1223. MySQLaccess::Debug::Print(2, "Array:");
  1224. foreach $tbl (@Tables) { MySQLaccess::Debug::Print(2,"+ $tbl"); }
  1225. return @Tables;
  1226. }
  1227. # ======================================
  1228. # sub Validate_Password($passwd,$host,$user,$encpw)
  1229. # Validate the given password
  1230. # for user '$user'
  1231. # connecting from host '$host'
  1232. # ======================================
  1233. sub Validate_Password {
  1234. my ($password,$host,$user,$encpw) = @_;
  1235. my $valid=0;
  1236. MySQLaccess::Debug::Print(1,"Validate_Password($password,$host,$user,$encpw)");
  1237. my $sql = "select host,user,password from user having "
  1238. ."host='$host' and user='$user' and password='$encpw' "
  1239. ."and password=PASSWORD('$password');\n";
  1240. $sql .= "select 'ok';\n";
  1241. MySQLaccess::Debug::Print(2,"SQL = $sql");
  1242. print MYSQL_Q "$sql";
  1243. # if password is valid, at least 1 row returns before we read 'ok'
  1244. while ( ($line=<MYSQL_A>) ne "ok\n") {
  1245. MySQLaccess::Debug::Print(2," A> $line");
  1246. $valid = defined($line);
  1247. }
  1248. my $skip = <MYSQL_A>; # read 'ok'
  1249. return $valid;
  1250. }
  1251. # ==========================================================
  1252. # sub Sort_fields: (rewritten by psmith)
  1253. # Build the query for an ordered list of entries
  1254. # ==========================================================
  1255. sub Sort_fields {
  1256. my ($start, $end, $sofar, $this, @rest) = (@_);
  1257. my @where = ("((FIELD not like '\\%') AND (FIELD <> ''))",
  1258. "((FIELD like '%\\%%') OR (FIELD like '%\\_%'))",
  1259. "(FIELD = '')");
  1260. my $res = '';
  1261. $this or return ("$start $sofar $end");
  1262. $sofar .= ' AND ' if $sofar;
  1263. foreach $w (@where) {
  1264. my $f = $w;
  1265. $f =~ s/FIELD/$this/g;
  1266. $res .= Sort_fields($start, $end, "$sofar$f", @rest);
  1267. }
  1268. return ($res);
  1269. }
  1270. # ===========================================================
  1271. # sub Sort_table: (rewritten by psmith)
  1272. # return all entries in the given table,
  1273. # in an ordered fashion
  1274. # ===========================================================
  1275. sub Sort_table {
  1276. my ($tbl, @order) = @_;
  1277. my @res=();
  1278. # as long as there's no full where clause (Distrib 3.20)...
  1279. # use having :-(
  1280. # NOTE: this clause WILL NOT work on 3.21, because of the
  1281. # order of 'ORDER BY' and 'HAVING'
  1282. my $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl ";
  1283. $start .= 'ORDER BY ' . join(',', @order) ." HAVING ";
  1284. my $end = ";\n";
  1285. # server version 3.21 has a full where clause :-)
  1286. if ($MySQLaccess::Host::SERVER >= '3.21') {
  1287. # print "+++USING FULL WHERE CLAUSE+++\n";
  1288. $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl WHERE ";
  1289. $end = ' ORDER BY ' . join(',', @order) . ";\n";
  1290. }
  1291. MySQLaccess::Debug::Print(1,"Sort_table():");
  1292. MySQLaccess::Debug::Print(2,"Sorting table $tbl by `@order'");
  1293. my $tmp;
  1294. foreach $tmp (@order)
  1295. {
  1296. $tmp="UCASE(host)" if ($tmp eq "ucase_host");
  1297. }
  1298. my $query = Sort_fields($start, $end, '', @order);
  1299. $query .= "select 'ok';\n";
  1300. MySQLaccess::Debug::Print(2,"Query: $query");
  1301. print MYSQL_Q "$query\n";
  1302. my $delim = <MYSQL_A>; # read header
  1303. MySQLaccess::Debug::Print(3," A> $delim");
  1304. if ($delim ne "ok\n") {
  1305. if ($delim =~ /^ERROR/) {
  1306. push(@MySQLaccess::Grant::Error,'use_old_server');
  1307. MySQLaccess::Report::Print_Error_Messages() ;
  1308. exit 1;
  1309. }
  1310. while (($line=<MYSQL_A>) ne "ok\n")
  1311. {
  1312. MySQLaccess::Debug::Print(3," A> $line");
  1313. push(@res,$line);
  1314. }
  1315. }
  1316. my $skip = <MYSQL_A>; # skip result 'ok'
  1317. # remove columnheaders from output
  1318. @res = grep(!/^\Q$delim\E$/, @res);
  1319. # remove trailing \n from each returned record
  1320. chomp(@res);
  1321. # each record has 1 field to much : ucase_host
  1322. @res = grep { /(.*)\t.*$/; $_ = $1; } @res;
  1323. MySQLaccess::Debug::Print(2,"Result of sorted table $tbl:");
  1324. foreach $line (@res) { MySQLaccess::Debug::Print(2," >>$line"); }
  1325. return @res;
  1326. }
  1327. # ===========================================================
  1328. # sub Get_All_db(template):
  1329. # return all db the grant-tables are working on,
  1330. # which conform to the template
  1331. # ===========================================================
  1332. sub Get_All_dbs {
  1333. my ($template,$tmp) = @_;
  1334. my @db=();
  1335. my $aref;
  1336. # working with temporary tables or production tables
  1337. if (defined($tmp) and $tmp) {
  1338. $aref = \@MySQLaccess::Grant::sorted_db_tmp_table ;
  1339. }
  1340. else {
  1341. $aref = \@MySQLaccess::Grant::sorted_db_table;
  1342. }
  1343. MySQLaccess::Debug::Print(1," template=[$template]");
  1344. # get all db for which access-rights can be calculated,
  1345. # which conform to the template.
  1346. # !! these db's don't have to exist yet, so it's not
  1347. # enough to look which db already exist on the system
  1348. $reg_expr = $template;
  1349. if ($template =~ /[\*\?]/) {
  1350. $reg_expr =~ tr/*?/%_/;
  1351. #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1352. }
  1353. $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1354. if ( ! ($template =~ /[\*\?%_]/) ) {
  1355. push(@db,$template);
  1356. return \@db;
  1357. }
  1358. MySQLaccess::Debug::Print(2,"#Reading db-table...");
  1359. foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_db_table) {
  1360. my @record=split(/\t/,$record);
  1361. my $db = $record[1];
  1362. MySQLaccess::Debug::Print(2,"> $db ");
  1363. if ( (!grep(/$db/i,@db)) and ($db =~/$reg_expr/i) ) {
  1364. push(@db,$db);
  1365. MySQLaccess::Debug::Print(2,"added");
  1366. }
  1367. else {
  1368. MySQLaccess::Debug::Print(2,"skipped");
  1369. }
  1370. }
  1371. # if no rule is found for a certain db in the db-table,
  1372. # the rights of the user are used, so we should inform
  1373. # the user for
  1374. if (!grep(/^%$/,@db)) { push(@db,"$MySQLaccess::NEW_DB"); }
  1375. return \@db;
  1376. }
  1377. # ===========================================================
  1378. # sub Get_All_users(template):
  1379. # return all users the grant-tables are working on,
  1380. # which conform to the template
  1381. # ===========================================================
  1382. sub Get_All_users {
  1383. ($template,$tmp) = @_; # nog verder uitwerken!!!
  1384. my @user=();
  1385. my $aref;
  1386. # working with temporary tables or production tables
  1387. if (defined($tmp) and $tmp) {
  1388. $aref = \@MySQLaccess::Grant::sorted_user_tmp_table ;
  1389. }
  1390. else {
  1391. $aref = \@MySQLaccess::Grant::sorted_user_table;
  1392. }
  1393. MySQLaccess::Debug::Print(1,"Debug Get_All_users:");
  1394. # get all db for which access-rights can be calculated.
  1395. # !! these db's don't have to exist yet, so it's not
  1396. # enough to look which db already exist on the system
  1397. $reg_expr = $template;
  1398. if ($template =~ /[\*\?]/) {
  1399. $reg_expr =~ tr/*?/%_/;
  1400. #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1401. }
  1402. $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1403. if ( ! ($template =~ /[\*\?%_]/) ) {
  1404. push(@user,$template);
  1405. return \@user;
  1406. }
  1407. MySQLaccess::Debug::Print(2,"#Reading user-table...");
  1408. foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_user_table) {
  1409. my @record=split(/\t/,$record);
  1410. my $user = $record[1];
  1411. MySQLaccess::Debug::Print(2,"> $user ");
  1412. if ( (!grep(/$user/,@user)) and ($user=~/$reg_expr/)) {
  1413. push(@user,$user);
  1414. MySQLaccess::Debug::Print(2, "added");
  1415. }
  1416. else {
  1417. MySQLaccess::Debug::Print(2, "skipped");
  1418. }
  1419. }
  1420. # Any user means also:
  1421. # - the 'empty' user, ie without supplying a username
  1422. # - any user still to be defined/created
  1423. #push(@user,''); #without_suplying_a_username
  1424. push(@user,"$MySQLaccess::NEW_USER");
  1425. #push(@Warnings,'minimum_priv');
  1426. return \@user;
  1427. }
  1428. # ===========================================================
  1429. # sub Get_All_hosts(template):
  1430. # return all hosts the grant-tables are working on,
  1431. # which conform to the template
  1432. # ===========================================================
  1433. sub Get_All_hosts {
  1434. my ($template,$tmp) = @_;
  1435. my @host=();
  1436. my $aref;
  1437. my $aref1;
  1438. # working with temporary tables or production tables
  1439. if (defined($tmp) and $tmp) {
  1440. $aref = \@MySQLaccess::Grant::sorted_host_tmp_table ;
  1441. $aref1= \@MySQLaccess::Grant::sorted_db_tmp_table ;
  1442. }
  1443. else {
  1444. $aref = \@MySQLaccess::Grant::sorted_host_table;
  1445. $aref1= \@MySQLaccess::Grant::sorted_db_table ;
  1446. }
  1447. MySQLaccess::Debug::Print(1, "Debug Get_All_hosts:");
  1448. # get all db for which access-rights can be calculated.
  1449. # !! these db's don't have to exist yet, so it's not
  1450. # enough to look which db already exist on the system
  1451. $reg_expr = $template;
  1452. if ($template =~ /[\*\?]/) {
  1453. $reg_expr =~ tr/*?/%_/;
  1454. #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);
  1455. }
  1456. $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr");
  1457. if ( ! ($template =~ /[\*\?%_]/) ) {
  1458. push(@host,$template);
  1459. return \@host;
  1460. }
  1461. MySQLaccess::Debug::Print(1, "#Reading db-table...");
  1462. foreach $record (@{$aref1}) { #MySQLaccess::Grant::sorted_db_table) {
  1463. my @record=split(/\t/,$record);
  1464. my $host = $record[0];
  1465. MySQLaccess::Debug::Print(2, "> $host ");
  1466. if (! grep(/$host/i,@host)) {
  1467. push(@host,$host);
  1468. MySQLaccess::Debug::Print(2, "added");
  1469. }
  1470. else {
  1471. MySQLaccess::Debug::Print(2, "skipped");
  1472. }
  1473. }
  1474. MySQLaccess::Debug::Print(1, "#Reading host-table...");
  1475. foreach $record (@{$aref}) {
  1476. my @record=split(/\t/,$record);
  1477. my $host = $record[0];
  1478. MySQLaccess::Debug::Print(2, "> $host ");
  1479. if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {
  1480. push(@host,$host);
  1481. MySQLaccess::Debug::Print(2, "added");
  1482. }
  1483. else {
  1484. MySQLaccess::Debug::Print(2, "skipped");
  1485. }
  1486. }
  1487. # DOUBT:
  1488. #print "#Reading user-table...\n" if ($DEBUG>1);
  1489. #foreach $record (@MySQLaccess::Grant::sorted_user_table) {
  1490. # my @record=split(/\t/,$record);
  1491. # my $host = $record[0];
  1492. # print "> $host " if ($DEBUG>2);
  1493. # if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {
  1494. # push(@host,$host);
  1495. # print "added\n" if ($DEBUG>2);
  1496. # }
  1497. # else {
  1498. # print "skipped\n" if ($DEBUG>2);
  1499. # }
  1500. #}
  1501. # Any host also means:
  1502. # - any host still to be defined/created
  1503. #push(@host,"any_other_host");
  1504. @host = sort(@host);
  1505. return \@host;
  1506. }
  1507. ##########################################################################
  1508. package MySQLaccess::Grant;
  1509. ##############
  1510. BEGIN {
  1511. $DEBUG = 0;
  1512. $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG);
  1513. }
  1514. # ===========================================================
  1515. # sub Diff_Privileges()
  1516. # Calculate diff between temporary and original grant-tables
  1517. # ===========================================================
  1518. sub Diff_Privileges {
  1519. my @before=();
  1520. my @after =();
  1521. my @diffs =();
  1522. # -----------------------------
  1523. # Build list of users,dbs,hosts
  1524. # to process...
  1525. my @all_dbs = @{MySQLaccess::DB::Get_All_dbs('*')};
  1526. my @all_users = @{MySQLaccess::DB::Get_All_users('*')};
  1527. my @all_hosts = @{MySQLaccess::DB::Get_All_hosts('*')};
  1528. #if EDIT-mode
  1529. my @all_dbs_tmp = @{MySQLaccess::DB::Get_All_dbs('*','tmp')};
  1530. my @all_users_tmp = @{MySQLaccess::DB::Get_All_users('*','tmp')};
  1531. my @all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts('*','tmp')};
  1532. my %Access;
  1533. # ------------------------------------
  1534. # Build list of priv. for grant-tables
  1535. foreach $host (@all_hosts) {
  1536. foreach $user (@all_users) {
  1537. foreach $db (@all_dbs) {
  1538. MySQLaccess::Grant::Initialize();
  1539. %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);
  1540. push(@before,MySQLaccess::Report::Raw_Report($host,$user,$db,\%Access));
  1541. }
  1542. }
  1543. }
  1544. # ----------------------------------
  1545. # Build list of priv. for tmp-tables
  1546. foreach $host (@all_hosts_tmp) {
  1547. foreach $user (@all_users_tmp) {
  1548. foreach $db (@all_dbs_tmp) {
  1549. MySQLaccess::Grant::Initialize('tmp');
  1550. %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db,'tmp');
  1551. push(@after,MySQLaccess::Report::Raw_Report($host,$user,$db,\%Access));
  1552. }
  1553. }
  1554. }
  1555. # ----------------------------------
  1556. # Write results to temp-file to make
  1557. # DIFF
  1558. @before = sort(@before);
  1559. @after = sort(@after);
  1560. ($hb, $before) = tempfile("$MySQLaccess::script.XXXXXX") or
  1561. push(@MySQLaccess::Report::Errors,"Can't create temporary file: $!");
  1562. ($ha, $after) = tempfile("$MySQLaccess::script.XXXXXX") or
  1563. push(@MySQLaccess::Report::Errors,"Can't create temporary file: $!");
  1564. print $hb join("\n",@before);
  1565. print $ha join("\n",@after);
  1566. close $hb;
  1567. close $ha;
  1568. # ----------------------------------
  1569. # compute difference
  1570. my $cmd="$MySQLaccess::DIFF $before $after |";
  1571. open(DIFF,"$cmd");
  1572. @diffs = <DIFF>;
  1573. @diffs = grep(/[<>]/,@diffs);
  1574. chomp(@diffs);
  1575. close(DIFF);
  1576. # ----------------------------------
  1577. # cleanup temp. files
  1578. unlink($before);
  1579. unlink($after);
  1580. return \@diffs;
  1581. }
  1582. # ===========================================================
  1583. # sub Initialize()
  1584. #
  1585. # ===========================================================
  1586. sub Initialize {
  1587. %MySQLaccess::Grant::Access = %{Default_Access_Rights()};
  1588. @MySQLaccess::Grant::Errors = ();
  1589. @MySQLaccess::Grant::Warnings = ();
  1590. @MySQLaccess::Grant::Notes = ();
  1591. # -----
  1592. # rules
  1593. $MySQLaccess::Grant::Rules{'user'} = 'no_rule_found';
  1594. $MySQLaccess::Grant::Rules{'db'} = 'no_rule_found';
  1595. $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';
  1596. $MySQLaccess::Grant::full_access = 1;
  1597. $MySQLaccess::Grant::process_host_table = 0;
  1598. return 1;
  1599. }
  1600. # ===========================================================
  1601. # sub ReadTables()
  1602. #
  1603. # ===========================================================
  1604. sub ReadTables {
  1605. my ($tmp) = @_;
  1606. my ($HOST,$DB,$USER);
  1607. my @tables;
  1608. # build list of available tables
  1609. @tables = MySQLaccess::DB::Show_Tables();
  1610. # reading production grant-tables or temporary tables?
  1611. $tmp = (defined($tmp) and $tmp) ? 1 : 0;
  1612. if ($tmp) { #reading temporary tables
  1613. $HOST=$MySQLaccess::ACCESS_H_TMP;
  1614. $DB =$MySQLaccess::ACCESS_D_TMP;
  1615. $USER=$MySQLaccess::ACCESS_U_TMP;
  1616. # ----------------------------
  1617. # do tables exist?
  1618. if (!grep(/$HOST/,@tables)) { MySQLaccess::DB::CreateTable($HOST); }
  1619. if (!grep(/$USER/,@tables)) { MySQLaccess::DB::CreateTable($USER); }
  1620. if (!grep(/$DB/,@tables)) { MySQLaccess::DB::CreateTable($DB); }
  1621. MySQLaccess::Debug::Print(1,"Finding fields in tmp-ACL files:");
  1622. # -----------------------------
  1623. # Get record-layout
  1624. my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);
  1625. my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);
  1626. my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);
  1627. %MySQLaccess::Grant::H_tmp = %{$h1}; @MySQLaccess::Grant::H_tmp = @{$h2};
  1628. %MySQLaccess::Grant::D_tmp = %{$d1}; @MySQLaccess::Grant::D_tmp = @{$d2};
  1629. %MySQLaccess::Grant::U_tmp = %{$u1}; @MySQLaccess::Grant::U_tmp = @{$u2};
  1630. # @MySQLaccess::Grant::Privileges_tmp=@{Make_Privlist()};
  1631. #
  1632. MySQLaccess::Debug::Print(1, "Reading sorted temp-tables:");
  1633. @MySQLaccess::Grant::sorted_db_tmp_table = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');
  1634. @MySQLaccess::Grant::sorted_host_tmp_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');
  1635. @MySQLaccess::Grant::sorted_user_tmp_table= defined($MySQLaccess::Param{'password'}) ?
  1636. MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):
  1637. MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');
  1638. }
  1639. else { #reading production grant-tables
  1640. $HOST=$MySQLaccess::ACCESS_H;
  1641. $DB =$MySQLaccess::ACCESS_D;
  1642. $USER=$MySQLaccess::ACCESS_U;
  1643. MySQLaccess::Debug::Print(1,"Finding fields in ACL files:");
  1644. # -----------------------------
  1645. # Get record-layout
  1646. my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);
  1647. my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);
  1648. my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);
  1649. %MySQLaccess::Grant::H = %{$h1}; @MySQLaccess::Grant::H = @{$h2};
  1650. %MySQLaccess::Grant::D = %{$d1}; @MySQLaccess::Grant::D = @{$d2};
  1651. %MySQLaccess::Grant::U = %{$u1}; @MySQLaccess::Grant::U = @{$u2};
  1652. @MySQLaccess::Grant::Privileges=@{Make_Privlist()};
  1653. MySQLaccess::Debug::Print(1, "Reading sorted tables:");
  1654. @MySQLaccess::Grant::sorted_db_table = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');
  1655. @MySQLaccess::Grant::sorted_host_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');
  1656. @MySQLaccess::Grant::sorted_user_table= defined($MySQLaccess::Param{'password'}) ?
  1657. MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):
  1658. MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');
  1659. }
  1660. return 0;
  1661. }
  1662. # ===========================================================
  1663. # sub Get_Access_Rights(host,user,db)
  1664. # report the access_rights for the tuple ($host,$user,$db).
  1665. # ===========================================================
  1666. sub Get_Access_Rights {
  1667. local ($host,$user,$db,$tmp) = @_;
  1668. my $aref_user;
  1669. my $aref_host;
  1670. my $aref_db;
  1671. # working with temporary tables or production tables
  1672. if (defined($tmp) and $tmp) {
  1673. $aref_user = \@MySQLaccess::Grant::sorted_user_tmp_table;
  1674. $aref_host = \@MySQLaccess::Grant::sorted_host_tmp_table;
  1675. $aref_db = \@MySQLaccess::Grant::sorted_db_tmp_table;
  1676. }
  1677. else {
  1678. $aref_user = \@MySQLaccess::Grant::sorted_user_table;
  1679. $aref_host = \@MySQLaccess::Grant::sorted_host_table;
  1680. $aref_db = \@MySQLaccess::Grant::sorted_db_table;
  1681. }
  1682. my ($refrecord,$refgrant);
  1683. my ($_host_,$_user_,$encpw_);
  1684. my %_Access_;
  1685. MySQLaccess::Debug::Print(1, "for ($host,$user,$db):");
  1686. # ******************************************************************************
  1687. # Create default access-rights
  1688. # default access-rights are no access at all!!
  1689. # ******************************************************************************
  1690. # get hostname for IP-address
  1691. # get IP-address for hostname
  1692. local $host_name = MySQLaccess::Host::IP2Name($host);
  1693. local $host_ip = MySQLaccess::Host::Name2IP($host);
  1694. MySQLaccess::Debug::Print(3,"host=$host, hostname=$host_name, host-ip =$host_ip");
  1695. MySQLaccess::Debug::Print(3,"user=$user");
  1696. MySQLaccess::Debug::Print(3,"db =$db");
  1697. # ***********************************************************************
  1698. # retrieve information on USER
  1699. # check all records in mysql::user for matches with the tuple (host,user)
  1700. # ***********************************************************************
  1701. # 4.OR (add) the privileges for the user from the "user" table.
  1702. # (add all privileges which is "Y" in "user")
  1703. ($refrecord,$refgrant) = Get_grant_from_user($host,$user,$aref_user);
  1704. ($_host_,$_user_,$encpw_) = @{$refrecord};
  1705. %_access_ = %{$refgrant};
  1706. foreach $field (keys(%U)) { ##only priv. set in user-table
  1707. $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});
  1708. }
  1709. if ($_user_ eq $MySQLaccess::NEW_USER) {
  1710. push(@Warnings,'minimum_priv');
  1711. }
  1712. if ($_user_ ne $user) {
  1713. $user=$_user_;
  1714. push(@Warnings,'anonymous_access');
  1715. }
  1716. # *******************************************************
  1717. # Validate password if this has been asked to do
  1718. # *******************************************************
  1719. if (defined($password)) {
  1720. $valid = Validate_Password($password,$_host_,$_user_,$_encpw_,$aref_user);
  1721. if (!$valid) { push(@Errors,'invalid_password'); }
  1722. else { push(@Notes,'valid_password'); }
  1723. }
  1724. # ******************************************************************************
  1725. # retrieve information on DB
  1726. # check all records in mysql::db for matches with the triple (host,db,user)
  1727. # first match is used.
  1728. # ******************************************************************************
  1729. # 2.Get grant for user from the "db" table.
  1730. ($refrecord,$refgrant)=Get_grant_from_db($host,$db,$user,$aref_db); #set process_host_table
  1731. ($_host_,$_user_,$encpw_) = @{$refrecord};
  1732. %_access_ = %{$refgrant};
  1733. foreach $field (keys(%D)) { ##only priv. set in db-table
  1734. $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});
  1735. }
  1736. # ***********************************************************************
  1737. # retrieve information on HOST
  1738. # check all records in mysql::host for matches with the tuple (host,db)
  1739. #
  1740. # ' The host table is mainly to maintain a list of "secure" servers. '
  1741. # ***********************************************************************
  1742. # 3.If hostname is "empty" for the found entry, AND the privileges with
  1743. # the privileges for the host in "host" table.
  1744. # (Remove all which is not "Y" in both)
  1745. if ($MySQLaccess::Grant::process_host_table) {
  1746. ($refrecord,$refgrant)=Get_grant_from_host($host,$db,$aref_host);
  1747. ($_host_,$_user_,$encpw_) = @{$refrecord};
  1748. %_access_ = %{$refgrant};
  1749. foreach $field (keys(%H)) { ##only priv. set in host-table
  1750. $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} and $_access_{$field});
  1751. }
  1752. }
  1753. MySQLaccess::Debug::Print(1,"done for ($host,$user,$db)");
  1754. return %MySQLaccess::Grant::Access;
  1755. }
  1756. # ####################################
  1757. # FINDING THE RIGHT GRANT-RULE
  1758. # ==========================================================
  1759. # sub Get_grant_from_user:
  1760. # ==========================================================
  1761. sub Get_grant_from_user {
  1762. my ($host,$user,$aref) = @_;
  1763. MySQLaccess::Debug::Print(1, "");
  1764. MySQLaccess::Debug::Print(1, "(host=$host,user=$user)");
  1765. my %Access_user = %{Default_Access_Rights()};
  1766. my $rule_found=0;
  1767. my @record = ();
  1768. my $record;
  1769. foreach $record (@{$aref}) {
  1770. $MySQLaccess::Grant::full_access=0;
  1771. MySQLaccess::Debug::Print(3, "Record= $record");
  1772. @record=split(/\t/,$record);
  1773. # check host and db
  1774. # with possible wildcards in field
  1775. # replace mysql-wildcards by reg-wildcards
  1776. my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1777. my $user_tpl = $record[1]; #user field isn't pattern-matched!!
  1778. my $passwd = $record[2];
  1779. MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl");
  1780. MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[1] -> $user_tpl");
  1781. MySQLaccess::Debug::Print(3, "=>password : read=$record[2] -> $passwd");
  1782. if ( MySQLaccess::Host::MatchTemplate($host,$host_tpl) and
  1783. MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user)
  1784. )
  1785. {
  1786. MySQLaccess::Debug::Print(2, "FOUND!!");
  1787. if ($passwd eq '') { push(@Warnings,'insecure_user'); }
  1788. else { push(@Notes,'password_required'); }
  1789. foreach $field (keys(%U)) {
  1790. $Access_user{$field} = $MySQLaccess::Report::Answer{$record[$U{$field}]};
  1791. }
  1792. #print "\n" if $DEBUG;
  1793. $MySQLaccess::Grant::Rules{'user'} = $record;
  1794. $rule_found=1;
  1795. last;
  1796. }
  1797. }
  1798. # -------------------------------
  1799. # setting privileges to user-priv
  1800. MySQLaccess::Debug::Print(2, "Rights after parsing user-table..:");
  1801. if (! $rule_found ) {
  1802. @record=();
  1803. MySQLaccess::Debug::Print(2, "NO record found in the user-table!!");
  1804. }
  1805. else {
  1806. MySQLaccess::Debug::Print(2, "Selected record=@record");
  1807. MySQLaccess::Debug::Print(2, "<=?=> $record");
  1808. }
  1809. MySQLaccess::Debug::Print(1, "returning @record");
  1810. return (\@record,\%Access_user); #matching record in user-table
  1811. }
  1812. # ==========================================================
  1813. # sub Get_grant_from_db:
  1814. # ==========================================================
  1815. sub Get_grant_from_db {
  1816. my ($host,$db,$user,$aref) = @_;
  1817. MySQLaccess::Debug::Print(1, "(host=$host,user=$user,db=$db)");
  1818. my %Access_db = %{Default_Access_Rights()};
  1819. my $rule_found=0;
  1820. foreach $record (@{$aref}) {
  1821. $full_access=0;
  1822. MySQLaccess::Debug::Print(2, "Read db: $record");
  1823. @record=split(/\t/,$record);
  1824. # check host and db
  1825. # with possible wildcards in field
  1826. # replace mysql-wildcards by reg-wildcards
  1827. my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1828. my $db_tpl = MySQLaccess::Wildcards::SQL2Reg($record[1]);
  1829. my $user_tpl = $record[2]; #user field isn't pattern matched!!
  1830. MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl");
  1831. MySQLaccess::Debug::Print(3, "=>db_tpl : read=$record[1] -> $db_tpl");
  1832. MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[2] -> $user_tpl");
  1833. if ( ( MySQLaccess::Host::Is_localhost($host_tpl)
  1834. or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)
  1835. or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )
  1836. and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) )
  1837. and ( MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user) ) ) {
  1838. $MySQLaccess::Grant::process_host_table = ($record[0] eq '');
  1839. if ($user_tpl eq '') { push(@Warnings,'public_database'); }
  1840. foreach $field (keys(%D)) {
  1841. $Access_db{$field} = $MySQLaccess::Report::Answer{$record[$D{$field}]};
  1842. }
  1843. $rule_found=1;
  1844. $MySQLaccess::Grant::Rules{'db'} = $record;
  1845. last;
  1846. }
  1847. }
  1848. # -------------------------------
  1849. # setting privileges to db-priv
  1850. MySQLaccess::Debug::Print(2, "Rights after parsing db-table..:");
  1851. if (! $rule_found ) {
  1852. MySQLaccess::Debug::Print(2, "NO rule found in db-table => no access granted!!");
  1853. }
  1854. return (\@record,\%Access_db);
  1855. }
  1856. # ==========================================================
  1857. # sub Get_grant_from_host:
  1858. # ==========================================================
  1859. sub Get_grant_from_host {
  1860. my ($host,$db,$aref) = @_;
  1861. MySQLaccess::Debug::Print(1, "Get_grant_from_host()");
  1862. my %Access_host = %{Default_Access_Rights()};
  1863. # the host-table doesn't have to be processed if the host-field
  1864. # in the db-table isn't empty
  1865. if (!$MySQLaccess::Grant::process_host_table) {
  1866. MySQLaccess::Debug::Print(2, ">> Host-table doesn't have to be processed!!");
  1867. $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';
  1868. return ([],\%Access_host);
  1869. }
  1870. my $rule_found=0;
  1871. my @record = ();
  1872. foreach $record (@{$aref}) {
  1873. $full_access=0;
  1874. MySQLaccess::Debug::Print(2, "host: $record");
  1875. @record=split(/\t/,$record);
  1876. # check host and db
  1877. # with possible wildcards in field
  1878. # replace mysql-wildcards by reg-wildcards
  1879. my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);
  1880. my $db_tpl = MySQLaccess::Wildcards::SQL2Reg($record[1]);
  1881. MySQLaccess::Debug::Print(3, "=>host_tpl : $record[0] -> $host_tpl");
  1882. MySQLaccess::Debug::Print(3, "=>db_tpl : $record[1] -> $db_tpl");
  1883. if ( ( MySQLaccess::Host::Is_localhost($host_tpl)
  1884. or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)
  1885. or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )
  1886. and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) ) ) {
  1887. $MySQLaccess::Grant::Rules{'host'} = $record;
  1888. $rule_found=1;
  1889. foreach $field (keys(%H)) {
  1890. $Access_host{$field} = $MySQLaccess::Report::Answer{$record[$H{$field}]};
  1891. }
  1892. last;
  1893. }
  1894. }
  1895. # -------------------------------
  1896. # setting privileges to host-priv
  1897. MySQLaccess::Debug::Print(2, "Rights after parsing host-table..:");
  1898. if (! $rule_found ) {
  1899. @record=();
  1900. MySQLaccess::Debug::Print(2, "NO restrictions found in the host-table!!");
  1901. }
  1902. # --------------------------------
  1903. # debugging access-rights in db
  1904. return (\@record,\%Access_host); #matching record in host-table
  1905. }
  1906. # ===========================================================
  1907. # sub Default_Access_Rights():
  1908. # return (a reference to) a hash which holds all default
  1909. # priviliges currently defined in the grant-tables.
  1910. # ===========================================================
  1911. sub Default_Access_Rights {
  1912. my %right = ();
  1913. MySQLaccess::Debug::Print(2, "Debug Default_Access_Rights():");
  1914. # add entry for all fields in the HOST-table
  1915. foreach $field (keys(%MySQLaccess::Grant::H)) {
  1916. $right{$field}='0' unless (defined($right{$field}));
  1917. }
  1918. # add entry for all fields in the DB-table
  1919. foreach $field (keys(%MySQLaccess::Grant::D)) {
  1920. $right{$field}='0' unless (defined($right{$field}));
  1921. }
  1922. # add entry for all fields in the USER-table
  1923. foreach $field (keys(%MySQLaccess::Grant::U)) {
  1924. $right{$field}='0' unless (defined($right{$field}));
  1925. }
  1926. # --------------
  1927. # debugging info
  1928. foreach $field (keys(%right)) { MySQLaccess::Debug::Print(3, sprintf("> %15s : %1s",$field,$right{$field})); }
  1929. return \%right;
  1930. }
  1931. # ======================================
  1932. # sub Make_Privlist
  1933. # Make an ordered list of the privileges
  1934. # that should be reported
  1935. # ======================================
  1936. sub Make_Privlist {
  1937. # layout:
  1938. #'select_priv', 'create_priv',
  1939. #'insert_priv', 'drop_priv',
  1940. #'update_priv', 'reload_priv',
  1941. #'delete_priv', 'process_priv',
  1942. #'file_priv', 'shutdown_priv');
  1943. my $right;
  1944. my @privlist=();
  1945. foreach $right (@U) {
  1946. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1947. };
  1948. foreach $right (@D) {
  1949. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1950. };
  1951. foreach $right (@H) {
  1952. if (! grep(/$right/,@privlist)) { push(@privlist,$right); }
  1953. };
  1954. # print "Privileges:\n";
  1955. # foreach $field (@privlist) { print " > $field\n"; }
  1956. return \@privlist;
  1957. }
  1958. ########################################################################
  1959. package MySQLaccess::Report;
  1960. use Exporter ();
  1961. @EXPORT = qw(&Print_Header());
  1962. BEGIN {
  1963. $FORM = $ENV{'SCRIPT_NAME'};
  1964. $DEBUG = 0;
  1965. $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG);
  1966. # translation-table for poss. answers
  1967. %Answer = ('Y' => 1 , 'N' => 0
  1968. , 1 => 'Y', 0 => 'N'
  1969. ,'?' => '?', '' => '?'
  1970. );
  1971. $headers = 0;
  1972. $separator = 0;
  1973. # ****************************
  1974. # Notes and warnings
  1975. %MESSAGES = (
  1976. 'insecure_user'
  1977. => "Everybody can access your DB as user `\$user' from host `\$host'\n"
  1978. ."WITHOUT supplying a password.\n"
  1979. ."Be very careful about it!!"
  1980. ,'password_required'
  1981. => "A password is required for user `\$user' :-("
  1982. ,'invalid_password'
  1983. => "The password '\$password' for user `\$user' is invalid :-P"
  1984. , 'valid_password'
  1985. => "You supplied the right password for user `\$user' :-)"
  1986. ,'public_database'
  1987. => "Any user with the appropriate permissions has access to your DB!\n"
  1988. ."Check your users!"
  1989. ,'full_access'
  1990. => "All grant-tables are empty, which gives full access to ALL users !!"
  1991. ,'no_rule_found'
  1992. => "No matching rule"
  1993. ,'no_equiv_host'
  1994. => "Not processed: host-field is not empty in db-table."
  1995. ,'least_priv'
  1996. => "If the final priveliges of the user are more then you gave the user,\n"
  1997. ."check the priveliges in the db-table `\$db'."
  1998. ,'minimum_priv'
  1999. => "The privileges for any new user are AT LEAST\n"
  2000. ."the ones shown in the table above,\n"
  2001. ."since these are the privileges of the db `\$db'.\n"
  2002. ,'not_found_mysql'
  2003. => "The MySQL client program <$MySQLaccess::MYSQL> could not be found.\n"
  2004. ."+ Check your path, or\n"
  2005. ."+ edit the source of this script to point \$MYSQL to the mysql client.\n"
  2006. ,'not_found_mysqldump'
  2007. => "The MySQL dump program <$MySQLaccess::MYSQLDUMP> could not be found.\n"
  2008. ."+ Check your path, or\n"
  2009. ."+ edit the source of this script to point \$MYSQLDUMP to the mysqldump program.\n"
  2010. ,'not_found_diff'
  2011. => "The diff program <$MySQLaccess::DIFF> could not be found.\n"
  2012. ."+ Check your path, or\n"
  2013. ."+ edit the source of this script to point \$DIFF to the diff program.\n"
  2014. ,'Unrecognized_option'
  2015. => "Sorry,\n"
  2016. ."You are using an old version of the mysql-program,\n"
  2017. ."which does not yet implement a neccessary option.\n"
  2018. ."\n"
  2019. ."You need at least Version 6.2 of the mysql-client,\n"
  2020. ."which was build in MySQL v3.0.18, to use this version\n"
  2021. ."of `$MySQLaccess::script'."
  2022. ,'Access_denied'
  2023. => "Sorry,\n"
  2024. ."An error occured when trying to connect to the database\n"
  2025. ."with the grant-tables:\n"
  2026. ."* Maybe YOU do not have READ-access to this database?\n"
  2027. ."* If you used the -U option, you may have supplied an invalid username?\n"
  2028. ." for the superuser?\n"
  2029. ."* If you used the -U option, it may be possible you have to supply\n"
  2030. ." a superuser-password to, with the -P option?\n"
  2031. ."* If you used the -P option, you may have supplied an invalid password?\n"
  2032. ,'Dbaccess_denied'
  2033. => "Sorry,\n"
  2034. ."An error occured when trying to connect to the database\n"
  2035. ."with the grant-tables. (dbaccess denied)\n"
  2036. ,'Unknown_tmp_table'
  2037. => "Sorry,\n"
  2038. ."An error occured when trying to work with the temporary tables in the database\n"
  2039. ."with the grant-tables. (One of the temporary tables does not exist)\n"
  2040. ,'Unknown_table'
  2041. => "Sorry,\n"
  2042. ."An error occured when trying to work with some tables in the database\n"
  2043. ."with the grant-tables. (table does not exist)\n"
  2044. ,'use_old_server'
  2045. => "Sorry,\n"
  2046. ."An error occured when executing an SQL statement.\n"
  2047. ."You might consider altering the use of the parameter `--old_server' when \n"
  2048. ."calling `$MySQLaccess::script'."
  2049. ,'unknown_error'
  2050. => "Sorry,\n"
  2051. ."An error occured when trying to connect to the database\n"
  2052. ."with the grant-tables. (unknown error)\n"
  2053. ,'anonymous_access'
  2054. => "Accessing the db as an anonymous user.\n"
  2055. ."Your username has no relevance\n"
  2056. ,'user_required'
  2057. => "You have to supply a userid."
  2058. ,'db_required'
  2059. => "You have to supply the name of a database."
  2060. ,'host_required'
  2061. => "You have to supply the name of a host."
  2062. );
  2063. }
  2064. # =====================================
  2065. # sub Print_Header:
  2066. # print header info
  2067. # =====================================
  2068. sub Print_Header {
  2069. if ($MySQLaccess::CMD) { #command-line mode
  2070. print "$MySQLaccess::script Version $MySQLaccess::VERSION\n"
  2071. ."By RUG-AIV, by Yves Carlier (Yves.Carlier\@rug.ac.be)\n"
  2072. ."Changes by Steve Harvey (sgh\@vex.net)\n"
  2073. ."This software comes with ABSOLUTELY NO WARRANTY.\n";
  2074. }
  2075. if ($MySQLaccess::CGI) { #CGI-BIN mode
  2076. print "content-type: text/html\n\n"
  2077. . "<HTML>\n"
  2078. ."<HEAD>\n"
  2079. ."<TITLE>MySQLaccess</TITLE>\n"
  2080. ."</HEAD>\n"
  2081. ."<BODY>\n"
  2082. ."<H1>$MySQLaccess::script Version $MySQLaccess::VERSION</H1>\n"
  2083. ."<CENTER>\n<ADDRESS>\n"
  2084. ."By RUG-AIV, by Yves Carlier (<a href=mailto:Yves.Carlier\@rug.ac.be>Yves.Carlier\@rug.ac.be</a>)<BR>\n"
  2085. ."Changes by Steve Harvey (<a href=mailto:sgh\@vex.net>sgh\@vex.net</a>)<BR>\n"
  2086. ."This software comes with ABSOLUTELY NO WARRANTY.<BR>\n"
  2087. ."</ADDRESS>\n</CENTER>\n"
  2088. ."<HR>\n";
  2089. Print_Taskbar();
  2090. print "<HR>\n";
  2091. }
  2092. return 1;
  2093. }
  2094. # =====================================
  2095. # sub Print_Footer:
  2096. # print footer info
  2097. # =====================================
  2098. sub Print_Footer {
  2099. if ($MySQLaccess::CMD) { #command-line mode
  2100. print "\n"
  2101. ."BUGs can be reported by email to bugs\@mysql.com\n";
  2102. }
  2103. if ($MySQLaccess::CGI) { #CGI-BIN mode
  2104. if ($MySQLaccess::Param{'brief'}) {
  2105. print "</table>\n"; #close table in brief-output
  2106. }
  2107. print "<HR>\n"
  2108. ."<ADDRESS>\n"
  2109. ."BUGs can be reported by email to <a href=mailto:bugs\@mysql.com>bugs\@mysql.com</a><BR>\n"
  2110. # ."Don't forget to mention the version $VERSION!<BR>\n"
  2111. ."</ADDRESS>\n"
  2112. ."</BODY>\n"
  2113. ."</HTML>\n";
  2114. }
  2115. return 1;
  2116. }
  2117. # =====================================
  2118. # sub Print_Taskbar:
  2119. # print taskbar on STDOUT
  2120. # =====================================
  2121. sub Print_Taskbar {
  2122. print "<CENTER>\n"
  2123. ."[<a href=$FORM?relnotes=on>Release&nbsp;Notes</a>] \n"
  2124. ."[<a href=$FORM?version=on>Version</a>] \n"
  2125. ."[<a href=$FORM?plan=on>Future&nbsp;Plans</a>] \n"
  2126. ."[<a href=$FORM?howto=on>Examples</a>] \n"
  2127. ."[<a href=$FORM?help=on>New check</a>] \n"
  2128. ."[<a href=$FORM?edit=on>Change/edit ACL</a>] \n"
  2129. ."</CENTER>\n";
  2130. return 1;
  2131. }
  2132. # =====================================
  2133. # sub Print_Form:
  2134. # print CGI-form
  2135. # =====================================
  2136. sub Print_Form {
  2137. print <<EOForm;
  2138. <center>
  2139. <!-- Quering -->
  2140. <FORM method=POST action=$FORM>
  2141. <table border width="100%" >
  2142. <tr>
  2143. <th>MySQL server</th>
  2144. <th>User information</th>
  2145. <th>Reports</th>
  2146. </tr>
  2147. <tr>
  2148. <td valign=top>
  2149. <table>
  2150. <tr>
  2151. <td halign=right><b>Host</b><br><font size=-2>(Host on which MySQL-server resides.)</font></td>
  2152. <td valign=top><INPUT name=rhost type=text size=15 maxlength=15 value="$MySQLaccess::Param{'rhost'}"></td>
  2153. </tr>
  2154. <tr>
  2155. <td halign=right><b>Superuser</b><br><font size=-2>(User which has <font color="Red">read-access</font> to grant-tables.)</font></td>
  2156. <td valign=top><INPUT name=superuser type=text size=15 maxlength=15 value="$MySQLaccess::Param{'superuser'}"></td>
  2157. </tr>
  2158. <tr>
  2159. <td halign=right><b>Password</b><br><font size=-2>(of Superuser.)</font></td>
  2160. <td valign=top><INPUT name=spassword type=password size=15 maxlength=15 value="$MySQLaccess::Param{'spassword'}"></td>
  2161. </tr>
  2162. </table>
  2163. </td>
  2164. <td valign=top>
  2165. <table>
  2166. <tr>
  2167. <td halign=right><b><font color=Red>User</font></b><br><font size=-2>(Userid used to connect to MySQL-database.)</font></td>
  2168. <td halign=top><INPUT name=user type=text size=15 maxlength=15 value="$MySQLaccess::Param{'user'}"></td>
  2169. </tr>
  2170. <tr>
  2171. <td halign=right><b>Password</b><br><font size=-2>(Password user has to give to get access to MySQL-database.)</font></td>
  2172. <td valign=top><INPUT name=password type=password size=15 maxlength=15 value="$MySQLaccess::Param{'password'}"></td>
  2173. </tr>
  2174. <tr>
  2175. <td halign=right><b><font color=Red>Database</font></b><br><font size=-2>(Name of MySQL-database user tries to connect to.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td>
  2176. <td valign=top><INPUT name=db type=text size=15 maxlength=15 value="$MySQLaccess::Param{'db'}"></td>
  2177. </tr>
  2178. <tr>
  2179. <td halign=right><b>Host</b><br><font size=-2>(Host from where the user is trying to connect to MySQL-database.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td>
  2180. <td valign=top><INPUT name=host type=text size=15 maxlength=15 value="$MySQLaccess::Param{'host'}"></td>
  2181. </tr>
  2182. </table>
  2183. </td>
  2184. <td valign=center>
  2185. <table cellspacing=5 cellpadding=2 cols=1 height="100%">
  2186. <tr align=center>
  2187. <td halign=right><INPUT type=submit name=brief value="Brief"><br>
  2188. <INPUT type=submit name=table value="Tabular"></td>
  2189. </tr>
  2190. <tr align=center>
  2191. <td></td>
  2192. </tr>
  2193. <tr align=center>
  2194. <td halign=right><INPUT type=reset value="Clear"></td>
  2195. </tr>
  2196. </table>
  2197. </td>
  2198. </tr>
  2199. </table>
  2200. </form>
  2201. </BODY>
  2202. </HTML>
  2203. EOForm
  2204. return 1;
  2205. }
  2206. # =====================================
  2207. # sub Print_Usage:
  2208. # print some information on STDOUT
  2209. # =====================================
  2210. sub Print_Usage {
  2211. Print_Error_Messages();
  2212. if ($MySQLaccess::CMD) { #command-line mode
  2213. Print_Options();
  2214. }
  2215. if ($MySQLaccess::CGI) { #CGI-BIN mode
  2216. Print_Form();
  2217. }
  2218. return 1;
  2219. }
  2220. # ======================================
  2221. # sub Print_Version:
  2222. # ======================================
  2223. sub Print_Version {
  2224. if ($MySQLaccess::CMD) {
  2225. print $MySQLaccess::INFO;
  2226. }
  2227. if ($MySQLaccess::CGI) {
  2228. print "<PRE>\n";
  2229. print $MySQLaccess::INFO;
  2230. print "</PRE>\n";
  2231. }
  2232. return 1;
  2233. }
  2234. # ======================================
  2235. # sub Print_Relnotes:
  2236. # ======================================
  2237. sub Print_Relnotes {
  2238. if ($MySQLaccess::CMD) {
  2239. print $MySQLaccess::RELEASE;
  2240. }
  2241. if ($MySQLaccess::CGI) {
  2242. print "<PRE>\n";
  2243. print $MySQLaccess::RELEASE;
  2244. print "</PRE>\n";
  2245. }
  2246. return 1;
  2247. }
  2248. # ======================================
  2249. # sub Print_Plans:
  2250. # ======================================
  2251. sub Print_Plans {
  2252. if ($MySQLaccess::CMD) {
  2253. print $MySQLaccess::TODO;
  2254. }
  2255. if ($MySQLaccess::CGI) {
  2256. print "<PRE>\n";
  2257. print $MySQLaccess::TODO;
  2258. print "</PRE>\n";
  2259. }
  2260. return 1;
  2261. }
  2262. # ======================================
  2263. # sub Print_HowTo:
  2264. # ======================================
  2265. sub Print_HowTo {
  2266. if ($MySQLaccess::CMD) {
  2267. print $MySQLaccess::HOWTO;
  2268. }
  2269. if ($MySQLaccess::CGI) {
  2270. print "<PRE>\n";
  2271. print $MySQLaccess::HOWTO;
  2272. print "</PRE>\n";
  2273. }
  2274. return 1;
  2275. }
  2276. # ======================================
  2277. # sub Print_Options:
  2278. # ======================================
  2279. sub Print_Options {
  2280. if ($MySQLaccess::CGI) { print "<PRE>\n"; }
  2281. print $MySQLaccess::OPTIONS;
  2282. if ($MySQLaccess::CGI) { print "</PRE>\n"; }
  2283. return 1;
  2284. }
  2285. # ======================================
  2286. # sub Print_Error_Access:
  2287. # ======================================
  2288. sub Print_Error_Access {
  2289. my ($error) = @_;
  2290. print "\n";
  2291. if ($MySQLaccess::CGI) { print "<font color=Red>\n<PRE>\n"; }
  2292. print $MESSAGES{$error};
  2293. if ($MySQLaccess::CGI) { print "</PRE>\n</font>\n"; }
  2294. print "\n";
  2295. return 1;
  2296. }
  2297. # ======================================
  2298. # sub Print_Error_Messages:
  2299. # ======================================
  2300. sub Print_Error_Messages {
  2301. # my ($error) = @_;
  2302. print "\n";
  2303. if ($MySQLaccess::CGI) { print "<font color=Red>\n<center>\n"; }
  2304. foreach $error (@MySQLaccess::Grant::Error) {
  2305. print $MESSAGES{$error};
  2306. print $MySQLaccess::CGI ? "<br>\n" : "\n";
  2307. }
  2308. if ($MySQLaccess::CGI) { print "</center>\n</font>\n"; }
  2309. print "\n";
  2310. return 1;
  2311. }
  2312. # ======================================
  2313. # sub Print_Message:
  2314. # ======================================
  2315. sub Print_Message {
  2316. my ($aref) = @_;
  2317. my @messages = @{$aref};
  2318. print "\n";
  2319. if ($MySQLaccess::CGI) { print "<font color=DarkGreen>\n<center>\n"; }
  2320. foreach $msg (@messages) {
  2321. print $msg;
  2322. print $MySQLaccess::CGI ? "<br>\n" : "\n";
  2323. }
  2324. if ($MySQLaccess::CGI) { print "</center>\n</font>\n"; }
  2325. print "\n";
  2326. return 1;
  2327. }
  2328. # ======================================
  2329. # sub Print_Edit:
  2330. # ======================================
  2331. sub Print_Edit {
  2332. print "\n";
  2333. if (!$MySQLaccess::CGI) {
  2334. print "Note: Editing the temporary tables is NOT supported in CMD-line mode!\n";
  2335. return 0;
  2336. }
  2337. print "<CENTER>\n"
  2338. ."<form action=$FORM method=GET>\n"
  2339. ."<table width=90% border>\n"
  2340. ."<tr>\n"
  2341. ." <td><input type=checkbox name=copy value=on> Copy grant-rules to temporary tables<br></td>\n"
  2342. ." <td rowspan=5 align=center valign=center><input type=submit value=Go></td>\n"
  2343. ."</tr>\n"
  2344. ."<tr>\n"
  2345. ." <td> Edit temporary tables with external application:<br>"
  2346. ." <a href=\"$MySQLaccess::MYSQLADMIN\">$MySQLaccess::MYSQLADMIN</a></td>\n"
  2347. ."</tr>\n"
  2348. ."<tr>\n"
  2349. ." <td><input type=checkbox name=preview value=on> Preview changes made in temporary tables</td>\n"
  2350. ."</tr>\n"
  2351. ."<tr>\n"
  2352. ." <td><input type=checkbox name=commit value=on> Make changes permanent</td>\n"
  2353. ."</tr>\n"
  2354. ."<tr>\n"
  2355. ." <td><input type=checkbox name=rollback value=on> Restore previous grand-rules</td>\n"
  2356. ."</tr>\n"
  2357. ."<tr>\n"
  2358. ." <td colspan=2 align=center><font size=-2 color=Red>You need write,delete and drop-privileges to perform the above actions</font></td>\n"
  2359. ."</tr>\n"
  2360. ."</table>\n"
  2361. ."</form>\n"
  2362. ."</CENTER>\n";
  2363. return 1;
  2364. }
  2365. # ======================================
  2366. # sub Print_Access_rights:
  2367. # print the access-rights on STDOUT
  2368. # ======================================
  2369. sub Print_Access_rights {
  2370. my ($host,$user,$db,$refhash) = @_;
  2371. if (defined($MySQLaccess::Param{'brief'})) {
  2372. # if ($MySQLaccess::CGI) { print "<PRE>\n"; }
  2373. Matrix_Report($host,$user,$db,$refhash);
  2374. # if ($MySQLaccess::CGI) { print "</PRE>\n"; }
  2375. }
  2376. else {
  2377. Tabular_Report($host,$user,$db,$refhash);
  2378. $MySQLaccess::Report::separator = $MySQLaccess::CGI ? "<hr>" : "-"x80;
  2379. }
  2380. return 1;
  2381. }
  2382. # ======================================
  2383. # sub Print_Diff_ACL:
  2384. # print the diff. in the grants before and after
  2385. # ======================================
  2386. sub Print_Diff_ACL {
  2387. my ($aref) = @_;
  2388. my @diffs = @{$aref};
  2389. my %block = ( '<' => 'Before',
  2390. '>' => 'After',
  2391. );
  2392. my %color = ( '<' => 'Green',
  2393. '>' => 'Red',
  2394. );
  2395. my $curblock = '';
  2396. # -----------------------------
  2397. # create column-headers
  2398. foreach $field (@MySQLaccess::Grant::Privileges) {
  2399. push(@headers,substr($field,0,4));
  2400. }
  2401. if ($MySQLaccess::CMD) {
  2402. print "\n";
  2403. print "Differences in access-rights BEFORE and AFTER changes in grant-tables\n";
  2404. # print "---------------------------------------------------------------------\n";
  2405. my $line1="";
  2406. my $line2="";
  2407. $line1 .= sprintf("| %-30s|",'Host,User,DB');
  2408. $line2 .= sprintf("+-%-30s+",'-' x 30);
  2409. foreach $header (@headers) {
  2410. $line1 .= sprintf("%-4s|",$header);
  2411. $line2 .= sprintf("%s+",'----');
  2412. }
  2413. print "$line2\n";
  2414. print "$line1\n";
  2415. print "$line2\n";
  2416. $format = "format STDOUT = \n"
  2417. . "^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " . " @|||" x 10 ."\n"
  2418. . '$host_user_db,@priv' . "\n"
  2419. . ".\n";
  2420. #print $format;
  2421. eval $format;
  2422. }
  2423. if ($MySQLaccess::CGI) {
  2424. print "<table border width=100%>\n";
  2425. print "<tr>\n";
  2426. print "<th colspan=11>";
  2427. print "Differences in access-rights <font color=$color{'<'}>BEFORE</font> "
  2428. ."and <font color=$color{'>'}>AFTER</font> changes to grant-tables</font>\n";
  2429. print "</th>";
  2430. print "</tr>\n";
  2431. print "<tr>\n";
  2432. $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB');
  2433. foreach $header (@headers) {
  2434. $line1 .= sprintf("<th>%-4s</th>",$header);
  2435. }
  2436. print "$line1</tr>\n";
  2437. }
  2438. foreach $line (@diffs) {
  2439. $type = substr($line,0,1);
  2440. $line = substr($line,1);
  2441. ($host,$user,$db,@priv) = split(/,/,$line);
  2442. if ($MySQLaccess::CMD) {
  2443. if ($type ne $curblock) {
  2444. $curblock = $type;
  2445. print $block{$curblock},":\n";
  2446. }
  2447. #print "$line\n";
  2448. write;
  2449. }
  2450. if ($MySQLaccess::CGI) {
  2451. if ($type ne $curblock) {
  2452. $curblock = $type;
  2453. print "<tr><td><b>$block{$curblock}<b></td></tr>\n";
  2454. }
  2455. $line1="<td><font color=$color{$type}>$host, $user, $db</font></td>";
  2456. foreach $field (@priv) {
  2457. $line1 .= sprintf("<td align=center><font color=$color{$type}>%-4s</font></td>",$field);
  2458. }
  2459. print "<tr>$line1</tr>\n";
  2460. }
  2461. }
  2462. print "\n";
  2463. if ($MySQLaccess::CMD) {
  2464. print "---------------------------------------------------------------------\n";
  2465. }
  2466. if ($MySQLaccess::CGI) {
  2467. print "</table><br>";
  2468. }
  2469. return 1;
  2470. }
  2471. # ======================================
  2472. # sub Tabular_Report
  2473. # Tabular report,
  2474. # suitable for 1 triple (host,db,user)
  2475. # ======================================
  2476. sub Tabular_Report {
  2477. my ($host,$user,$db,$a) = @_;
  2478. my $column=2;
  2479. # -----------------------------
  2480. # separator
  2481. if ($MySQLaccess::Report::separator) { print "$MySQLaccess::Report::separator\n"; }
  2482. # -----------------------------
  2483. # print table of access-rights
  2484. my $rows = int(@MySQLaccess::Grant::Privileges/2); #round up
  2485. my @table=();
  2486. $j=0;
  2487. for $i (0 .. $rows-1) {
  2488. $table[$j]=$MySQLaccess::Grant::Privileges[$i];
  2489. $j = $j+2;
  2490. }
  2491. $j=1;
  2492. for $i ($rows .. $#MySQLaccess::Grant::Privileges) {
  2493. $table[$j]=$MySQLaccess::Grant::Privileges[$i];
  2494. $j = $j+2;
  2495. }
  2496. if ($MySQLaccess::CMD) {
  2497. print "\n";
  2498. print "Access-rights\n";
  2499. print "for USER '$user', from HOST '$host', to DB '$db'\n";
  2500. }
  2501. if ($MySQLaccess::CGI) {
  2502. print "<table border width=100%>\n";
  2503. print "<tr>\n";
  2504. }
  2505. if ($MySQLaccess::CGI) {
  2506. print "<th colspan=5>";
  2507. print "<font color=Red>Access-rights</font>\n";
  2508. print "for USER '<font color=Green>$user</font>', from HOST '<font color=Green>$host</font>', to DB '<font color=Green>$db</font>'\n";
  2509. print "</th>";
  2510. print "</tr>\n";
  2511. print "<tr>\n";
  2512. }
  2513. if ($MySQLaccess::CMD) {
  2514. print "\t+-----------------+---+\t+-----------------+---+";
  2515. }
  2516. foreach $field (@table) {
  2517. if ($MySQLaccess::CMD) {
  2518. if ($column==2) { print "\n\t"; $column=1;}
  2519. else { print "\t"; $column=2;}
  2520. printf "| %-15s | %s |",$field,$Answer{$a->{$field}};
  2521. }
  2522. if ($MySQLaccess::CGI) {
  2523. if ($column==2) { print "</tr>\n<tr>\n"; $column=1;}
  2524. else { print "<td width=10%></td>"; $column=2;}
  2525. printf " <td width=35%><b>%-15s</b></td><td width=10%>%s</td>\n",$field,$Answer{$a->{$field}};
  2526. }
  2527. }
  2528. print "\n";
  2529. if ($MySQLaccess::CMD) {
  2530. print "\t+-----------------+---+\t+-----------------+---+\n";
  2531. }
  2532. if ($MySQLaccess::CGI) {
  2533. print "</tr>\n</table><br>";
  2534. }
  2535. # ---------------
  2536. # print notes:
  2537. foreach $note (@MySQLaccess::Grant::Notes) {
  2538. my $message = $MESSAGES{$note};
  2539. $message =~ s/\$user/$user/g;
  2540. $message =~ s/\$db/$db/g;
  2541. $message =~ s/\$host/$host/g;
  2542. $message =~ s/\$password/$password/g;
  2543. $PREFIX='NOTE';
  2544. if ($MySQLaccess::CMD) {
  2545. my @lines = split(/\n/,$message);
  2546. foreach $line (@lines) {
  2547. print "$PREFIX:\t $line\n";
  2548. $PREFIX=' ';
  2549. }
  2550. }
  2551. if ($MySQLaccess::CGI) {
  2552. print "<b>$PREFIX:</b> $message<br>\n";
  2553. }
  2554. }
  2555. # ---------------
  2556. # print warnings:
  2557. foreach $warning (@MySQLaccess::Grant::Warnings) {
  2558. my $message = $MESSAGES{$warning};
  2559. $message =~ s/\$user/$user/g;
  2560. $message =~ s/\$db/$db/g;
  2561. $message =~ s/\$host/$host/g;
  2562. $message =~ s/\$password/$password/g;
  2563. $PREFIX='BEWARE';
  2564. if ($MySQLaccess::CMD) {
  2565. my @lines = split(/\n/,$message);
  2566. foreach $line (@lines) {
  2567. print "$PREFIX:\t $line\n";
  2568. $PREFIX=' ';
  2569. }
  2570. }
  2571. if ($MySQLaccess::CGI) {
  2572. print "<b>$PREFIX:</b> $message<br>\n";
  2573. }
  2574. }
  2575. # ---------------
  2576. # print errors:
  2577. foreach $error (@MySQLaccess::Grant::Errors) {
  2578. my $message = $MESSAGES{$error};
  2579. $message =~ s/\$user/$user/g;
  2580. $message =~ s/\$db/$db/g;
  2581. $message =~ s/\$host/$host/g;
  2582. $message =~ s/\$password/$password/g;
  2583. $PREFIX='ERROR';
  2584. if ($MySQLaccess::CMD) {
  2585. my @lines = split(/\n/,$message);
  2586. foreach $line (@lines) {
  2587. print "$PREFIX:\t $line\n";
  2588. $PREFIX=' ';
  2589. }
  2590. }
  2591. if ($MySQLaccess::CGI) {
  2592. print "<b>$PREFIX:</b> $message<br>\n";
  2593. }
  2594. }
  2595. # ---------------
  2596. # inform if there are no rules ==> full access for everyone.
  2597. if ($MySQLaccess::Grant::full_access) { print "$MESSAGES{'full_access'}\n"; }
  2598. # ---------------
  2599. # print the rules used
  2600. print "\n";
  2601. if ($MySQLaccess::CMD) {
  2602. print "The following rules are used:\n";
  2603. foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {
  2604. my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});
  2605. $rule =~ s/\t/','/g;
  2606. printf " %-5s : '%s'\n",$field,$rule;
  2607. }
  2608. }
  2609. if ($MySQLaccess::CGI) {
  2610. print "<br>\n";
  2611. print "<table border width=100%>\n";
  2612. print "<tr><th colspan=2>The following rules are used:</th></tr>\n";
  2613. foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {
  2614. my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});
  2615. $rule =~ s/\t/','/g;
  2616. printf "<tr><th>%-5s</th><td>'%s'</td></tr>\n",$field,$rule;
  2617. }
  2618. print "</table>\n";
  2619. }
  2620. return 1;
  2621. }
  2622. # ======================================
  2623. # sub Matrix_Report:
  2624. # single-line output foreach triple,
  2625. # no notes,warnings,...
  2626. # ======================================
  2627. sub Matrix_Report {
  2628. my ($host,$user,$db,$a) = @_;
  2629. my @headers = ();
  2630. if (! $headers) {
  2631. # -----------------------------
  2632. # create column-headers
  2633. foreach $field (@MySQLaccess::Grant::Privileges) {
  2634. push(@headers,substr($field,0,4));
  2635. }
  2636. # -----------------------------
  2637. # print column-headers
  2638. print "\n";
  2639. if ($MySQLaccess::CMD) {
  2640. my $line1="";
  2641. my $line2="";
  2642. foreach $header (@headers) {
  2643. $line1 .= sprintf("%-4s ",$header);
  2644. $line2 .= sprintf("%s ",'----');
  2645. }
  2646. $line1 .= sprintf("| %-20s",'Host,User,DB');
  2647. $line2 .= sprintf("+ %-20s",'-' x 20);
  2648. print "$line1\n";
  2649. print "$line2\n";
  2650. }
  2651. if ($MySQLaccess::CGI) {
  2652. print "<table width=100% border>\n";
  2653. my $line1="<tr>";
  2654. foreach $header (@headers) {
  2655. $line1 .= sprintf("<th>%-4s</th>",$header);
  2656. }
  2657. $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB');
  2658. print "$line1</tr>\n";
  2659. }
  2660. # ----------------------------
  2661. # column-headers should only be
  2662. # printed once.
  2663. $MySQLaccess::Report::headers=1;
  2664. }
  2665. # ------------------------
  2666. # print access-information
  2667. if ($MySQLaccess::CMD) {
  2668. foreach $field (@MySQLaccess::Grant::Privileges) {
  2669. printf " %-2s ",$Answer{$a->{$field}};
  2670. }
  2671. printf "| %-20s",join(',',$host,$user,$db);
  2672. print "\n";
  2673. }
  2674. if ($MySQLaccess::CGI) {
  2675. print "<tr>";
  2676. foreach $field (@MySQLaccess::Grant::Privileges) {
  2677. printf "<td align=center>%-2s</td>",$Answer{$a->{$field}};
  2678. }
  2679. printf "<td><b>%-20s</b></td>",join(', ',$host,$user,$db);
  2680. print "</tr>\n";
  2681. }
  2682. return 1;
  2683. }
  2684. # ======================================
  2685. # sub Raw_Report:
  2686. # single-line output foreach triple,
  2687. # no notes,warnings,...
  2688. # ======================================
  2689. sub Raw_Report {
  2690. my ($host,$user,$db,$a) = @_;
  2691. my @headers = ();
  2692. my $string = "";
  2693. # ------------------------
  2694. # print access-information
  2695. $string = "$host,$user,$db,";
  2696. foreach $field (@MySQLaccess::Grant::Privileges) {
  2697. $string .= $Answer{$a->{$field}} . ",";
  2698. }
  2699. return $string;
  2700. }
  2701. #######################################################################
  2702. package MySQLaccess::Wildcards;
  2703. BEGIN {
  2704. $DEBUG = 0;
  2705. $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG);
  2706. }
  2707. # ############################################
  2708. # SQL, WILDCARDS and REGULAR EXPRESSIONS
  2709. # ============================================
  2710. # translage SQL-expressions to Reg-expressions
  2711. # ============================================
  2712. sub SQL2Reg {
  2713. my ($expr) = @_;
  2714. my $expr_o = $expr;
  2715. $expr =~ s/\./\\./g;
  2716. $expr =~ s/\\%/\002/g;
  2717. $expr =~ s/%/.*/g;
  2718. $expr =~ s/\002/%/g;
  2719. $expr =~ s/\\_/\002/g;
  2720. $expr =~ s/_/.+/g;
  2721. $expr =~ s/\002/_/g;
  2722. MySQLaccess::Debug::Print(2,"$expr_o --> $expr");
  2723. return $expr;
  2724. }
  2725. # translage WILDcards to Reg-expressions
  2726. # ============================================
  2727. sub Wild2Reg {
  2728. my ($expr) = @_;
  2729. my $expr_o = $expr;
  2730. $expr =~ s/\./\\./g;
  2731. $expr =~ s/\\\*/\002/g;
  2732. $expr =~ s/\*/.*/g;
  2733. $expr =~ s/\002/*/g;
  2734. $expr =~ s/\\\?/\002/g;
  2735. $expr =~ s/\?/.+/g;
  2736. $expr =~ s/\002/?/g;
  2737. MySQLaccess::Debug::Print(2,"$expr_o --> $expr");
  2738. return $expr;
  2739. }
  2740. # =============================================
  2741. # match a given string with a template
  2742. # =============================================
  2743. sub MatchTemplate {
  2744. my ($tpl,$string) = @_;
  2745. my $match=0;
  2746. if ($string=~ /^$tpl$/ or $tpl eq '') { $match=1; }
  2747. else { $match=0;}
  2748. MySQLaccess::Debug::Print(2,"($tpl,$string) --> $match");
  2749. return $match;
  2750. }
  2751. #######################################################################
  2752. package MySQLaccess::Host;
  2753. BEGIN {
  2754. $localhost = undef;
  2755. $DEBUG = 2;
  2756. $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG);
  2757. }
  2758. # ======================================
  2759. # sub IP2Name
  2760. # return the Name with the corr. IP-nmbr
  2761. # (no aliases yet!!)
  2762. # ======================================
  2763. sub IP2Name {
  2764. my ($ip) = @_;
  2765. my $ip_o = $ip;
  2766. if ($ip !~ /([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/o) {
  2767. MySQLaccess::Debug::Print(3,"'$ip' is not an ip-number, returning IP=$ip");
  2768. return $ip;
  2769. }
  2770. MySQLaccess::Debug::Print(4,"IP=$ip split up => $1.$2.$3.$4");
  2771. $ip = pack "C4",$1,$2,$3,$4;
  2772. MySQLaccess::Debug::Print(4,"IP packed -> >>$ip<<\n");
  2773. my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($ip, AF_INET);
  2774. MySQLaccess::Debug::Print(3,"IP=$ip_o => hostname=$name");
  2775. MySQLaccess::Debug::Print(4,"aliases=$aliases");
  2776. MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length");
  2777. return ($name || $ip);
  2778. #return ($name || undef);
  2779. }
  2780. # ======================================
  2781. # sub Name2IP
  2782. # return the IP-number of the host
  2783. # ======================================
  2784. sub Name2IP {
  2785. my ($name) = @_;
  2786. if ($name =~ /[%_]/) {
  2787. MySQLaccess::Debug::Print(3,"'$name' contains SQL-wildcards, returning name=$name");
  2788. return $name;
  2789. }
  2790. my ($_name,$aliases,$addrtype,$length,@addrs) = gethostbyname($name);
  2791. my ($a,$b,$c,$d) = unpack('C4',$addrs[0]);
  2792. my $ip = "$a.$b.$c.$d";
  2793. MySQLaccess::Debug::Print(3,"hostname=$name => IP=$ip");
  2794. MySQLaccess::Debug::Print(4,"aliases=$aliases");
  2795. MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length");
  2796. #if ($ip ne "") { return "$ip"; }
  2797. #else { return undef; }
  2798. return ($ip || $name);
  2799. }
  2800. # ========================================
  2801. # sub LocalHost
  2802. # some special action has to be taken for
  2803. # the localhost
  2804. # ========================================
  2805. sub LocalHost {
  2806. if (!defined($MySQLaccess::Host::localhost)) {
  2807. $MySQLaccess::Host::localhost = Sys::Hostname::hostname();
  2808. MySQLaccess::Debug::Print(3,"Setting package variable \$localhost=$MySQLaccess::Host::localhost");
  2809. }
  2810. my $host = $localhost;
  2811. MySQLaccess::Debug::Print(3,"localhost = $host");
  2812. return $host;
  2813. }
  2814. # ========================================
  2815. # check if the given hostname (or ip)
  2816. # corresponds with the localhost
  2817. # ========================================
  2818. sub Is_localhost {
  2819. my ($host_tpl) = @_;
  2820. my $isit = 0;
  2821. if (($MySQLaccess::host_name eq $localhost) or ($MySQLaccess::host_ip eq $local_ip)) {
  2822. MySQLaccess::Debug::Print(2,"Checking for localhost");
  2823. MySQLaccess::Debug::Print(3,"because ($MySQLaccess::host_name EQ $localhost) AND ($MySQLaccess::host_ip EQ $local_ip)");
  2824. $isit = ( 'localhost' =~ /$host_tpl/ ) ? 1 : 0;
  2825. MySQLaccess::Debug::Print(3," 'localhost' =?= $host_tpl -> $isit");
  2826. return $isit;
  2827. }
  2828. else {
  2829. MySQLaccess::Debug::Print(4,"Not checking for localhost");
  2830. MySQLaccess::Debug::Print(4,"because ($MySQLaccess::host_name != $localhost) AND ($MySQLaccess::host_ip != $local_ip)");
  2831. return 0;
  2832. }
  2833. }
  2834. # =========================================
  2835. # check if host (IP or name) can be matched
  2836. # on the template.
  2837. # =========================================
  2838. sub MatchTemplate {
  2839. my ($host,$tpl) = @_;
  2840. my $match = 0;
  2841. MySQLaccess::Debug::Print(1, "($host) =?= ($tpl)");
  2842. my $host_name = IP2Name($host);
  2843. my $host_ip = Name2IP($host);
  2844. MySQLaccess::Debug::Print(2, "name=$host_name ; ip=$host_ip");
  2845. $match = (MySQLaccess::Wildcards::MatchTemplate($tpl,$host_name) or
  2846. MySQLaccess::Wildcards::MatchTemplate($tpl,$host_ip));
  2847. MySQLaccess::Debug::Print(2, "($host_name,$host_ip) =?= ($tpl): $ncount");
  2848. return $match;
  2849. }
  2850. ########################################################################
  2851. package MySQLaccess::Debug;
  2852. BEGIN {
  2853. my $dbg_file = "$MySQLaccess::script_log";
  2854. open(DEBUG,"> $dbg_file") or warn "Could not open outputfile $dbg_file for debugging-info\n";
  2855. select DEBUG;
  2856. $| = 1;
  2857. select STDOUT;
  2858. }
  2859. # =========================================
  2860. # Print debugging information on STDERR
  2861. # =========================================
  2862. sub Print {
  2863. my ($level,$mesg) = @_;
  2864. my ($pack,$file,$line,$subname,$hasargs,$wantarray) = caller(1);
  2865. my ($PACK) = split('::',$subname);
  2866. my $DEBUG = ${$PACK."::DEBUG"} ? ${$PACK."::DEBUG"} : $MySQLaccess::DEBUG ;
  2867. my ($sec,$min,$hour) = localtime();
  2868. print DEBUG "[$hour:$min:$sec $subname] $mesg\n" if ($DEBUG>=$level);
  2869. }