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.

389 lines
8.8 KiB

  1. #!/usr/bin/perl
  2. # -*- cperl -*-
  3. #
  4. # Copyright (C) 2002 MySQL AB and Jeremy Cole
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; version 2 of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. use Fcntl;
  19. use File::Spec;
  20. use if $^O eq 'MSWin32', 'Term::ReadKey' => qw/ReadMode/;
  21. use strict;
  22. my $config = ".my.cnf.$$";
  23. my $command = ".mysql.$$";
  24. my $hadpass = 0;
  25. my $mysql; # How to call the mysql client
  26. my $rootpass = "";
  27. $SIG{QUIT} = $SIG{INT} = sub {
  28. print "\nAborting!\n\n";
  29. echo_on();
  30. cleanup();
  31. exit 1;
  32. };
  33. END {
  34. # Remove temporary files, even if exiting via die(), etc.
  35. cleanup();
  36. }
  37. sub read_without_echo {
  38. my ($prompt) = @_;
  39. print $prompt;
  40. echo_off();
  41. my $answer = <STDIN>;
  42. echo_on();
  43. print "\n";
  44. chomp($answer);
  45. return $answer;
  46. }
  47. sub echo_on {
  48. if ($^O eq 'MSWin32') {
  49. ReadMode('normal');
  50. } else {
  51. system("stty echo");
  52. }
  53. }
  54. sub echo_off {
  55. if ($^O eq 'MSWin32') {
  56. ReadMode('noecho');
  57. } else {
  58. system("stty -echo");
  59. }
  60. }
  61. sub write_file {
  62. my $file = shift;
  63. -f $file or die "ERROR: file is missing \"$file\": $!";
  64. open(FILE, ">$file") or die "ERROR: can't write to file \"$file\": $!";
  65. foreach my $line ( @_ ) {
  66. print FILE $line, "\n"; # Add EOL char
  67. }
  68. close FILE;
  69. }
  70. sub prepare {
  71. # Locate the mysql client; look in current directory first, then
  72. # in path
  73. our $SAVEERR; # Suppress Perl warning message
  74. open SAVEERR, ">& STDERR";
  75. close STDERR;
  76. for my $m (File::Spec->catfile('bin', 'mysql'), 'mysql') {
  77. # mysql --version should always work
  78. qx($m --no-defaults --version);
  79. next unless $? == 0;
  80. $mysql = $m;
  81. last;
  82. }
  83. open STDERR, ">& SAVEERR";
  84. die "Can't find a 'mysql' client in PATH or ./bin\n"
  85. unless $mysql;
  86. # Create safe files to avoid leaking info to other users
  87. foreach my $file ( $config, $command ) {
  88. next if -f $file; # Already exists
  89. local *FILE;
  90. sysopen(FILE, $file, O_CREAT, 0600)
  91. or die "ERROR: can't create $file: $!";
  92. close FILE;
  93. }
  94. }
  95. # Simple escape mechanism (\-escape any ' and \), suitable for two contexts:
  96. # - single-quoted SQL strings
  97. # - single-quoted option values on the right hand side of = in my.cnf
  98. #
  99. # These two contexts don't handle escapes identically. SQL strings allow
  100. # quoting any character (\C => C, for any C), but my.cnf parsing allows
  101. # quoting only \, ' or ". For example, password='a\b' quotes a 3-character
  102. # string in my.cnf, but a 2-character string in SQL.
  103. #
  104. # This simple escape works correctly in both places.
  105. sub basic_single_escape {
  106. my ($str) = @_;
  107. # Inside a character class, \ is not special; this escapes both \ and '
  108. $str =~ s/([\'])/\\$1/g;
  109. return $str;
  110. }
  111. sub do_query {
  112. my $query = shift;
  113. write_file($command, $query);
  114. my $rv = system("$mysql --defaults-file=$config < $command");
  115. # system() returns -1 if exec fails (e.g., command not found, etc.); die
  116. # in this case because nothing is going to work
  117. die "Failed to execute mysql client '$mysql'\n" if $rv == -1;
  118. # Return true if query executed OK, or false if there was some problem
  119. # (for example, SQL error or wrong password)
  120. return ($rv == 0 ? 1 : undef);
  121. }
  122. sub make_config {
  123. my $password = shift;
  124. my $esc_pass = basic_single_escape($rootpass);
  125. write_file($config,
  126. "# mysql_secure_installation config file",
  127. "[mysql]",
  128. "user=root",
  129. "password='$esc_pass'");
  130. }
  131. sub get_root_password {
  132. my $attempts = 3;
  133. for (;;) {
  134. my $password = read_without_echo("Enter current password for root (enter for none): ");
  135. if ( $password ) {
  136. $hadpass = 1;
  137. } else {
  138. $hadpass = 0;
  139. }
  140. $rootpass = $password;
  141. make_config($rootpass);
  142. last if do_query("");
  143. die "Unable to connect to the server as root user, giving up.\n"
  144. if --$attempts == 0;
  145. }
  146. print "OK, successfully used password, moving on...\n\n";
  147. }
  148. sub set_root_password {
  149. my $password1;
  150. for (;;) {
  151. $password1 = read_without_echo("New password: ");
  152. if ( !$password1 ) {
  153. print "Sorry, you can't use an empty password here.\n\n";
  154. next;
  155. }
  156. my $password2 = read_without_echo("Re-enter new password: ");
  157. if ( $password1 ne $password2 ) {
  158. print "Sorry, passwords do not match.\n\n";
  159. next;
  160. }
  161. last;
  162. }
  163. my $esc_pass = basic_single_escape($password1);
  164. do_query("UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';")
  165. or die "Password update failed!\n";
  166. print "Password updated successfully!\n";
  167. print "Reloading privilege tables..\n";
  168. reload_privilege_tables()
  169. or die "Can not continue.\n";
  170. print "\n";
  171. $rootpass = $password1;
  172. make_config($rootpass);
  173. }
  174. sub remove_anonymous_users {
  175. do_query("DELETE FROM mysql.user WHERE User='';")
  176. or die print " ... Failed!\n";
  177. print " ... Success!\n";
  178. }
  179. sub remove_remote_root {
  180. if (do_query("DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';")) {
  181. print " ... Success!\n";
  182. } else {
  183. print " ... Failed!\n";
  184. }
  185. }
  186. sub remove_test_database {
  187. print " - Dropping test database...\n";
  188. if (do_query("DROP DATABASE test;")) {
  189. print " ... Success!\n";
  190. } else {
  191. print " ... Failed! Not critical, keep moving...\n";
  192. }
  193. print " - Removing privileges on test database...\n";
  194. if (do_query("DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'")) {
  195. print " ... Success!\n";
  196. } else {
  197. print " ... Failed! Not critical, keep moving...\n";
  198. }
  199. }
  200. sub reload_privilege_tables {
  201. if (do_query("FLUSH PRIVILEGES;")) {
  202. print " ... Success!\n";
  203. return 1;
  204. } else {
  205. print " ... Failed!\n";
  206. return undef;
  207. }
  208. }
  209. sub cleanup {
  210. unlink($config,$command);
  211. }
  212. # The actual script starts here
  213. prepare();
  214. print <<HERE;
  215. NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
  216. SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
  217. In order to log into MySQL to secure it, we'll need the current
  218. password for the root user. If you've just installed MySQL, and
  219. you haven't set the root password yet, the password will be blank,
  220. so you should just press enter here.
  221. HERE
  222. get_root_password();
  223. #
  224. # Set the root password
  225. #
  226. print "Setting the root password ensures that nobody can log into the MySQL\n";
  227. print "root user without the proper authorisation.\n\n";
  228. if ( $hadpass == 0 ) {
  229. print "Set root password? [Y/n] ";
  230. } else {
  231. print "You already have a root password set, so you can safely answer 'n'.\n\n";
  232. print "Change the root password? [Y/n] ";
  233. }
  234. my $reply = <STDIN>;
  235. if ( $reply =~ /n/i ) {
  236. print " ... skipping.\n";
  237. } else {
  238. set_root_password();
  239. }
  240. print "\n";
  241. #
  242. # Remove anonymous users
  243. #
  244. print <<HERE;
  245. By default, a MySQL installation has an anonymous user, allowing anyone
  246. to log into MySQL without having to have a user account created for
  247. them. This is intended only for testing, and to make the installation
  248. go a bit smoother. You should remove them before moving into a
  249. production environment.
  250. HERE
  251. print "Remove anonymous users? [Y/n] ";
  252. $reply = <STDIN>;
  253. if ( $reply =~ /n/i ) {
  254. print " ... skipping.\n";
  255. } else {
  256. remove_anonymous_users();
  257. }
  258. print "\n";
  259. #
  260. # Disallow remote root login
  261. #
  262. print <<HERE;
  263. Normally, root should only be allowed to connect from 'localhost'. This
  264. ensures that someone cannot guess at the root password from the network.
  265. HERE
  266. print "Disallow root login remotely? [Y/n] ";
  267. $reply = <STDIN>;
  268. if ( $reply =~ /n/i ) {
  269. print " ... skipping.\n";
  270. } else {
  271. remove_remote_root();
  272. }
  273. print "\n";
  274. #
  275. # Remove test database
  276. #
  277. print <<HERE;
  278. By default, MySQL comes with a database named 'test' that anyone can
  279. access. This is also intended only for testing, and should be removed
  280. before moving into a production environment.
  281. HERE
  282. print "Remove test database and access to it? [Y/n] ";
  283. $reply = <STDIN>;
  284. if ( $reply =~ /n/i ) {
  285. print " ... skipping.\n";
  286. } else {
  287. remove_test_database();
  288. }
  289. print "\n";
  290. #
  291. # Reload privilege tables
  292. #
  293. print <<HERE;
  294. Reloading the privilege tables will ensure that all changes made so far
  295. will take effect immediately.
  296. HERE
  297. print "Reload privilege tables now? [Y/n] ";
  298. $reply = <STDIN>;
  299. if ( $reply =~ /n/i ) {
  300. print " ... skipping.\n";
  301. } else {
  302. reload_privilege_tables();
  303. }
  304. print "\n";
  305. print <<HERE;
  306. All done! If you've completed all of the above steps, your MySQL
  307. installation should now be secure.
  308. Thanks for using MySQL!
  309. HERE