이 블로그 검색

레이블이 Web Development인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Web Development인 게시물을 표시합니다. 모든 게시물 표시

2023년 8월 22일 화요일

What are Authentication and Authorization

Definitions

Authentication

The process of verifying a user's identity, confirming that the person is who they claim to be.

Authentication is the process of confirming the identity of a user or system. This involves the user providing evidence of their claimed identity or the system verifying the identity of the entity attempting to access a resource. Authentication is achieved when a user provides valid credentials (such as a username and password) to confirm their identity, often used during the login process. It is the first step required for a user to gain access to a system.

Authorization

The act of granting permissions to authorized individuals.

Authorization is the process of verifying whether an authenticated entity has the necessary permissions to access specific resources or perform certain actions. It occurs after authentication and involves determining what actions an authenticated entity is allowed to perform. For instance, in a web application, authorization might involve checking a user's permissions before allowing access to a specific page.

Vulnerable Points List

  • All pages requiring authentication or authorization

Vulnerability Testing Methods

  • Checking if access is possible to posts that are not accessible by simply changing page numbers (changing the HTTP address)
  • Verifying if client-side redirection occurs (this might allow response manipulation)
  • Reviewing comment sections for potential vulnerabilities
  • Checking if JavaScript files (.js) are used to implement redirection
  • Testing parameter manipulation

Attack Methods

Authentication Bypass Process

Details of Authentication Bypass Process

  1. Page 1 is accessible to anyone.
  2. Page 2 requires login. An unsuccessful login attempt is made by the attacker.
  3. If the login is successful on Page 2, the user is redirected to Page 3, granting access to the forum.
  4. However, Page 3 does not check for successful authentication.
  5. The attacker accesses Page 3 without going through Page 2.
  6. The server provides Page 3 content to the attacker.

Authorization Bypass Process

Details of Authorization Bypass Process

  1. The attacker requests "user profile" from the web server.
  2. The web server provides the "user profile" to the attacker.
  3. The attacker then requests "admin profile" from the web server.
  4. The web server denies the request, indicating incorrect cookie parameters.
  5. The attacker speculates that the server checks the cookie parameters.
  6. The attacker sends a tampered request for "user profile" to the web server.
  7. The web server provides the "admin profile" to the attacker.

Mitigation Strategies

  • Ultimate defense: Server-side verification through sessions
    • Server-side verification through sessions is essential
    • Client-side code should focus on user convenience features only
  • Additional measures:
    • Implement strong password policies: Enforce length, complexity, and change intervals
    • Introduce Two-Factor Authentication (2FA): Add additional authentication factors beyond passwords
  • Apply the principle of least privilege: Grant users only the minimum permissions required

Feel free to use this translated content for your blog! If you have any further questions or need additional assistance, feel free to ask.


2023년 4월 16일 일요일

Creating a Login Authentication Website with APM (Apache2, PHP, MySQL)

Purpose

Create a website with APM (Apache2, Php, Mysql) authentication using PHP's built-in session feature.

  1. Implement login function
  2. Implement main page
    • Only accessible after logging in
    • Show who is currently logged in
  3. Implement logout function
  4. Implement sign-up function
    • Check for duplicate IDs
    • Check for empty fields

The session ID is the user ID.

*Note:

Setting up APM (Apache, PHP, MySQL) Environment on Ubuntu

Set up the Database(MySQL)

Server name = "localhost"

Database name = "test"

Database User name = "root"

Database Password= "1234"

Table name= “users”

first row of table for admin ID: admin

first row of table for admin PWD: admin

Steps

  1. Create a database with the MySQL user:

    mysqladmin -u root create test -p
    
  2. Connect to MySQL user:

    mysql -u root -p
    
  3. Set the root account password (if not already set):

    use mysql;
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234';
    
  4. Select the database to use:

    use test;
    
  5. Create a table:

    create table users(
    	id int primary key auto_increment,
    	user_id varchar(255),
    	user_pwd varchar(255)
    );
    
  6. Insert a default admin account into the table:

    insert into users (user_id, user_pwd) values ('admin','admin');
    
  7. Verify the data in the table:

    select * from users;
    
  8. Exit the MySQL user:

    quit;
    
  9. Start the MySQL server:

    service mysql start
    
  10. Start the Apache server:

    # Start Apache
    sudo service apache2 start
    # Stop Apache
    sudo service apache2 stop
    # Restart Apache
    sudo service apache2 restart
    

Code

Main.php

<?php
session_start(); // Start session

if(!isset($_SESSION['user_id'])) // If not logged in
{
    header ('Location: ./login.html'); // Redirect to login page
}

echo "<h2>Login Success</h2><br><h2>";
echo $_SESSION['user_id'];
echo ", you have successfully logged in.</h2><br><br>"; // Print user's name
echo "<a href=logout.php>Logout</a>"; // Print logout link

?>

login.html

<html>
<head>
    <title>Login Page</title>
    <meta charset="utf-8">
</head>
<body>
    <form method="post" action="/login_chk.php">
        <div>
            <label for="user_id">ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd">Password </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <button type="submit">Login</button>
        </div>
    </form>
    <button onclick="location.href='sign_up.html'">Sign Up</button>
</body>
</html>

login_chk.php

<?php
session_start(); // Start session

$id = $_POST['user_id']; // User ID
$pw = $_POST['user_pwd']; // Password

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user info with the entered ID
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

// If user info exists
if($result->num_rows == 1){
    $row = $result->fetch_array(MYSQLI_ASSOC);
    // If the entered password is correct
    if($row['user_pwd'] == $pw){
        $_SESSION['user_id'] = $id;
        // If session is successfully saved
        if(isset($_SESSION['user_id'])){
            header('Location: ./Main.php');
        }
        else{
            echo "Session save failed";
        }
    }
    // If the entered password is incorrect
    else{
        echo "Wrong ID or password.";
        header('Location: ./login.html');
    }
}
// If user info does not exist
else{
    echo "Wrong ID or password.";
    header('Location: ./login.html');
}

$conn->close(); // Close database connection
?>

sign_up.html

<html>
<head>
    <title> Sign Up </title>
    <meta charset="utf-8">
</head>
<body>
    <form action = "./sign_up.php" method="post">
        <div>
            <label for="user_id"> ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd"> PW </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <input type="submit" value="submit">
        </div>
    </form>
</body>
</html>

sign_up.php

<?php
$id = $_POST['user_id']; // ID submitted by the user
$pw = $_POST['user_pwd']; // Password submitted by the user

if($id==NULL || $pw==NULL) // If the user didn't fill out all the fields
{
    echo "Please fill out all the fields";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// If the ID already exists
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

if($result->num_rows == 1)
{
    echo "ID already exists";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

// Add new user info to the database
$sql = "INSERT INTO users (user_id, user_pwd) VALUES ('$id', '$pw')";
$signup = mysqli_query($conn, $sql);

// If the signup process is successful
if($signup)
{
    echo "Registration completed.";
}

$conn->close(); // Close the database connection
?>

logout.php

<?php
session_start(); // Start the session

$res = session_destroy(); // Remove all session variables

if($res)
{
    header('Location: ./Main.php'); // If the logout process is successful, redirect to the login page
}
?>

2023년 4월 11일 화요일

Setting up APM (Apache, PHP, MySQL) Environment on Ubuntu

 

System Specification

Name Version
VirtualBox 7.0
Ubuntu 22.04.2
Windows 11
CPU AMD Ryzen 7 5700U
RAM 16.0 GB
GPU -
SDD 512 GB

Installing Apache2

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install apache2
    sudo apt install apache2
    
  2. Enter the server start command to check if the Apache server is installed correctly.

    # Start Apache server
    sudo service apache2 start
    # Stop Apache server
    sudo service apache2 stop
    # Restart Apache server
    sudo service apache2 restart
    
  3. Open a web browser and go to http://localhost to check if the server is running.

Installing Mysql

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install Mysql
    sudo apt install mysql-server
    
  2. Check the mysql version to make sure it is installed correctly.

    # Check mysql version
    mysql --version
    

Installing PHP

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install PHP and modules that allow php to use apache2 and mysql
    sudo apt install php libapache2-mod-php php-mysq
    
  2. Use the following command to check if it is installed correctly

    # Check php version
    php -v
    

Testing the server

In order to test if the server is working properly, let's create a php file and test it on the Apache server.

To do this, you need to know basic Linux commands and how to use vim.

vim

The most basic text editor in Linux. Similar to Windows' Notepad.

  • In the past, vi was used, but vim was created by adding some more features to it.
  • Vim is a text editor that is designed to edit text without using a mouse by default, so it is very difficult to use without knowing the shortcuts and how to use it.
  • Depending on the Linux version and type, vim may not be installed.

Necessary Linux commands

bashCopy code
sudo su # Switch to Linux root account. Has the highest privileges of all Linux accounts
cd / # cd is used to move, and adding / moves to the highest-level folder
cd .. # Adds .. to move to the parent folder
ls # Shows the file and folder list of the current directory
vim # Creates or opens a vim file when followed by a file

Necessary Vim commands

  • Open or create a vim file: vim [filename and extension]

    vim phpinfo.php # create or open a php file named phpinfo in the current directory
    
  • Edit a vim file: press the "i" key

    Pressing the "i" key will change the left bottom corner of the screen to display "INSERT," indicating that you are in insert mode and can edit the file.

  • Exit insert mode and return to command mode: press the "ESC" key

    While in insert mode, you can only type text into the file, but to save the changes, you need to return to command mode and enter a specific command.

  • Save a vim file: type ":w" in command mode and press Enter

  • Exit a vim file: type ":q" in command mode and press Enter

Default location of Apache server

/var/www/html

How to test the server

  1. Switch to root account.
  2. Move to the default location of the Apache server.
  3. Create a PHP file in the default location of the Apache server using Vim.
  4. Start the Apache server.
  5. Open a web browser and check if it works correctly.

Step-by-step

sudo su # Enter the password to switch to the root account.
cd /var/www/html # Move to the default location of the Apache server.
ls # Check the files. If you just installed it, there should be only one file named "index.html".
vim phpinfo.php # Create or open a PHP file named "phpinfo".
i # Change to insert mode and type the following contents.
<?php
	phpinfo();
?>
ESC key # Return to command mode in Vim.
:wq # Save and exit Vim.
sudo service apache2 start # Start the Apache server.

Open a web browser and enter http://localhost/phpinfo.php to run it.

"phpinfo();" is a command that retrieves PHP version information and details, so the following output will be displayed.



2023년 4월 9일 일요일

The Evolution of Authorization: A Brief History Leading up to OAuth 2.0

The Importance of HTTP and Login Authentication Technology

When the Internet was first created, the HTTP protocol was a kind of rule to quickly exchange information. Servers simply prepared data and responded to requests without storing client information, which was known as the stateless characteristic.

However, as technology progressed, servers needed to identify who the client was. For example, shopping websites needed to display different items in each client's shopping cart. This led to the creation of various login authentication technologies.

Cookie

The first login authentication technology, cookies, stored the user ID and password on the server. When the client sent the ID and password to the server, the server checked them.

Cookies are typically stored in the HTTP URI's header, which is easy to access during information requests. Therefore, attackers often intercepted the information in the middle of the request and obtained the user ID and password.

Session

Session created a storage area to store the client's user ID and password and generated a unique Session ID to save it. When the client logged in, the client sent the Session ID instead of the user ID and password to the server, which used it to identify the client.

Since the user ID and password were only sent once, it was difficult to intercept them. Also, the Session ID was not related to the user ID and password, which made it more secure than cookies. However, it was still possible to log in using the Session ID, so security was still not enough.

To improve security, the Session ID was given an expiration time. However, it was inconvenient for clients and not very effective.

Access Token

Next, the Access Token was created. Like the Session ID, it is used for authentication, but the Access Token collects and encrypts the necessary information for authentication. This information is usually stored using the JSON Web Token (JWT) method.

JWT (JSON Web Token) Components

[Header].[Payload].[Signature]
  • Header: Contains the type and encryption method of the Access Token.

    {
      "typ": "JWT",
      "alg": "SHA256"
    }
    
  • Payload: Contains the necessary information for authentication, such as the token creation time, activation date, expiration date, etc. It does not contain client-related information (such as ID and password).

    {
      "sub": "1",
      "iss": "ori",
      "exp": 1636989718,
      "iat": 1636987918
    }
    
  • Signature: A string created using the SHA256 algorithm specified in the header, using the information in the payload and the server's private key. This is used to authenticate the token, so if the token is tampered with, it can be detected immediately.

    {
      "SHA": "9F69FA131C4CA518D3CCE296013D9A3C2B4AA63CA02583C8B6F1F7F354A1D874"
    }
    

Access Token and Refresh Token

One problem with Access Tokens is that they cannot create a new token before the expiration of the current token because the encryption uses an expiration date. However, if the expiration date is set to a short period of time, it is inconvenient for clients. This led to the creation of the Refresh Token.

Access Tokens are issued with a short expiration date, while Refresh Tokens are issued with a long expiration date. When the Access Token expires, the client uses the Refresh Token to authenticate and obtain a new Access Token.

Since the Refresh Token is only sent to the server when the Access Token expires, it is difficult to intercept. Also, since Access Tokens are frequently reissued, it becomes more difficult to intercept them.

OAuth (Open Authorization) 1.0

OAuth 1.0 added another application to protect IDs and passwords. This application was used as an independent service for user authentication and was called the consumer.

User: User

Service provider: Google OAuth Service

Consumer: Twitter

  1. The user attempts to log in to Twitter.
  2. Twitter requests a Request Token from Google OAuth Service.
  3. Google OAuth Service checks the Key and Secret sent by Twitter and generates a Request Token.
  4. Twitter shows the login page through Google OAuth Service (redirect).
  5. The user's login information (ID and password) is sent to Google OAuth Service.
  6. Google OAuth Service checks the Request Token and the ID and password (login authentication).
  7. Google OAuth Service informs Twitter that the authentication was successful.
  8. Twitter requests an Access Token from Google OAuth Service since the user has been authenticated.
  9. Google OAuth Service generates and sends an Access Token to Twitter.
  10. Twitter gives the user the Access Token. Connection complete.
  11. The user logs in using the Access Token until it expires.

In summary, OAuth 1.0 is a way for the user (User), the site the user wants to use (Consumer), and another web service that holds user information (Service Provider) to interact with each other to function. However, this method is complicated to implement, and the lack of Refresh Token means that a new token cannot be created before the expiration of the existing Access Token. Additionally, authentication was only possible through web pages.

OAuth (Open Authorization) 2.0

Disadvantages of OAuth 1.0 Improvements in OAuth 2.0
Lack of security during communication Use of HTTPS instead of HTTP
Too complex Simplification of functionality
Inability to issue new tokens before the expiration of access tokens Introduction of Refresh Tokens
Login authentication only possible through web pages Expansion of login authentication methods

In addition, the separation of the server responsible for login authentication and the server that processes user requests made it difficult for Access Tokens, user IDs, and passwords to be compromised.

Resource Server A server that manages resources and responds to requests with an Access Token
Authorization Server A server that authenticates clients and issues tokens for clients to access services on the resource server
Resource Owner A user who owns an account on the resource server
Client A website that uses the resource server's API to retrieve data
Access Token A token that allows requests for resources to the resource server
Refresh Token A token that allows the client to request a new Access Token from the authorization server

Authorization Code Grant

  • Recommended usage
  • High level of security: Access Token is not directly transmitted to the client, preventing potential leaks
  • Generally used on the backend server

  1. The user sends their ID and password to the authorization server via the client. If the login is successful, the authorization server issues an authorization code to the user.
  2. The client sends the authorization code to the authorization server and requests an Access Token. The authorization server verifies the authorization code and issues an Access Token and a Refresh Token.
  3. The client can access the resources on the resource server using the issued Access Token.
  4. When the Access Token expires, the client uses the Refresh Token to request a new Access Token from the authorization server.

Implicit Grant

  • Recommended to use
  • The most commonly used authentication method
  • Typically used when a user logs into a shopping mall (User Agent Application)

  1. The user attempts to log in to the authentication server using the client. After the authentication server completes the login authentication, it issues an access token.
  2. The authentication server returns a redirection response that includes the access token to the client. The access token is included in the URI fragment.
  3. The client extracts the access token from the redirection response and attempts to access the resource on the resource server using the token. After the resource server verifies the validity of the access token with the authentication server, the client can access the requested resource.

Resource Owner Password Credentials Grant

  • Not recommended to use
  • Can be used in all types of applications
  • Typically used in API connections

  1. The user submits their ID, password, and client information to the authentication server using the client. After the authentication server authenticates the login and client information, it issues an access token.
  2. The client can access the resource server's resource using the issued access token.

Client Credentials Grant

  • Not recommended
  • Access token can be issued directly based on client authentication
  • Used to access application data, not user-related data

  1. The client sends its client information (client ID and client secret) to the authorization server. If the client information is authenticated by the authorization server, an access token is issued.
  2. The client can use the access token to access resources on the resource server.

Device Code Grant

  • Not recommended
  • Authentication is carried out using a separate device
  • Used when there is no web browser or limited input device (e.g., smart TV, game console)

  1. The user starts the client application on the device with limited input. The client requests a device code, a user code, and a verification URL from the authorization server.
  2. The authorization server returns a device code, a user code, and a verification URL to the client. The user goes to the verification URL on a different device (e.g., smartphone, computer) to enter the user code and complete the login.
  3. The client sends the device code and client identifier to the authorization server and requests an access token.
  4. After the user completes the login authentication on the verification URL, the authorization server issues an access token, and the client can use the access token to access resources on the resource server.

Refresh Token Grant

Access tokens are refreshed using a refresh token, and the original access token expires after a certain period of time.

2023년 4월 5일 수요일

HTTP Status Codes: A Guide to Status Codes in the Request-Response Cycle

 

Definition

HTTP status codes are codes that are generated during the request-response cycle between a client and a server. They indicate the status of the request made by the client and the response provided by the server.

HTTP Status Codes

1xx (Informational): Request received, continuing process

  • 100 Continue: The server has received the request headers and the client should proceed to send the request body.
  • 101 Switching Protocols: The server agrees to switch to the protocol specified in the Upgrade header field.

2xx (Successful): The request was successfully received, understood, and accepted

  • 200 OK: The request was successful and the server has returned the requested data.
  • 201 Created: The request was successful and a new resource has been created.
  • 204 No Content: The request was successful, but there is no response body to return.
  • 206 Partial Content: The server is delivering only a portion of the resource due to a range header sent by the client.

3xx (Redirection): Further action needs to be taken in order to complete the request

  • 301 Moved Permanently: The requested resource has been permanently moved to a new location, and all future requests should be directed to the new location.
  • 302 Found: The requested resource has been temporarily moved to a different location, but future requests may still be directed to the original location.
  • 304 Not Modified: The requested resource has not been modified since the last time it was accessed by the client, and can be retrieved from the client's cache.
  • 307 Temporary Redirect: The requested resource has been temporarily moved to a different location, but future requests should still be directed to the original location.

4xx (Client Error): The request contains bad syntax or cannot be fulfilled by the server

  • 400 Bad Request: The server cannot understand the request due to bad syntax or an invalid request message.
  • 401 Unauthorized: The request requires authentication, and the client must authenticate itself to get the requested response.
  • 403 Forbidden: The server understands the request, but the client is not authorized to access the requested resource.
  • 404 Not Found: The requested resource could not be found on the server.

5xx (Server Error): The server failed to fulfill a valid request

  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
  • 502 Bad Gateway: The server received an invalid response from a server acting as a gateway or proxy.
  • 503 Service Unavailable: The server is currently unable to handle the request due to a temporary overload or maintenance of the server.
  • 504 Gateway Timeout: The server acting as a gateway or proxy did not receive a timely response from the upstream server.

There are many other status codes in addition to those listed above, but these are the most commonly used ones.

HTTP Protocol Requests and Responses: Communication between Client and Server

Definition

HTTP (Hyperext Transfer Protocol) is one of the communication protocols used on the internet to exchange data. HTTP is responsible for communication between web browsers and web servers, where the client requests data from the server and the server responds with the data.

How it Works

HTTP works on a request-response model, where the client typically requests a web page and the server responds with the requested HTML file, images, videos, and other resources.

Components of the HTTP Protocol

  1. HTTP Method: The method used by the client to send a request to the server. The most common HTTP methods are GET, POST, PUT, and DELETE.
  2. URI (Uniform Resource Identifier): A string used to uniquely identify a resource on the internet.
  3. Header: The part of the request or response that contains metadata. Headers can contain information about the request or response, authentication information, and cache control information.
  4. Body: The part of the request or response that contains the actual data being transmitted. Generally, the body is not used in a GET request, but in a POST or PUT request, data is sent in the body.

HTTP Request Example

[http method] [URL] [HTTP version]

[header]

GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
  • HTTP Method: GET
  • URI: /index.html
  • Version: HTTP/1.1
  • Header: Host, User-Agent, Accept, Accept-Language, Connection

HTTP Response Example

[HTTP version] [status code]

[Header]

[Body]

HTTP/1.1 200 OK
Date: Wed, 12 May 2021 10:12:34 GMT
Server: Apache/2.4.29 (Unix)
Last-Modified: Fri, 01 May 2020 12:34:56 GMT
ETag: "abcd1234efgh5678"
Content-Length: 1234
Content-Type: text/html

<!DOCTYPE html>
<html>
<head>
	<title>Example Web Page</title>
</head>
<body>
	<h1>Hello, World!</h1>
	<p>This is an example web page.</p>
</body>
</html>

  • Version: HTTP/1.1
  • Status Code: 200 OK
  • Header: Date, Server, Last-Modified, ETag, Content-Length, Content-Type
  • Body: HTML document

Logic Gate Truth Tables & Definitions

Logic Gate Truth Tables Java Code !A // NOT A&B // AND ~(A&B) // NAND A|B // OR ~(A|B) // XOR A^B // XOR ~(A^B) // XNOR ~A // Inve...