Saturday, April 13, 2019

LAMP for beginner


Linux, Apache, MySQL, PHP (LAMP) for beginners...

Enough to get you started... (this was done in AWS).

  1. Launch a new EC2 instance from AWS' Red Hat 7 AMI (free tier)
  2. Log into it using "ec2-user"
  3. Elevate privilege
    sudo su - 
  4. Do a fresh update
    yum update
  5. Add repositories
    1. REMI:
      rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
    2. EPEL
      rpm -Uvh http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm
    3. MySQL
      rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7.rpm
  6. Installing Apache
    1. Yum install command
      yum install httpd
    2. Set it to start on boot:
      systemctl enable httpd.service 
    3. Start it now:
      systemctl start httpd.service
    4. Default log location (access_log and error_log)
      /var/log/httpd
    5. Default configuration
      /etc/httpd/conf/httpd.conf
  7. Installing mysql
    1. Yum install command
      yum install mysql-server
    2. Set this to start on boot:
      systemctl enable mysqld.service
    3. Start it now
      systemctl start mysqld.service
    4. Get the mysql temporary password for root
      grep "A temporary password" /var/log/mysqld.log | tail -nl
    5. You should get something like this...
       [Server] A temporary password is generated for root@localhost: V!cedo*iP0iW
    6. Secure your mysql
      mysql_secure_installation
    7. Accept all secure measures. Don't forget your new password!
  8. Install php
    1. Do it from REMI repo (RedHat only comes with php 5.3)
      yum --enablerepo=epel,remi-php73 install php
    2. Install Modules of your choice (these are what I installed)
      yum --enablerepo=remi-php73 install php-mysql php-xml php-xmlrpc php-soap php-gd php-fpm
    3. Restart Apache for the php install to take effect
      systemctl restart httpd.service
  9. You should be able to browse to it now
    1. you can do it locally:
      curl locahost
    2. You can do it remotely
      http://publicIP
    3. If you don't see it from remote, try turning off IPTABLES
      systemctl status iptables
  10. Write your first HTML page
    1. Go to /var/www/html/
    2. Edit a new file
      vi index.html
    3. Paste the following
      <html>
      <head>
      </head>
      <body>
      <p>Hello World</p>
      </body>
      </html>
      
  11. Write your first PHP page
    1. Still at /var/www/html/
    2. Edit a new file
      vi index.php
    3. Anything inside <?php and ?>  will be interpreted as PHP code
    4. Paste the following
      <html>
      <head>
      </head>
      <body>
      <?php
      print("Hello World");
      phpinfo();
      ?>
      </body>
      </html>
      
  12.  Let's secure your site
    1. Install mod_ssl module
      yum install mod_ssl
    2. Get self-signed cert via this command(or look up how to purchase one or get a free one from cacert.org)
      openssl req -newkey rsa:2048 -nodes -keyout /etc/ssl/private/myserver.key -x509 -days 365 -out /etc/ssl/private/myserver.crt
    3. Go to /etc/httpd/conf.d
    4. Create a new file ssl.conf and paste the following into it
      LoadModule ssl_module modules/mod_ssl.so
      
      Listen 443
      <VirtualHost *:443>
          ServerName myserver
          SSLEngine on
          SSLCertificateFile "/etc/ssl/private/myserver.crt"
          SSLCertificateKeyFile "/etc/ssl/private/myserver.key"
      </VirtualHost>
      
    5. Restart httpd
      systemctl restart httpd.service
    6. Check log if you run into issue, you may have a syntax error
    7. Go to your browser and use https instead
  13. Bonus Round! Let's accept client certs. Go here for more info.
    1. Update the previous step's ssl.conf with this new
      LoadModule ssl_module modules/mod_ssl.so
      
      Listen 443
      <VirtualHost *:443>
          ServerName myserver
          SSLEngine on
          SSLCertificateFile "/etc/ssl/private/myserver.crt"
          SSLCertificateKeyFile "/etc/ssl/private/myserver.key"
          SSLCACertificateFile "/etc/ssl/private/myserver.crt" 
          ## Your choice here is required, optional, and optional_no_ca
          SSLVerifyClient optional_no_ca
          ## this is number of depths of CA to traverse, use 1
          SSLVerifyDepth 1
          ## this send the cert info to PHP
          SSLOptions +StdEnvVars +ExportCertData
          ## this will allow it to accept your own CA unknown to browser
          SSLCADNRequestPath /etc/ssl/private/ 
      </VirtualHost>
      
    2. Restart httpd so that the new ssl.conf is accepted
    3. At this point, you need a cert loaded to your browser to test this
      1. You can use your company cert
      2. You can also use self-signed cert and loaded onto your browser (use openssl to self-sign a key pair then use "openssl pkcs12" command to put it together as PKCS12 so that you can import it into your browser)
    4. Now browse to your sample PHP page you created before and you should get prompted for your cert, give it and let's take a look at the Apache Environment variables
    5.   Creating a table to hold visitor credential. Here's additional how-to mysql.
      1. Log into mysql
        mysql -u root -p
      2. Create a new database
        mysql> CREATE DATABASE mylamp;
      3. Select this database for use
        mysql> USE mylamp;
      4. Let's create our table
        CREATE TABLE users (
            id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
            username VARCHAR(50) NOT NULL UNIQUE,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            lastvisit_at DATETIME DEFAULT CURRENT_TIMESTAMP 
        );
        
      5. Let's check it
        mysql> SHOW TABLES;
      6. You can also do this:
        mysql> DESCRIBE users;
      7. Now let's create a new user to access this table (I'm disabling password validation for this user). More info here.
        SET GLOBAL validate_password.policy=LOW;
        CREATE USER 'mylampuser'@'localhost'
          IDENTIFIED WITH mysql_native_password BY 'password';
        GRANT ALL
          ON mylamp.*
          TO 'mylampuser'@'localhost'
          WITH GRANT OPTION;
        
      8. You can exit now
        mysql> exit
    6. Let's create some PHP files to write user information to the table. Here's additional info on how to do this.
      1. Create a new file, config.php (at /var/www/html)
        vi config.php
      2. Paste the following
        <?php
        /* Database credentials. */
        define('DB_SERVER', 'localhost');
        define('DB_USERNAME', 'mylampuser');
        define('DB_PASSWORD', 'password');
        define('DB_NAME', 'mylamp');
         
        /* Attempt to connect to MySQL database */
        $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
         
        // Check connection
        if($link === false){
            die("ERROR: Could not connect. " . mysqli_connect_error());
        }
        ?>
        
      3. Create a new file, login.php (also at /var/www/html)
        vi login.php
      4. Paste the following
        <?php
        // Include config file
        session_start();
        require_once "config.php";
        if(isset($_SERVER['SSL_CLIENT_S_DN_Email'])){
         $_SESSION['username'] = $_SERVER['SSL_CLIENT_S_DN_Email'];
         $username = $_SERVER['SSL_CLIENT_S_DN_Email'];
         $sql = "SELECT id FROM users WHERE username = ?";
         if($stmt = mysqli_prepare($link, $sql)){
          // Bind variables to the prepared statement as parameters
          mysqli_stmt_bind_param($stmt, "s", $username);
          // Attempt to execute the prepared statement
          if(mysqli_stmt_execute($stmt)){
           /* store result */
           mysqli_stmt_store_result($stmt);
        
           if(mysqli_stmt_num_rows($stmt) == 1){
            //update user
            $sql = "UPDATE users SET lastvisit_at = now() where username = ?";
           } else{
            //add a new user
            $sql = "Insert into users (username) values (?)";
           }
           if($stmt = mysqli_prepare($link, $sql)){
            mysqli_stmt_bind_param($stmt, "s", $username);
            if(mysqli_stmt_execute($stmt)){
             mysqli_stmt_store_result($stmt);
             mysqli_stmt_free_result($stmt);
             mysqli_stmt_close($stmt);
            }
           }else{
            echo "Oops! Something went wrong. Please try again later.";
           }
          } else{
           echo "Oops! Something went wrong. Please try again later.";
          }
        }
        }else{
         $_SESSION['username'] = 'unknown';
        }
        echo $_SESSION['username'];
        mysqli_close($link);
        ?>
        

      5. Also create users.php to view all the entries in the table
        vi users.php
      6. Paste the following (more info here)
        <?php
        require_once "config.php";
        
        $sql = "SELECT * from users";
        if($stmt = mysqli_prepare($link, $sql)){
                if(mysqli_stmt_execute($stmt)){
                        mysqli_stmt_store_result($stmt);
                        printf("Number of rows: %d.<br>", mysqli_stmt_num_rows($stmt));
                        mysqli_stmt_bind_result($stmt, $id, $username, $created, $lastuse);
                        while(mysqli_stmt_fetch($stmt)){
                                printf("%s -- %s -- %s -- %s. <br>",$id,$username,$created,$lastuse);
                        }
                        mysqli_stmt_free_result($stmt);
                        mysqli_stmt_close($stmt);
                }
        }else{
                echo "Oops! Something went wrong. Please try again later.";
        }
        /* close connection */
        mysqli_close($link);
        ?>
        
      7. Browse to users.php, you'll see 0 entries
      8. In a new tab, open login.php, you should get success
      9. Now, go back to users.php tab, and refresh the page, you should see 1 entry with your information.
      10. For extra flexibility, you can include this in your other page to process the login action (index.php)
        <html>
        <head>
        </head>
        <body>
        <?php
        include 'login.php';
        print("Hello World");
        ?>
        </body>
        </html>
        























    AWS WAF log4j query

    How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...