Strzelacz48
    • 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
    # SO Lista 4 Pseudoterminale, pliki i katalogi ![](https://i.imgur.com/lmkB1Nj.png) ## Zadanie 1 Olek ![](https://i.imgur.com/cRm0J6g.png) :::spoiler Łiskacz ```c= void tty_curpos(int fd, int *x, int *y) { // termios, old termios struct termios ts, ots; // ts = tcgetattr() tcgetattr(fd, &ts); // ots = ts memcpy(&ots, &ts, sizeof(struct termios)); // Wyłączamy ECHO, ICANON i CREAD. // ECHO - pokazuj użytkownikowi wprowadzane znaki. // ICANON - obsługa znaków specjalnych. // CREAD - odbieraj nowe dane (zdaniem dokumentacji FreeBSD bezużyteczne). ts.c_lflag &= ~(ECHO | ICANON | CREAD); // TCSADRAIN - zmiany nie dotyczą danych w buforze. // TCSAFLUSH - zmiany nie dotyczą bufora, niezatwierdzone wejście // jest usuwane. tcsetattr(fd, TCSADRAIN, &ts); /* How many characters in the input queue. */ int m = 0; // FIONREAD == TIOCINQ - Get the number of bytes in the input buffer. ioctl(fd, TIOCINQ, &m); /* Read them all. */ // Wczytujemy zawartość bufora wejścia w jądrze (czyszcząc go). char discarded[m]; m = Read(fd, discarded, m); // CPR Cursor Position Report (również Device Status Report). // Sterownik terminala wypisze aplikacji `ESC[n;mR`, gdzie // n - rząd, m - kolumna. Zapisujemy to w buf. Write(fd, CPR(), sizeof(CPR())); char buf[20]; int n = Read(fd, buf, 19); buf[n] = '\0'; // Włączamy ICANON i wypełniamy z powrotem bufor wejścia. ts.c_lflag |= ICANON; tcsetattr(fd, TCSADRAIN, &ts); for (int i = 0; i < m; i++) // TIOCSTI - Insert the given byte in the input queue. (Faking input) ioctl(fd, TIOCSTI, discarded + i); // Przywracamy stary stan termios (ECHO, CREAD). tcsetattr(fd, TCSADRAIN, &ots); // Czytamy CPR. sscanf(buf, "\033[%d;%dR", x, y); } ``` ::: > funkcja `tty_curpos` z terminal.c ```c= void tty_curpos(int fd, int *x, int *y) { struct termios ts, ots; tcgetattr(fd, &ts); // ustawia obecny stan atrybutów terminala w strukturze ts memcpy(&ots, &ts, sizeof(struct termios)); ts.c_lflag &= ~(ECHO | ICANON); ts.c_cflag &= ~CREAD; tcsetattr(fd, TCSADRAIN, &ts); // ustawia zmienioną strukturę ts jako atrybuty terminala // TCSADRAIN - // the change occurs after all output written to fd // has been transmitted. This function should be // used when changing parameters that affect output. /* How many characters in the input queue. */ int m = 0; #ifdef LINUX ioctl(fd, TIOCINQ, &m); #endif /* Read them all. */ char discarded[m]; m = Read(fd, discarded, m); Write(fd, CPR(), sizeof(CPR())); char buf[20]; int n = Read(fd, buf, 19); buf[n] = '\0'; ts.c_lflag |= ICANON; tcsetattr(fd, TCSADRAIN, &ts); for (int i = 0; i < m; i++) ioctl(fd, TIOCSTI, discarded + i); tcsetattr(fd, TCSADRAIN, &ots); sscanf(buf, "\033[%d;%dR", x, y); } ``` ![](https://i.imgur.com/aefr967.png) ![](https://i.imgur.com/kM81fuU.png) --- ![](https://i.imgur.com/qNUikAH.png) ![](https://i.imgur.com/2bW9TKS.png) ``` CPR - cursor position report Local modes: ECHO /* enable echoing */ ICANON /* canonicalize input lines */ Control modes: CREAD /* enable receiver */ ``` > `termios` struct ```c= struct termios { tcflag_t c_iflag; /* Input flags */ tcflag_t c_oflag; /* Output flags */ tcflag_t c_cflag; /* Control flags */ tcflag_t c_lflag; /* Local modes */ cc_t c_line; /* Line discipline (nonstandard)*/ cc_t c_cc[NCCS]; /* Terminal special characters */ speed_t c_ispeed; /* Input speed (nonstandard; unused) */ speed_t c_ospeed; /* Output speed (nonstandard; unused) */ }; ``` ## Zadanie 2 kasia ![](https://i.imgur.com/65kxGZo.png) :::info A pseudoterminal is a pair of virtual character devices that provide a bidirectional communication channel. One end of the channel is called the master; the other end is called the slave. The slave end of the pseudoterminal provides an interface that behaves exactly like a classical terminal. A process that expects to be connected to a terminal, can open the slave end of a pseudoterminal and then be driven by a program that has opened the master end. Anything that is written on the master end is provided to the process on the slave end as though it was input typed on a terminal. ::: ![](https://imgur.com/YrX6bUD.png) Następnie wykonujemy ``strace -f -e read,write -o script.log script -T timing -c dash`` i znowu wpisujemy jakies polecenia, zaglądamy do pliku ``script.log``. > IGNCR - ignore CR > ICRNL - map CR to NL (ala CRMOD) > CR - \r - \(Carriage Return\) moves the cursor to the beginning of the line without advancing to the next line. jak ustawimy jedną z tych flag to nie mozemy wyslac zadnego polecenia w dashu - przycisk ENTER pojawia się jako \M zamiast działać ## Zadanie 3 Kuba ![](https://i.imgur.com/vz0SfWs.png) ![](https://i.imgur.com/JaxMTuW.png) ![](https://i.imgur.com/HQSmCiT.png) Ostatni proces w potoku jest dzieckiem powłoki i wszystkie inne procesy są dziećmi ostatniego procesu, dzieje się tak z tego powodu, że ostatni proces jest dzieckiem powłoki, a powłoka ma dostęp do informacji, że działanie całego potoku zakończyło się. Kolejność wywołań : 1. Powłoka sh (949) wywołuje fork, powstaje dziecko sh (1988). 2. Wywoływany jest dwa razy pipe w sh (1988). 3. sh (1988) wywołuje dwukrotnie fork, powstają kolejne dzieci sh (1989) i sh (1990). W każdym dziecku przy użyciu dup2 zmieniane jest wejście pipe’a na stdout, a wyjście jest zamykane przez close. W rodzicu (sh (1988)) wyjście pipe’a ustawiane jest na stdin przy użyciu dup2, a wejście jest zamykane przez close. 4. Na tak przygotowanych procesach (1989 i 1990) uruchamiane są kolejno przez execve programy ps -ef oraz grep sh. 5. W sh (1988) wywoływane jest polecenie creat do stworzenia pliku wyjściowego cnt, cnt jest ustawiane na stdout a następnie wykonywane jest polecenie execve z argumentem wc -l (1988). 6. Na końcu, po wykonaniu powyższych poleceń zostanie wykonany waitpid. Obsługa niepowodzenia w execve należy do programisty, jedną z możliwości jest zakończenie działania programu. Ominięcie jednego niepowodzenia przyniosłoby nieoczekiwane rezultaty, zakładając że nie zadziała np. ps -ef, na wejściu grep sh nie będzie nic, przez co cały pipeline się zawiesi. Warto wiedzieć o tym, że przez setpgrp(2) ustawiana jest cała grupa procesów, dzięki czemu przy niepowodzeniu można łatwo wysłać sygnał do wszystkich procesów i je zakończyć. ## Zadanie 4 ![](https://i.imgur.com/NUVUfrz.png) ## Zadanie 5 Marcin ![](https://i.imgur.com/1sjQMIs.png) Aby odczytać katalog, należy użyć funkcji ``opendir(3)`` oraz ``readdir(3)`` (korzysta z syscalla reddirenties? do sprawdzenia). ``read(2)`` i ``write(2)`` służą do operacji na plikach. :::::spoiler ``man opendir`` ![](https://i.imgur.com/gSgDYWy.png) ::::: :::::spoiler ``man readdir`` * moja (xD nie to czego szukasz) ![](https://i.imgur.com/VyEOOS1.png) * [z neta](https://www.man7.org/linux/man-pages/man3/readdir.3.html) ![](https://i.imgur.com/cmXttkw.png) ![](https://i.imgur.com/nwIPfUE.png) ::::: [**Rekord katalogu**](https://unix.stackexchange.com/questions/186992/what-is-directory-entry) (ang. directory entry) to w istocie mapowanie nazw plików do ich inody(która jest wskaźnikiem na informacje o pliku). Rekord katalogu istnieje bo użytkownik bawi sie zwykle nazwami plików a kernel nie rozumie nazw plików. Dlatego rekord zawiera nazwę pliku i strukturę informacji opisujących atrybuty pliku takie jak typ pliku (plik zwykły, katalog), rozmiar pliku, właściciel pliku, uprawnienia dla pliku, czy datę ostatniej modyfikacji. Używając `stat` można wczytać strukturę informacji zawierającą wszystkie atrybuty (inaczej **metadane**) pliku/katalogu. Wywołanie na moim komputerze `stat UnityProjects` ``` Plik: Unity_Projects/ rozmiar: 110 bloków: 0 bloki I/O: 4096 katalog Urządzenie: 0,38 inody: 109714 dowiązań: 1 Dostęp: (0755/drwxr-xr-x) Uid: ( 1000/strzelacz48) Gid: ( 1000/strzelacz48) Kontekst: unconfined_u:object_r:user_home_t:s0 Dostęp: 2022-11-03 16:25:40.148523719 +0100 Modyfikacja: 2022-11-03 16:25:03.882484085 +0100 Zmiana: 2022-11-03 16:25:03.882484085 +0100 Utworzenie: 2022-11-03 16:24:46.201465414 +0100 ``` `ls -U` można użyć aby terminal wypisał nieposortowany w żaden sposób zawartość katalogu i sprawdzić na żywo (porównać) czy jest posortowany. `stat /` ``` Plik: / rozmiar: 158 bloków: 0 bloki I/O: 4096 katalog Urządzenie: 0,34 inody: 256 dowiązań: 1 Dostęp: (0555/dr-xr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root) Kontekst: system_u:object_r:root_t:s0 Dostęp: 2022-11-03 10:10:44.845385300 +0100 Modyfikacja: 2022-11-03 00:03:51.371693597 +0100 Zmiana: 2022-11-03 00:03:51.371693597 +0100 Utworzenie: 2022-10-27 19:28:00.958955651 +0200 ``` Wynika z tego, że katalog / zawiera 1(możliwe błędy z linuxsem)? **twardych dowiązań** (ang. hard links), które tworzą nową nazwę dla danego zasobu i zapisują ją w nowej lokalizacji (nie kasując poprzedniej), a same dowiązania nie odwołują się do samego katalogu, lecz do jego zawartości. Inną definicją dowiązania twardego jest liczba wskaźników na inode’y plików, które wliczają się do licznika referencji do pliku. W moim przypadku dowiązanie jest tylko jedno. W każdym katalogu musi być co najmniej 1. Po wywołaniu `ls -al` zostaną wylistowane wszystkie katalogi i linki: ![](https://i.imgur.com/MFDZVLU.png) Nas głównie interesować będą katalogi zaznaczone ciemnym niebieskim, tzn. `.`, `..`, `boot`, `.cache`, `dev`, `etc`, `home`, `lost+found`, `media`, `mnt`, `opt`, `proc`, `root`, `run`, `snap`, `srv`, `sys`, `usr`, `var` oraz `tmp`. Na wydruku ls jest 20, a w stat jest 1?(Po zliczeniu ich wyjaśnia się liczba dowiązań, których jest 20). W każdym z tych katalogów jest stworzony *hard link* do katalogu `..`, którym w tym przypadku jest `/`. ## Zadanie 6 Kornelia ![](https://i.imgur.com/9QrglPH.png) - access(path, F_OK) - funkcaja `access` sprawdza uprawnienia dostępu do pliku o ścieżce `path`, `F_OK` oznacza, że sprawdzamy czy plik istnieje; funkcja zwróci 0 jeśli plik ma żądane uprawnienia (w przypadku F_OK jeśli istnieje) - O_CREAT - pozwala funkcji `open` na utworzenie pliku o podanej ścieżce, jeśli taki jeszcze nie istnieje - O_WRONLY - otwieranie pliku w trybie `write-only` - 0700 - użytkownik (właściciel pliku) ma uprawnienia rwx TOCTTOU (Time Of Check To Time Of Use) - błąd spowodowany wyścigiem, który może wystąpić jeśli pomiędzy sprawdzeniem stanu i wykorzystaniem wyniku tego sprawdzenienia istnieje odstęp czasu (w którym sprawdzony stan może ulec zmianie) W zadaniu wyścig jest pomiędzy wywołaniem `access` i `open`. Jeśli `access` zwróci -1 (plik nie istnieje), to chcemy go utworzyć wywołaniem `open`. Pomiędzy tymi wywołaniami inny proces może otworzyć plik, wtedy oba procesy zwrócą `true` i dostaną blokadę. Rozwiązanie - użyć jednej funkcji zamiast dwóch : ```c= bool f_lock(const char *path) { return Open(path, O_CREAT|O_EXCL|O_WRONLY, 0700) >= 0; } ``` `O_CREAT` + `O_EXCL` -> funkcja `open` utworzy plik o podanej ścieżce (jeśli taki nie istnieje) lub zakończy się z błędem `EEXIST` (jeśli plik, który próbujemy utworzyć już istnieje) Błąd TOCTTOU sprawia, że program jest podatny na atak. W momencie, gdy program znajduje się pomiędzy sprawdzeniem poprawności operacji a wykonaniem związanego z tym działania, atakujący może np. podmienić plik przez dowiązanie, w wyniku czego może uzyskać dostęp do wrażliwych danych. Ogólniej : TOCTTOU może prowadzić do eskalacji uprawnień (można będzie wykonać operacje, do których nie zostały przyznane uprawnienia). :::spoiler Przykład z wikipedii ![](https://i.imgur.com/dKAxKQs.png) Uprawnienia dostępu zostały sprawdzone dla pliku *file*, po czym zostało utworzone dowiązanie *file -> /etc/passwd*. Funkcja *write* będzie teraz pisała do pliku */etc/passwd*, który może nie posiadać uprawnień do zapisu. ::: --- ![](https://i.imgur.com/fRRLbl1.png) ## Zadanie 7 ![](https://i.imgur.com/FEFC9oJ.png) ## Zadanie 8 ![](https://i.imgur.com/ajVK1gU.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