Ivan Christian
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # HW 1 System Security ## 1 ### 1.1 - Minimum Exposure: - Information about the non matching password (`check` function) is exposed. The length of the password is exposed as well as the left-most incorrect byte by the `check` function. - Returning messages indicating for errors on the length and the index exposes information about password, hence violating the minimum exposure principle. - Tracability: - None of the errors are logged and documented, which makes the attempts to guess the password untraceable, therefore violating the traceability principle. - Complete Mediation: - Checking the password length and the index is not monitored or controlled, therefore violating the complete mediation principle. ### 1.2 ```python= import os import random ''' Default Class ''' class BlackBox(object): def __init__(self): len_ = random.randint(100, 1000) self._passwd = os.urandom(len_) def check(self, user_passwd): if len(user_passwd) != len(self._passwd): return "Error:len" for i in range(len(user_passwd)): if user_passwd[i] != self._passwd[i]: return "Error:idx:%d" % i return "OK" def check_pw_length(bb_pw): ''' Find the password length ''' # Generate a string of length 100 - 1000 ( assuming this is given ) for i in range(100, 1001): len_check = os.urandom(i) if bb_pw.check(len_check) != "Error:len": return i def brute_force(bb_pw, pw_len): pw_list = [0] * pw_len for i in range(pw_len): byte_correct = False while not byte_correct: pw_int = int.from_bytes(pw_list, byteorder='big') pw_guess = pw_int.to_bytes(pw_len, byteorder='big') result = bb_pw.check(pw_guess) if f"Error:idx:{i}" in result: pw_list[i] += 1 else: byte_correct = True return result, pw_guess def main(): blackbox_pw = BlackBox() pw_len = check_pw_length(blackbox_pw) print(f'Guessing length of password : {pw_len}, Actual length of password : {len(blackbox_pw._passwd)}') result, pw_guess = brute_force(blackbox_pw, pw_len) print(f'Guessed password : {pw_guess} and the results is {result}') if __name__ == '__main__': main() ``` ##### Result: ``` Guessing length of password : 146, Actual length of password : 146 Guessed password : b'!,\x00\xce\x9c\xb5ajN\xc4\x08\xa9\x82(\xe6\xa8s}\xa4\x07\xf4\xf9\x02\xd2E\x1f\xc4\xcc\xc7|\xb4O\xf4RN\x0b\xc6\x0cC~\x8dr\xe5\xbf\x12~\x1a\xc6\x89\xcd\x16H$\x03\xaag]?\x0b\x02cu\x9e\x0f\x80\xe0~A\x88\xeb\xf6Q\x9b*\x17\x00\xeb\xafy\xd1<\x90\xe5\xa7#$\xc8\xcd\x16\x1b\x8b+\x04\x1f\xdc`A\xb4\x9d\x81\xfe\xa6\x18v\xce\x82d\xa9R\xc9\xfb\xdcxk\xe1\x0b\xf98\x0e\x95^\xda\xfch\x98\x07\x89\xcc\x16\x14\xa4\x18\x8e\xa9\xae\x89JsPQfJ\xee2\xb2\x82' and the results is OK ``` ### 1.3a - No information about what is wrong should be displayed to the users or guessers ( Prevents brute-force as well as minimising exposure ). - Loggings and counters on how many tries should be created in order to check for unusal failures and errors. - Program should go to sleep to reduce time avaiable for brute force attacks. ### 1.3b ```python= import os import random from time import sleep class SecureBlackBox(object): def __init__(self): self._error = 0 len_ = random.randint(100, 1000) self._passwd = os.urandom(len_) def check(self, user_passwd): filename = 'log.txt' if user_passwd == self._passwd: self._error = 0 if os.path.isfile(filename): with open('log.txt', 'w+') as f: f.write(f'Password Correct.\n') else: with open('log.txt', 'a+') as f: f.write(f'Password Correct.\n') return "OK" elif self._error >= 3: # Pause the program to control bruteforce attacks print(f"Too many consecutive errors. Please wait {self._error * 10} seconds before trying again.") sleep(10 * self._error) self._error += 1 if os.path.isfile(filename): with open('log.txt', 'w+') as f: f.write(f'Too many errors, Error : {self._error}, Tried with : {user_passwd}\n') else: with open('log.txt', 'a+') as f: f.write(f'Too many errors, Error : {self._error}, Tried with : {user_passwd}\n') return "Error." # 2 or fewer consecutive errors => return simple "Error" message else: if os.path.isfile(filename): with open('log.txt', 'w+') as f: f.write(f'Error : {self._error}, Tried with : {user_passwd}\n') else: with open('log.txt', 'a+') as f: f.write(f'Error : {self._error}, Tried with : {user_passwd}\n') self._error += 1 return "Error." ``` ## 2 ```python= import os def get_username(uid, passwd): for line in passwd: data = line.split(':') if int(data[2]) == uid: return data[0] return None def get_password_hash(username, shadow): for line in shadow: data = line.split(':') if data[0] == username: return data[1] return None if __name__ == "__main__": with open("/etc/passwd", 'r') as f: passwd = [line.strip() for line in f.readlines()] with open("/etc/shadow", 'r') as f: shadow = [line.strip() for line in f.readlines()] uid = os.getuid() username = get_username(uid, passwd) print(get_password_hash(username, shadow)) ``` The python code opens and reads from both `/etc/passwd` and `/etc/shadow`, then gets the uid of the current process. It then correlates the uid with the username in the `/etc/passwd` file, and looks for that username in `/etc/shadow` to obtain the hash of the user. ## 3 Linux mechanism that keeps docker isolated: - AppArmor security profiles for Docker - AppArmor is a Linux security module that provides a way to restrict the actions that a program can perform on the system. AppArmor profiles define the permissions that a program has, such as which files it can access and which system calls it can execute. By restricting the actions of a program, AppArmor helps to reduce the attack surface of the system and increase security. Docker can use AppArmor to restrict the actions that a container can perform on the host system. By creating an AppArmor profile for a container, the administrator can control which files the container can access and which system calls it can execute. This helps to reduce the attack surface of the container and increase its security. In summary, AppArmor is a Linux security module that provides a way to restrict the actions that a program can perform on the system, and Docker can use AppArmor to restrict the actions that a container can perform on the host system, increasing security. - Linux NameSpace: - A Docker container gets its own namespace from the host kernel, that means the program in the container can't try to read kernel memory or eat more RAM than allowed. Linux Namespaces are a Linux kernel feature that provide isolated environments for system resources such as processes, network, user IDs, and file systems. It allows for the creation of isolated containers, each with its own view of the system resources. Docker uses Linux namespaces to create isolated containers for each Docker container. Docker is a platform for developers and system administrators to easily create, deploy, and run applications in containers. Docker containers are isolated from each other and from the host system, and they provide a consistent environment for application deployment and execution. Docker leverages Linux namespaces to provide the isolation and control over system resources required to run multiple containers on the same host. In summary, Linux namespaces provide the basic building blocks for containerization, and Docker uses these namespaces to create isolated containers for application deployment and execution. - Linux control groups: - Linux control groups (cgroups) is a Linux kernel feature that provides a way to manage and allocate system resources, such as CPU time, memory, and I/O bandwidth, among groups of processes. cgroups allow you to limit, prioritize, and distribute system resources to processes, helping to ensure that each process has the resources it needs to run effectively. Docker uses cgroups to manage the resources of containers. When a Docker container is created, it is assigned to a cgroup, which sets limits and constraints on the resources the container can access. This helps ensure that each container receives the resources it needs to run, and prevents one container from monopolizing the resources of the host system or interfering with other containers. In summary, Linux cgroups provide a way to manage and allocate system resources among groups of processes, and Docker uses cgroups to manage the resources of containers. This allows Docker to ensure that each container has the resources it needs to run effectively, while also preventing one container from interfering with other containers or the host system. - Linux capabilities: - Linux capabilities is a Linux kernel feature that provides a way to control the permissions of processes, by dividing the traditional root permissions into smaller, more fine-grained capabilities. For example, a process can be granted the capability to bind to a privileged network port, but not the capability to execute a privileged system call. Docker uses Linux capabilities to control the permissions of containers. When a Docker container is created, its capabilities can be limited, allowing the container to perform only the actions it needs to carry out its intended purpose. This helps to reduce the attack surface of containers, making them more secure, by limiting the actions a malicious container could perform. In summary, Linux capabilities provide a way to control the permissions of processes, by dividing the traditional root permissions into smaller, more fine-grained capabilities. Docker uses Linux capabilities to control the permissions of containers, reducing the attack surface of containers and making them more secure. ## 4 ### 4.1 ![https://www.pluralsight.com/blog/it-ops/linux-file-permissions](https://i.imgur.com/GI5lda8.png) Taken from `https://www.pluralsight.com/blog/it-ops/linux-file-permissions` ```csvpreview ,manual.txt, report.txt, microedit, src/code.c, src/code.h alex,R/W,W,R/W,R,- benn,R,R,R/W,R/W,- cloe,-,R/W,R,R,R/W ``` ------------------ Alex and manual.txt - can be seen from -rw (owner for manual.txt) Alex and report.txt - can be seen from -w- (other user from report.txt) Alex and microedit - can be seen from r-x (other user from microedit) Alex and src/code.c - can be seen from src/code.c (other user from src/code.c) Alex and src/code.h - can be seen from src/code.h (other users can read the file) --------------- Benn and manual.txt - can be seen from r-- (other user) Benn and report.txt - can be seen from -r-- (owner) Benn and microedit - can be seen from rws (owner) Benn and src/code.c - can be seen from -rw- (owner) Benn and src/code.h - can be seen from --- (group) --------------- Cloe and manual.txt - can be seen from --- (group) Cloe and report.txt - can be seen from rw- (group) Cloe and microedit - can be seen from r-- (group) Cloe and src/code.c - can be seen from r-- (group and other user) Cloe and src/code.h - can be seen from rw (group and owner) #### 4.2 ![](https://i.imgur.com/p1auZ7d.png) ![](https://i.imgur.com/2ouMLyI.png) ![](https://i.imgur.com/60FYqpZ.png) ``` #/bin/bash echo Creating the folder and files mkdir hw touch hw/manual.txt touch hw/report.txt touch hw/microedit mkdir hw/src touch hw/src/code.c touch hw/src/code.h echo Creating users and groups sudo adduser alex sudo adduser benn sudo adduser cloe sudo groupadd -f gurus sudo groupadd -f staff sudo usermod -a -G staff alex sudo usermod -a -G staff benn sudo usermod -a -G staff cloe sudo usermod -a -G gurus cloe echo Change Ownership sudo chown alex:staff hw sudo chown benn:staff hw/src sudo chown alex:gurus hw/manual.txt sudo chown benn:staff hw/report.txt sudo chown benn:gurus hw/microedit sudo chown benn:staff hw/src/code.c sudo chown cloe:gurus hw/src/code.h echo Change Permissions sudo chmod 755 hw sudo chmod 455 hw/src sudo chmod 604 hw/manual.txt sudo chmod 462 hw/report.txt sudo chmod 644 hw/src/code.c sudo chmod 460 hw/src/code.h sudo chmod 745 hw/microedit sudo chmod u+s hw/microedit ``` ## 5 ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ int arg1, arg2; printf("Running\n"); if (argc != 3) return -1; arg1 = atoi(argv[1]); arg2 = atoi(argv[2]); printf("Argument 1: %d \n",arg1); printf("Argument 2: %d \n", arg2); if (arg1 < 0 || arg2 < 0) return -1; if (arg1 + arg2 >= 0) return -1; printf("ACCESS GRANTED\n"); } ``` ``` Running Argument 1: 2147483647 Argument 2: 1 ACCESS GRANTED ``` The problem for this code is that the only scenario where access granted is achieved is when there's an int overflow, which can be done using the arguments above. To prevent int overflow, - Actually consider how large/small a number it will ever contain. - Actually consider if it needs to be signed or unsigned. Unsigned is usually less problematic. - Pick the smallest type of intn_t or uintn_t types from stdint.h that will satisfy the above (or the ...fast_t etc flavours if you wish). - If needed, come up with integer constants that contain the maximum and/or minimum value the variable will hold and check against those whenever you do arithmetic. ## 6 ``` void fun3(void){ char a[8]; double b; return; } void fun2(void){ fun3(); } void fun1(void){ char a[16]; int b; float c; fun2(); } int main(void){ fun1(); } ``` ![](https://i.imgur.com/60rLK3i.png) ## 7 ![](https://i.imgur.com/boTSyXu.png) - Executing gdb with vuln1 after compiling it ![](https://i.imgur.com/2kMZwMC.png) - Getting buffer start locations in memory ![](https://i.imgur.com/4As5wm3.png) - Set break point ![](https://i.imgur.com/LD81DQ9.png) - To override EIP with ‘FFFF’, we print an array of ‘F’ with length of 144 bytes. This will write in to the EIP : `run $(python -c "print('F'*144)")` ![](https://i.imgur.com/Woe2Kb7.png) - To find the offset of EIP: `run $(python -c "print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCDEFGHIJKLMNOPQRSTUVWXYZ')")` - This is done to check and replace where the eip is. - ![](https://i.imgur.com/Ygv8qqC.png) - To override EBP with ‘FFFF’ and EIP with ‘PPPP’, the code is modified to :`run $(python -c "print ('F'*140+'P'*4)")` ![](https://i.imgur.com/yG6yrvN.png) ![](https://i.imgur.com/4rZjcFD.png) ![](https://i.imgur.com/DfsaK6g.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully