이 블로그 검색

2023년 4월 30일 일요일

Powerfull Integer Problem Solved: Uncover the Most Efficient Java Algorithm

 

Problem

Problem_Link

Problem Solving Approach

  1. Traverse through all the numbers in the intervals and store their frequencies in a HashMap.
  2. Sort the hashmap based on the keys.→in worst case, O(n log n)
  3. Find the maximum powerful integer by iterating through the sorted hashmap, which occurs at least k times.

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

https://github.com/eunhanlee/powerfullInteger/blob/master/read%20me.md

import java.util.*;
class Solution {

    /**
     * This method takes in the number of intervals n, the 2D integer array of intervals interval, and the minimum number of occurrences k for a number to be considered powerful.
     * It returns the powerful integer which occurs at least k times. If multiple integers have at least k occurrences, the maximum integer out of all those elements is returned.
     * If no integer occurs at least k times, -1 is returned.
     *
     * @param n         the number of intervals
     * @param interval  the 2D integer array of intervals where interval[i] = [start, end]
     * @param k         the minimum number of occurrences for a number to be considered powerful
     * @return the powerful integer which occurs at least k times, or -1 if no integer occurs at least k times
     */
    public static int powerfullInteger(int n, int[][] interval, int k) {
        // A hashmap to store the frequency of each number
        Map<Integer, Integer> map = new HashMap<>();
        // The maximum powerful integer that occurs at least k times, if there is no, return -1
        int maxPowerful = -1;

        // Loop through each interval and update the frequency of each number in the hashmap
        for (int i = 0; i < n; i++) {
            for (int j = interval[i][0]; j <= interval[i][1]; j++) {
                map.put(j, map.getOrDefault(j, 0) + 1);
            }
        }

        // Sort the hashmap by key
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
        list.sort(Map.Entry.comparingByKey());

        // find the maximum powerful integer
        for (Map.Entry<Integer, Integer> val : list) {
            if (val.getValue() >= k) {
                maxPowerful = val.getKey();
            }
        }

        return maxPowerful;
    }
}

Ascii Table

 Decimal ASCII table

Octal Ascii Table

Hexadecimal Ascii Table





Hex

Oct

Dec

Char

0

0

0

Ctrl-@ NUL

1

1

1

Ctrl-A SOH

2

2

2

Ctrl-B STX

3

3

3

Ctrl-C ETX

4

4

4

Ctrl-D EOT

5

5

5

Ctrl-E ENQ

6

6

6

Ctrl-F ACK

7

7

7

Ctrl-G BEL

8

10

8

Ctrl-H BS

9

11

9

Ctrl-I HT

0A

12

10

Ctrl-J LF

0B

13

11

Ctrl-K VT

0C

14

12

Ctrl-L FF

0D

15

13

Ctrl-M CR

0E

16

14

Ctrl-N SO

0F

17

15

Ctrl-O SI

10

20

16

Ctrl-P DLE

11

21

17

Ctrl-Q DCI

12

22

18

Ctrl-R DC2

13

23

19

Ctrl-S DC3

14

24

20

Ctrl-T DC4

15

25

21

Ctrl-U NAK

16

26

22

Ctrl-V SYN

17

27

23

Ctrl-W ETB

18

30

24

Ctrl-X CAN

19

31

25

Ctrl-Y EM

1A

32

26

Ctrl-Z SUB

1B

33

27

Ctrl-[ ESC

1C

34

28

Ctrl- FS

1D

35

29

Ctrl-] GS

1E

36

30

Ctrl-^ RS

1F

37

31

Ctrl_ US

20

40

32

Space

21

41

33

!

22

42

34

"

23

43

35

#

24

44

36

$

25

45

37

%

26

46

38

&

27

47

39

'

28

50

40

(

29

51

41

)

2A

52

42

*

2B

53

43

+

2C

54

44

,

2D

55

45

-

2E

56

46

.

2F

57

47

/

30

60

48

0

31

61

49

1

32

62

50

2

33

63

51

3

34

64

52

4

35

65

53

5

36

66

54

6

37

67

55

7

38

70

56

8

39

71

57

9

3A

72

58

:

3B

73

59

;

3C

74

60

3D

75

61

=

3E

76

62

3F

77

63

?

40

100

64

@

41

101

65

A

42

102

66

B

43

103

67

C

44

104

68

D

45

105

69

E

46

106

70

F

47

107

71

G

48

110

72

H

49

111

73

I

4A

112

74

J

4B

113

75

K

4C

114

76

L

4D

115

77

M

4E

116

78

N

4F

117

79

O

50

120

80

P

51

121

81

Q

52

122

82

R

53

123

83

S

54

124

84

T

55

125

85

U

56

126

86

V

57

127

87

W

58

130

88

X

59

131

89

Y

5A

132

90

Z

5B

133

91

[

5C

134

92

5D

135

93

]

5E

136

94

^

5F

137

95

_

60

140

96

`

61

141

97

a

62

142

98

b

63

143

99

c

64

144

100

d

65

145

101

e

66

146

102

f

67

147

103

g

68

150

104

h

69

151

105

i

6A

152

106

j

6B

153

107

k

6C

154

108

l

6D

155

109

m

6E

156

110

n

6F

157

111

o

70

160

112

p

71

161

113

q

72

162

114

r

73

163

115

s

74

164

116

t

75

165

117

u

76

166

118

v

77

167

119

w

78

170

120

x

79

171

121

y

7A

172

122

z

7B

173

123

{

7C

174

124

|

7D

175

125

}

7E

176

126

~

7F

177

127

DEL

Hexadecimal Ascii Table

 Decimal ASCII table

Octal Ascii Table

Ascii Table






0

Ctrl-@ NUL

1

Ctrl-A SOH

2

Ctrl-B STX

3

Ctrl-C ETX

4

Ctrl-D EOT

5

Ctrl-E ENQ

6

Ctrl-F ACK

7

Ctrl-G BEL

8

Ctrl-H BS

9

Ctrl-I HT

0A

Ctrl-J LF

0B

Ctrl-K VT

0C

Ctrl-L FF

0D

Ctrl-M CR

0E

Ctrl-N SO

0F

Ctrl-O SI

10

Ctrl-P DLE

11

Ctrl-Q DCI

12

Ctrl-R DC2

13

Ctrl-S DC3

14

Ctrl-T DC4

15

Ctrl-U NAK

16

Ctrl-V SYN

17

Ctrl-W ETB

18

Ctrl-X CAN

19

Ctrl-Y EM

1A

Ctrl-Z SUB

1B

Ctrl-[ ESC

1C

Ctrl- FS

1D

Ctrl-] GS

1E

Ctrl-^ RS

1F

Ctrl_ US

20

Space

21

!

22

"

23

#

24

$

25

%

26

&

27

'

28

(

29

)

2A

*

2B

+

2C

,

2D

-

2E

.

2F

/

30

0

31

1

32

2

33

3

34

4

35

5

36

6

37

7

38

8

39

9

3A

:

3B

;

3C

3D

=

3E

3F

?

40

@

41

A

42

B

43

C

44

D

45

E

46

F

47

G

48

H

49

I

4A

J

4B

K

4C

L

4D

M

4E

N

4F

O

50

P

51

Q

52

R

53

S

54

T

55

U

56

V

57

W

58

X

59

Y

5A

Z

5B

[

5C

5D

]

5E

^

5F

_

60

`

61

a

62

b

63

c

64

d

65

e

66

f

67

g

68

h

69

i

6A

j

6B

k

6C

l

6D

m

6E

n

6F

o

70

p

71

q

72

r

73

s

74

t

75

u

76

v

77

w

78

x

79

y

7A

z

7B

{

7C

|

7D

}

7E

~

7F

DEL

Octal Ascii Table

Decimal ASCII table

Hexadecimal Ascii Table

Ascii Table



0

Ctrl-@ NUL

1

Ctrl-A SOH

2

Ctrl-B STX

3

Ctrl-C ETX

4

Ctrl-D EOT

5

Ctrl-E ENQ

6

Ctrl-F ACK

7

Ctrl-G BEL

10

Ctrl-H BS

11

Ctrl-I HT

12

Ctrl-J LF

13

Ctrl-K VT

14

Ctrl-L FF

15

Ctrl-M CR

16

Ctrl-N SO

17

Ctrl-O SI

20

Ctrl-P DLE

21

Ctrl-Q DCI

22

Ctrl-R DC2

23

Ctrl-S DC3

24

Ctrl-T DC4

25

Ctrl-U NAK

26

Ctrl-V SYN

27

Ctrl-W ETB

30

Ctrl-X CAN

31

Ctrl-Y EM

32

Ctrl-Z SUB

33

Ctrl-[ ESC

34

Ctrl- FS

35

Ctrl-] GS

36

Ctrl-^ RS

37

Ctrl_ US

40

Space

41

!

42

"

43

#

44

$

45

%

46

&

47

'

50

(

51

)

52

*

53

+

54

,

55

-

56

.

57

/

60

0

61

1

62

2

63

3

64

4

65

5

66

6

67

7

70

8

71

9

72

:

73

;

74

75

=

76

77

?

100

@

101

A

102

B

103

C

104

D

105

E

106

F

107

G

110

H

111

I

112

J

113

K

114

L

115

M

116

N

117

O

120

P

121

Q

122

R

123

S

124

T

125

U

126

V

127

W

130

X

131

Y

132

Z

133

[

134

135

]

136

^

137

_

140

`

141

a

142

b

143

c

144

d

145

e

146

f

147

g

150

h

151

i

152

j

153

k

154

l

155

m

156

n

157

o

160

p

161

q

162

r

163

s

164

t

165

u

166

v

167

w

170

x

171

y

172

z

173

{

174

|

175

}

176

~

177

DEL

Decimal ASCII code table

Octal Ascii Table

Hexadecimal Ascii Table

Ascii Table






0

Ctrl-@ NUL

1

Ctrl-A SOH

2

Ctrl-B STX

3

Ctrl-C ETX

4

Ctrl-D EOT

5

Ctrl-E ENQ

6

Ctrl-F ACK

7

Ctrl-G BEL

8

Ctrl-H BS

9

Ctrl-I HT

10

Ctrl-J LF

11

Ctrl-K VT

12

Ctrl-L FF

13

Ctrl-M CR

14

Ctrl-N SO

15

Ctrl-O SI

16

Ctrl-P DLE

17

Ctrl-Q DCI

18

Ctrl-R DC2

19

Ctrl-S DC3

20

Ctrl-T DC4

21

Ctrl-U NAK

22

Ctrl-V SYN

23

Ctrl-W ETB

24

Ctrl-X CAN

25

Ctrl-Y EM

26

Ctrl-Z SUB

27

Ctrl-[ ESC

28

Ctrl- FS

29

Ctrl-] GS

30

Ctrl-^ RS

31

Ctrl_ US

32

Space

33

!

34

"

35

#

36

$

37

%

38

&

39

'

40

(

41

)

42

*

43

+

44

,

45

-

46

.

47

/

48

0

49

1

50

2

51

3

52

4

53

5

54

6

55

7

56

8

57

9

58

:

59

;

60

61

=

62

63

?

64

@

65

A

66

B

67

C

68

D

69

E

70

F

71

G

72

H

73

I

74

J

75

K

76

L

77

M

78

N

79

O

80

P

81

Q

82

R

83

S

84

T

85

U

86

V

87

W

88

X

89

Y

90

Z

91

[

92

93

]

94

^

95

_

96

`

97

a

98

b

99

c

100

d

101

e

102

f

103

g

104

h

105

i

106

j

107

k

108

l

109

m

110

n

111

o

112

p

113

q

114

r

115

s

116

t

117

u

118

v

119

w

120

x

121

y

122

z

123

{

124

|

125

}

126

~

127

DEL

2023년 4월 29일 토요일

find number Problem Solved: Uncover the Most Efficient Java Algorithm

Problem

Problem_Link

Problem Solving Approach

  • Odd digit numbers have a pattern

    1

    3

    5

    7

    9

    11

    13

    15

    17

    19

    31

    33

    35

    37

    39

    51

    53

    55

    57

    59

    71

    73

    75

    77

    79

    91

    93

    95

    97

    99

    101

    103

    105

    107

    109

  • As seen above, the pattern repeats every 5 numbers.

  • Therefore, we can know the position of each digit by dividing N by 5.

  • If we know the position of each digit, we can find out what number will be in that position (1, 3, 5, 7, 9)

  • Let's take the 13th odd digit number as an example

    • The rightmost digit (ones place) in 13 is the 3rd.

    • According to the odd digit pattern, the third number is 5.

    • The second rightmost digit (tens place) in 13 is the 2nd.

    • According to the odd digit pattern, the second number is 3.

    • In conclusion, the 13th odd digit number is 35.

  • Let's take the 27th odd digit number as an example

    • The rightmost digit (ones place) in 27 is the (27%5) 2nd.

    • According to the odd digit pattern, the second number is 3.

    • Excluding the calculated digits from 27, we get 27-27%5 = 27/5=5.

    • The second rightmost digit (tens place) is the (5%5) 5th.

    • According to the odd digit pattern, the fifth number is 9.

    • In conclusion, the 27th odd digit number is 93.

  • There is something slightly incorrect with the above pattern. For example, 5%5 is 0. However, we want the pattern to follow the table above.

    - n % 5 = 0 //5th number = 9
    - n % 5 = 1 //1th number = 1
    - n % 5 = 2 //2th number = 3
    - n % 5 = 3 //3th number = 5
    - n % 5 = 4 //4th number = 7

    To fix this, we subtract 1 from n.

    - n-1 % 5 = 0 //1th number = 1
    - n-1 % 5 = 1 //2th number = 3
    - n-1 % 5 = 2 //3th number = 5
    - n-1 % 5 = 3 //4th number = 7
    - n-1 % 5 = 4 //5th number = 9
  • Lastly, when we get 0, 1, 2, 3, 4, the actual numbers we want are 1, 3, 5, 7, 9. To optimize this, we multiply by 2 and add 1.

    0*2+1=1
    2*2+1=3
    3*2+1=5
    4*2+1=7
    5*2+1=9

Time O(log n), Space O(1)

class Solution
{
    /**
     * Finds the Nth number containing only odd digits.
     *
     * @param N The position of the desired number.
     * @return The Nth number containing only odd digits.
     */
    public long findNumber(long N)
    {
        // The variable to store the final result
        long result = 0;
        // The variable to represent the digit position (1, 10, 100, ...)
        long position = 1;

        // Continue until N is greater than 0
        while (N > 0)
        {
            // Calculate the odd digit by subtracting 1 from N and dividing by 5
            long oddDigit = ((N - 1) % 5) * 2 + 1;
            // Subtract 1 from N and divide by 5 to prepare for the next digit calculation
            N = (N - 1) / 5;
            // Add the odd digit multiplied by the current position to the result
            result += oddDigit * position;
            // Move to the next digit position
            position *= 10;
        }

        // Return the Nth number containing only odd digits
        return result;
    }
}

Explanation

  • The given integer N is repeatedly divided by 5 during the computation process, which reduces its value. In this process, odd-digit numbers are generated. The loop continues as long as N is greater than 0.

  • With each iteration, N is updated to (N - 1) / 5. This process reduces N by more than half, causing N to decrease significantly with each iteration. Since N is almost halved with each iteration, the time complexity can be considered as O(log N).

2023년 4월 25일 화요일

SQL Injection Data Extraction Process

 


Presume

Make a guess about what SQL query the server might be using.

Based on the results, make a guess about what the server is doing, such as whether it is performing authentication and identification at the same time or separately, and whether it can search for the term "over" to find "overwatch".

Vulnerability Assessment

Check whether SQL injection is possible.

Avoid using comments in queries as much as possible.

Check whether the login authentication and identification are separated or done together.

Select SQL Query

Choose an appropriate SQL injection method based on whether a list is displayed or not when searching.

For example, if a list is displayed, use In-band SQLi. If an error message is displayed, use Error-based SQLi. If only login failure messages are displayed, use Blind SQLi.

Identifying Data Output Locations

If a list is displayed, determine how many columns are being used, as the number of columns displayed may differ from the number of columns searched by the server.

Create Base SQL Injection

Create a basic template to avoid mistakes later.

Retrieve Database, Table, and Column Names

Now that the SQL query to use and the data output position have been identified, retrieve the necessary information.

Extract Data

SQL injection successful.

How to Find Substrings in a String

 

Definition of substring

A sequence of consecutive characters within a larger string.

In other words, it is a smaller string that is written without changing the order of the characters selected from the original string or skipping any characters in the middle.

Example of substrings

Substrings of "abc": "", "a", "b", "c", "ab", "bc", "abc"

In mathematics, the empty string ("") is also considered a substring.

However, in programming problems, whitespace characters are usually not considered as substrings.

How to find substrings



Example

public static int countSubstring(String str) {
    int n = str.length();
    return n*(n+1)/2;
}

2023년 4월 24일 월요일

Efficient Algorithm in Java for Solving the Maximize The Number Problem

 Problem

Problem_Link

Problem Solving Method

  • Goal: Swap the 1 at the end and the 0 at the front.
  • Condition: The number of swaps must be less than the given k.
  • Use StringBuilder: Since the string needs to be swapped, StringBuilder is the most efficient method.
  • The last 1 must only be needed when the number of swaps is less than k.
  • The loop ends when:
    1. The number of swaps is greater than k.
    2. The loop is performed for the given length.

So, two pointers are used. 

The first pointer (i) iterates to find 0, and the second pointer (lastOneIndex) finds the 1 at the end.

After both pointers have found their values, they swap them, and if the number of swaps exceeds K, the loop stops.

Time complexity: O(n), Space complexity: O(n)

class Solution {
    public static String maximumNumber(String S, int K) {
        // Convert string S to StringBuilder for easy modification
        StringBuilder sb = new StringBuilder(S);
        int n = S.length(); // Length of the string
        int lastOneIndex = n - 1; // Variable to store the index of the last 1
        int counter = 0; // Variable to store the number of swaps

        // Find the index of the last 1 in the back
        // This index must be greater than i and the number of swaps must be less than K.
        for (int i = 0; i < n && counter < K; i++) {
            while (lastOneIndex > i && sb.charAt(lastOneIndex) == '0') {
                lastOneIndex--;
            }

            // If the current position is 0 and the last 1 is behind the current position, swap
            if (sb.charAt(i) == '0' && lastOneIndex > i) {
                sb.setCharAt(i, '1'); // Change the current position's 0 to 1
                sb.setCharAt(lastOneIndex, '0'); // Change the last 1 position to 0
                counter++; // Increase the number of swaps
            }
        }

        // Return the modified string
        return sb.toString();
    }
}

2023년 4월 23일 일요일

Efficient Algorithm in Java for Solving the Wave Array Problem

 

Problem

Problem_Link

Solution

  • Given: a sorted array
  • Condition: Convert to wave array, where the elements are sorted in wave-like order (higher, lower, higher)
  • Condition2: lexicographically smallest.

Given the values and conditions, we can solve the problem by simply swapping elements in the sorted array without the need for searching.

The condition "lexicographically smallest" implies using compareTo for comparison, which is based on Unicode.

Therefore, we can solve the problem by simply iterating through half of the sorted array and swapping the current element with the previous even element.

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

class Solution {
    public static void convertToWave(int n, int[] a) {
        // Iterate through the array starting from index 1 and incrementing by 2
        // Swap the current element with the previous even element
        for(int i = 1; i < n; i += 2){
            // Swap the current element with the previous even element
            int temp = a[i];
            a[i] = a[i - 1];
            a[i - 1] = temp;
        }
    }
}

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.



Web Hacking: Cookie Tampering, Directory Traversal, Session Hijacking, Authentication Bypass, Brute Force Attack

Web hacking is a common technique used by attackers to exploit vulnerabilities in web applications. In this article, we will explore some common types of web attacks, including cookie tampering, directory traversal, session hijacking, authentication bypass, and brute force attacks.

Cookie Tampering

Definition

Cookie tampering refers to the malicious act of modifying cookie values used in web applications.

Purpose

Cookies are stored on the client-side and are used to maintain the state between the client and server (such as authentication, session management, user identification, etc.).

Prevention

  • Authentication and encryption for cookies
  • Filtering and validation for input values
  • Filtering for output values
  • Appropriate cookie settings based on the purpose and duration of use

Example

Using Burp Suite:

Let's confirm a successful login. The response status code is 302.

A status code in the 300s indicates redirection. This means that the user has been redirected to another webpage.

Let's check the cookies. We can see that the username is stored in the cookie, rather than using a session to differentiate users.

By changing the value of loginUser to "admin," we can steal authorization through cookie tampering.

Directory Traversal

Another name

  • File Path Traversal

Definition

Directory traversal is an attack that involves guessing the paths of files or directories within a website in order to directly access those files or directories.

Prevention

To prevent these vulnerabilities, it is important to:

  • Limit access to files or directories
  • Filter and validate input values
  • Filter output values

Example

Using Burp Suite:

If the homepage is split into step1 and step2, you can try to access step3 directly without logging in.

Session Hijacking

Another name

  • Session Fixation

Definition

Session hijacking involves an attacker acquiring a valid session and then using that session to impersonate the user or access other accounts.

Prevention

Proper session management is essential:

  • Generate session IDs using random and unpredictable values
  • Set a reasonable session expiration time
  • Use encrypted protocols such as SSL or TLS to transmit session IDs

Example

  1. The attacker monitors network traffic to capture the user's session ID.
  2. The attacker uses the stolen session ID to log in to the website as an authenticated user.
  3. The attacker can now perform malicious actions with the user's privileges.

Authentication Bypass

Another name

  • Login Bypass

Definition

Authentication bypass occurs when login is possible without verifying the ID and password or when login can be done through other means.

Prevention

  • Authenticate and verify login credentials

Example

  1. The attacker discovers a vulnerable authentication mechanism (e.g., weak password policy, missing input validation).
  2. The attacker finds a way to bypass the authentication mechanism (e.g., SQL injection, using default passwords, tampering with authentication tokens).
  3. The attacker bypasses the authentication process and gains unauthorized access to the system.
  4. The attacker can now steal information or manipulate the system without being authenticated.

Brute Force Attack

Definition

A brute force attack is an attack that guesses passwords by trying all possible combinations.

Prevention

  • Encourage users to use safe passwords
  • Use blacklisting to lock accounts after a certain number of failed logins
  • Add security features such as CAPTCHA

Example

Using Burp Suite:

Although the Intruder function in Burp Suite can be used, it is much faster to use Python:

import httplib2

# Suppose that the GET request is made to example.php?otpNum=0000.
# URL of target website (in this case, example.php)
url = "<http://example.php>"

# httplib2 instance creation
http_obj = httplib2.Http()

# Range of otp_num (0000 to 9999)
for otp_num in range(10000):
    # Format otp_num into a 4-digit number (e.g., 0035)
    otp_num_formatted = f"{otp_num:04d}"

    # Add otp_num parameter to GET request
    request_url = f"{url}?otpNum={otp_num_formatted}"
    response, content = http_obj.request(request_url, method="GET")

    # Depending on how the results are found, the processing can be modified.
    # For example, if the server returns a specific message, it can be checked.
    # Use print(content) to check and set success conditions.
    if not b"Login Fail" in content:
        print(f"Success! OTP number is: {otp_num_formatted}")
        break
    else:
        print(f"Failed for OTP number: {otp_num_formatted}")


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