Thursday, 6 October 2022

Patience Sort

 


 

Introduction

Patience sort is one of the common sorting algorithms. This algorithm is inspired and named by the card game called Solitaire. An another variant of this algorithm is used to find the longest increasing subsequence in a given array, which is said to used in SQL Server, process control.

Little bit history from the below reference paper from David Aldous and Persi Diaconis, Patience sort was named by C.L. Mallows in early 1960's but was never published.

Time Complexity: O(N2) 

Time Complexity using priority queue: O(N * log(N)) [Example is given below]

Auxiliary Space: O(N) [Auxiliary space means extra or temporary space used by the algorithm to process the logic]


Algorithm

  • Rules
    • Number can be added to the pile only if it is lesser than current number/card.
    • If the existing piles does't meet the first rule, a new pile is created.
    • Ideally the goal is to have list of lists holding sorted values, possibly lesser number of piles.
  • Logic
    • Involves two steps process, creation and merging of piles.
  • Piles
    • Initialize an empty 2D list with no piles.
    • Loop through each number/card.
    • First card forms a new pile consisting single number/card.
    • Each subsequent card is placed in the leftmost (top) of the existing pile if the value is greater or equal to new number/card value.
    • If the above rule fails, when it is unable to find greater element in any of the top values in the available piles, a new pile is created by adding the number/card on the top of the stack.
  • Merge
    • Given sorted arrays perform merge in k-way merge operation using priority queue (min-heap). As we would want to find the smallest element and followed by the next smallest. Let's say to find any element from the list this algorithm would not be suitable.
    • Priority queue, is kind of queue data structure which additionally holds priority value for every element. There are different ways the priority could be defined. Such as :
      • The largest element holds higher priority
      • The smallest element holds higher priority
    • In python we have predefined module available perform this operation, "heapq".

Visualization

Credits: https://assets.leetcode.com/users/images/4eb9f4c5-5612-4761-8da1-9f5e58e5d9ae_1616834711.464945.png

Source Code

import bisect
import heapq


def patience_sort(seq):
# array of piles initially null
piles = []
print("Started with the given input of array values ", seq, "\n")

# Each subsequent card is placed on the leftmost existing pile
# whose top card has a value greater than or
# equal to the new card's value,
# or to the right of all of the existing piles,
# thus forming a new pile.
print("Lets create a list of piles using bisect algorithm:")
for x in seq:
new_pile = [x]

# Bisect algorithm is to find a position in list where an element
# needs to be inserted to keep the list in sorted order.
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
i = bisect.bisect_left(piles, new_pile)
if i != len(piles):
piles[i].insert(0, x)
else:
piles.append(new_pile)
print("At each level status of piles {}".format(piles))
print("List of increasing subsequences are ", piles, "\n")

print("Lets perform the sorting operation for the piles:")
print("Before sort status for sequence {}, having piles {}".format(seq, piles))
# priority queue allows us to retrieve least pile efficiently
for i in range(len(seq)):
small_pile = piles[0]
seq[i] = small_pile.pop(0)

# Heap data structure is mainly used to represent a priority queue.
# Here the smallest heap element is given higher priority.
# Implements as complete binary tree.
# For each elements are pushed or popped, heap structure is maintained.
if small_pile:
# Here the function inserts and pops elements in one statement.
# In this, the element is first popped, then the element is pushed.
# heapreplace() is equivalent to heappop() followed by heappush().
# The order will be adjusted, so the heap structure is maintained.
heapq.heapreplace(piles, small_pile)
else:
# This function is used to remove and return the smallest element from the heap.
# The order is adjusted, so that heap structure is maintained.
heapq.heappop(piles)

print("At level {} status for sequence {}, having piles {}".format(i, seq, piles))

print("\nFinally! After patience sort input array is sorted ", seq)
assert not piles


input_values = [3, 7, 5, 6, 4, 2, 10, 9, 8]
patience_sort(input_values)

Output


Started with the given input of array values  [3, 7, 5, 6, 4, 2, 10, 9, 8] 

Lets create a list of piles using bisect algorithm:
At each level status of piles [[3]]
At each level status of piles [[3], [7]]
At each level status of piles [[3], [5, 7]]
At each level status of piles [[3], [5, 7], [6]]
At each level status of piles [[3], [4, 5, 7], [6]]
At each level status of piles [[2, 3], [4, 5, 7], [6]]
At each level status of piles [[2, 3], [4, 5, 7], [6], [10]]
At each level status of piles [[2, 3], [4, 5, 7], [6], [9, 10]]
At each level status of piles [[2, 3], [4, 5, 7], [6], [8, 9, 10]]
List of increasing subsequences are  [[2, 3], [4, 5, 7], [6], [8, 9, 10]] 

Lets perform the sorting operation for the piles:
Before sort status for sequence [3, 7, 5, 6, 4, 2, 10, 9, 8], having piles [[2, 3], [4, 5, 7], [6], [8, 9, 10]]
At level 0 status for sequence [2, 7, 5, 6, 4, 2, 10, 9, 8], having piles [[3], [4, 5, 7], [6], [8, 9, 10]]
At level 1 status for sequence [2, 3, 5, 6, 4, 2, 10, 9, 8], having piles [[4, 5, 7], [8, 9, 10], [6]]
At level 2 status for sequence [2, 3, 4, 6, 4, 2, 10, 9, 8], having piles [[5, 7], [8, 9, 10], [6]]
At level 3 status for sequence [2, 3, 4, 5, 4, 2, 10, 9, 8], having piles [[6], [8, 9, 10], [7]]
At level 4 status for sequence [2, 3, 4, 5, 6, 2, 10, 9, 8], having piles [[7], [8, 9, 10]]
At level 5 status for sequence [2, 3, 4, 5, 6, 7, 10, 9, 8], having piles [[8, 9, 10]]
At level 6 status for sequence [2, 3, 4, 5, 6, 7, 8, 9, 8], having piles [[9, 10]]
At level 7 status for sequence [2, 3, 4, 5, 6, 7, 8, 9, 8], having piles [[10]]
At level 8 status for sequence [2, 3, 4, 5, 6, 7, 8, 9, 10], having piles []

Finally! After patience sort input array is sorted  [2, 3, 4, 5, 6, 7, 8, 9, 10]

Conclusion

Today we have seen a simple version of patience sort using priority queue, there are other ways to implement the same sort. Happy Sorting!

Credit and References

https://en.wikipedia.org/wiki/Patience_sorting
https://www.stat.berkeley.edu/~aldous/Research/OP/patience.pdf


Thursday, 22 September 2022

Common 50 Security Unix Commands and Tools

 


Introduction

In our current security system building environment we have different tools and commands are readily available for an engineer, specially for the security engineer to use.
Let's have look in most popular commands used in day to day to help us protect or monitor from potential attacks.

Commands

  • ipconfig / ifconfig
    • Description
      • Shows the configuration of the assigned network interface to the server.
      • Includes, MAC address, IPv4 address, IPv6 address, default gateway, transferred and received packets size and dropouts, MTU - Maximum Transmission Unit states the maximum size of the packet the network interface can transfer, and so on.
      • ipconfig command is used in Windows and ifconfig is for Linux/Unix and iOS.
    • Example
Credit: https://upload.wikimedia.org/wikipedia/commons/c/c9/Ifconfig_example_screenshot.png

  • ping
    • Command
      • The basic command to validate the reachability of the server of the given server name or ip address
      • Provides the information on the response time, to determine RTT - Round Trip Time.
      • Usually uses ICMP protocol request and reply.
    • Example
Credits: https://upload.wikimedia.org/wikipedia/commons/e/e2/Ping_iputils_screenshot.png

  • arp
    • Command
      • Shows the local machine's ARP - Address Resolution Protocol cache.
      • ARP cache shows the list of MAC address of the interface associated with each IP address the local host has communicated with recently.
      • Usage of this command to also investigate a suspecting spoof attack.
    • Example
Credit: https://networkencyclopedia.com/wp-content/uploads/2019/08/arp-command.jpg

  • traceroute / tracert
    • Command
      • Reports the list of hops needs to be made from source to destination host.
      • RTT is as well reported.
      • tracert is Windows command and traceroute is Linux based command.
      • ICMP or UDP is used in this communication. 
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/traceroute.png

  • route
    • Command
      • Edit or view the host's local routing table.
      • By default all the traffic from the host is routed via gateway router.
      • Additional entries found in this table could be suspicious.
    • Example
Credit: https://www.cisco.com/c/dam/en/us/support/docs/voice-unified-communications/unified-intelligent-contact-management-enterprise/20524-route-command.gif


  • getmac
    • Command
      • Returns the MAC address and the list of network protocols associated with each address for all the network cards in the host.
    • Example
Credit: https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2016/12/windows-command-getmac.png

  • pathping / mtr
    • Command
      • Provides information about network latency and network loss at intermediate hops between a source and destination.

      • Combination of traceroute and ping command.
      • Windows uses pathping, Linux uses mtr commands.
    • Example
Credit: https://www.omnisecu.com/images/tcpip/pathping-final-output.jpg

  • nmap
    • Command
      • nmap uses diverse methods for scanning the ports scan and services running network IP address.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20200519222836/to-scan-multiple-host.png

  • netstat
    • Command
      • Shows the process state of the ports in the host.
      • Able to identify only authorized services running and connections made from different hosts.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/all_port-1.png

  • nslookup
    • Command
      • Returns the query name records for the given domain name or IP address using DNS resolver.
    • Example
Credit: https://www.cloudns.net/blog/wp-content/uploads/2018/10/1.png

  • netcat
    • Command
      • Enables reading and writing data between hosts.
      • One of the most powerful command, considered as Swiss army knife of networking tools.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20200505144617/Port-Scanning-Using-Netcat-Command-in-Linux.png

  • dnsenum
    • Command
      • Returns the as much information and all the IP address that are in use for a domain.
    • Example
Credit: https://kalilinuxtutorials.com/wp-content/uploads/2015/04/dnsenum_1.png

  • scanless
    • Command
      • Scan for all the services and ports which are running and open in a host.
    • Example
Credit: https://securityonline.info/wp-content/uploads/2017/05/Capture-9.jpg

  • curl
    • Command
      • Perform data transfer over many protocols, commonly used for HTTP.
      • Other supported protocols are FTP, IMAP, LDAP, POP3, SMB, and SMTP.
    • Example
Credit: https://linuxhint.com/wp-content/uploads/2021/07/4-16.png

  • tcpdump
    • Command
      • Packet and protocol analysis is very an important part of security.
      • Using tcpdump, capture the packets from an interface and generate the .pcap file.
      • Can filter packets, to save only selected number of frames.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20200521231605/capture-specific-number-of-packages.png

  • wireshark
    • Command
      • Packet capture and analysis is done using graphical interface.
      • Captured packets can be easily analysed using wireshark.
    • Example
Credit: https://www.wireshark.org/docs/wsug_html_chunked/wsug_graphics/ws-display-filter-tcp.png

  • hping
    • Command
      • hping is an open source packet generator and analyzer for TCP/IP protocol.
      • hping can be used to send large volumes of TCP traffic at a target while spoofing the source IP address to be appeared from random or specified user source.
      • Subset of uses of hping:
        • firewall testing
        • advanced port scanning
        • remote uptime guessing
        • tcp/ip stack auditing
    • Example
Credit: https://www.cyberpratibha.com/blog/wp-content/uploads/2014/06/hping-1.jpg

  • tcpreplay
    • Command
      • Replays the previously captured traffic, which is saved in .pcap file in the network interface.
    • Example
Credit: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1v-rqZ_2oOtTklCScvgxZ4cayhhgruB6MMEj8ssC2Z_MBIkJmP8POyv7Pzg4j7bKXVURfkkrPChyphenhyphenj2yLg3hMjc8PcfyoeXkPQe2SHtqNDl9jrSpuzvdeb9QN-edglI9gt16PxX2STHCrg/s1600/tcpreplay1.png

  • lsattr
    • Command
      • Displays the information about the attributes of the specific device or type of the device.
    • Example
Credit: https://www.golinuxcloud.com/wp-content/uploads/lsattr-recursive.png

  • dig
    • Command
      • Is abbreviated as domain information groper.
      • As like nslookup used for querying the information about the domain from the DNS, but nslookup can be used for one server whereas in dig it can return the results of multiple server at same time.
    • Example
Credit: https://i0.wp.com/allabouttesting.org/wp-content/uploads/2018/08/dig1.jpg?ssl=1

  • lsof
    • Command
      • Returns the list of open files and process that have open them.
      • Command is used in unix like operating systems.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20190220132931/lsof1.png

  • dd
    • Command
      • Allows to copy data from raw data from one source disk to another.
      • Called as disk/data duplicator.
    • Example
Credit: https://linuxhint.com/wp-content/uploads/2021/04/image3-37.png

  • openssl
    • Command
      • OpenSSL is an open-source command line tool that is commonly used to generate private keys, create CSRs, install your SSL/TLS certificate, and identify certificate information.

    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20200317185845/Creating-New-Private-Key-and-CSR-using-Openssl-command-in-Linux.png

  • memdump
    • Command
      • Displays a hexadecimal memory dump defined by a starting address and specified number of bytes.

    • Example
Credit: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWahCRqMdBkX7Pe9Od3nTm5ZPfLTvF4lmkOsAVbxjIiM8rP3Sd7geajCklov8dvhEP6NuqAmJGYdwsqqCUCwM15n18U5oJabxfw5UcWUdR5h11ncX4OVUjp0N_hhyW0VTjh6QLlpN056jx/s1600/eg3.png

  • free
    • Command
      • Displays the total amount of free space available along with the amount of memory used and swap memory in the system, and also the buffers used by the kernel.

    • Example
Credit: https://static.javatpoint.com/linux/images/free2.png

  • ssh
    • Command
      • Provides a secure encrypted connection between two hosts over an insecure network. 

    • Example
Credit: https://www.linuxshelltips.com/wp-content/uploads/2021/09/Connect-to-Linux-Using-SSH.png

  • nbtstat
    • Command
      • Displays NetBIOS over TCP/IP (NetBT) protocol statistics, NetBIOS name tables for both the local computer and remote computers, and the NetBIOS name cache.
      • Helps troubleshoot NetBIOS name resolution issues.
    • Example
Credit: https://pentestlab.files.wordpress.com/2012/08/1.jpg

  • hostname
    • Command
      • Displays the name of the current host system and only root user authority can set the host name.

    • Example
Credit: https://www.cyberciti.biz/media/new/faq/2011/01/Linux-Find-hostname-command.jpg

  • top
    • Command
      • Shows the realtime view of the processes running on the system.
    • Example
Credit: https://linuxhint.com/wp-content/uploads/2020/10/word-image-376.png

  • systeminfo / uname
    • Command
      • Displays the information about the host.
    • Example
Credit: https://i.ytimg.com/vi/j2VZ7BXtAHc/maxresdefault.jpg


Tools

  • Nessus
    • Command
      • Nessus is a remote security scanning tool, which scans and raises alerts if any vulnerabilities or exposures found that malicious attackers could gain control. 
      • Such as sensitive information unauthorized control, misconfiguration, Denial of service vulnerabilities, vulnerable passwords and so on. 
    • Example
Credit: https://www.tenable.com/themes/custom/tenable/img/nessus/nessus-live-results_large.png

  • Metasploit
    • Command
      • Metasploit is an open source exploit framework, though also has the enterprise edition for performing ethical hacking.
      • Provides information about security vulnerabilities and allow customization to perform penetration testing on networks and systems.
    • Example
Credit: https://samsclass.info/123/proj10/LNK1.png

  • Sn1per
    • Command
      • Is a framework developed for performing penetration testing and evidence gathering.
      • Saves time by automation the execution of open source or commercial tools and view the results in web reports. 
    • Example
Credit: https://sn1persecurity.com/wordpress/wp-content/uploads/2021/12/Sn1per-Professional-Attack-Surface-Management1.png

  • TheHarvester
    • Command
      • Command line tool acts as a search engine, for the given domain finds the list of email accounts, subdomain names, virtual hosts, open ports, employee details.
      • Gathers these information from public sources.
    • Example
Credit: https://media.geeksforgeeks.org/wp-content/uploads/20200515201739/WhatsApp-Image-2020-05-15-at-8.16.23-PM.jpeg

  • fireELF
    • Command
      • Fileless attacks occurs in the memory without writing into disks, as it is volatile it's hard to detect and to find in future.
      • fireELF is an open source fileless malware framework which injects file less exploit payloads into a cross platform host.
      • In Linux using memfd_create the elf executables in memory.
    • Example
Credit: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifWNJMoFilBU6l1BrzE1U7OcNqH6tL-u4Z-r3JIjvdZz01BdGyJ8Afm3SrERnCN8nqUZK5nYeyPwAi9nIUViHYs73SC8HYkOarh7cYskXxOSTTdnrCdvlGiM_6oR64wlOwgpSuzCLnWO0A/s1600/fireELF_2_ss1.png

  • RouterSpoilt
    • Command
      • An open source exploit framework and provides vulnerability scanner, dedicated for embedded systems.
      • Allows to perform penetration testing operations such as:
        • exploits: modules taking advantages of vulnerabilities
        • creds: modules to test credentials
        • scanners: modules to check if vulnerability is found to any exploit
        • payloads: modules for generating payloads for various architecture and injection points
        • generic: modules to perform general attacks
    • Example
Credit: https://img.wonderhowto.com/img/71/72/63664322438160/0/seize-control-router-with-routersploit.w1456.jpg

  • BeEF
    • Command
      • BeEF is abbreviated to Browser exploitation framework for recovering web session and exploiting client side scripting, including mobile clients.
      • This penetration testing tool focuses is only on web browsers.
    • Example
Credit: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOWsgIirSHt-1TWJ4SF91XYWocOnnQFQVo0dlwLd1mJjp6wQiabyuAglKQjKz4Yz8nKD64fMnSChHraKv0MQ6Q_0ofG-wIfnJPnva1P6SNFUaSXS4Mykch_W5uZN5doTPQ5iGfXnfkppM/s1600/beef6.tiff

  • OWASP ZAP
    • Command
      • Most popular open source web application and mobile security scanner tool.
      • Used by both the developers and penetration testers. 
    • Example
Credit: https://www.researchgate.net/profile/Ali-Fathi-Sawehli/publication/338101873/figure/fig14/AS:838586463166464@1576946001385/Main-Interface-of-OWASP-ZAP-Owasporg-2019.ppm

  • Pacu
    • Command
      • An open source comprehensive scanning and exploit tools developed exclusive for Amazon - AWS penetration testing.
    • Example
Credit: https://securityonline.info/wp-content/uploads/2018/08/pacu.png

  • Cuckoo
    • Command
      • Cuckoo is an open source tool malware analysis tool, used to launch malware in a secure and isolated environment.
      • Providing a file to the command Cuckoo, returns the result of the complete impact when the file executed in an isolated environment.
    • Example
Credit: https://info.varonis.com/hs-fs/hubfs/Imported_Blog_Media/cuckoo_dash-1.png?width=3595&height=1955&name=cuckoo_dash-1.png

  • WinHex
    • Command
      • WinHex is a universal hexadecimal editor, particularly helpful in the realm of computer forensics, data recovery, low-level data processing, and IT security. 
      • An advanced tool for everyday and emergency use: inspect and edit all kinds of files, recover deleted files or lost data from hard drives with corrupt file systems or from digital camera cards. 
    • Example
Credit: https://ars.els-cdn.com/content/image/1-s2.0-S1742287604000295-gr12.jpg

  • FTK imager
    • Command
      • FTK Imager is a data preview and imaging tool that lets you quickly assess electronic evidence to determine if further analysis.

    • Example
Credit: https://eforensicsmag.com/wp-content/uploads/2014/04/m1.png

  • Autospy
    • Command
      • Autopsy is a digital forensics platform and graphical interface for digital forensics tools. 
      • It is used by law enforcement, military, and corporate examiners to investigate what happened on a computer, also can recover photos from camera's memory card.
    • Example
Credit: http://sleuthkit.org/autopsy/docs/user-docs/4.16.0/command_line_ingest_profile.png

  • Sniffer
    • Command
      • A sniffer is a software or hardware tool that allows the user to “sniff” or monitor your internet traffic in real time, capturing all the data flowing to and from your computer. 
      • By recording packets, you can trace connection states to the exact point at which they fail, which may help you to diagnose some types of problems that are otherwise difficult to detect.
    • Example
Credit: https://miro.medium.com/max/1400/0*fyyka1dBKDUmyaQk

  • Brutus
    • Command
      • Brutus is one of the most powerful, fastest and most flexible remote passwords cracking tool. 
      • Brutus password cracker bangs against network services of remote systems trying to guess passwords by using a dictionary and permutations thereof.
      • It supports protocols such as HTTP, POP3, FTP, SMB, TELNET, IMAP, NNTP
    • Example
Credit: https://www.techrepublic.com/a/hub/i/2015/06/03/4a29b3aa-0988-11e5-940f-14feb5cc3d2a/brutus-5218766a.gif?x95853

  • Cain and Abel
    • Command
      • Cain and Abel is a password recovery tool for Microsoft Windows, used to recover many kinds of passwords using methods such as network packet sniffing, cracking various password hashes by using methods such as dictionary attacks, brute force and cryptanalysis attacks. 
      • Cryptanalysis attacks were done via rainbow tables which could be generated with the winrtgen.exe program provided with Cain and Abel.
    • Example
Credit: https://cdn.cyberpunk.rs/wp-content/uploads/2020/04/cain-and-abel-interface.jpg

  • John the Ripper
    • Command
      • John the Ripper is a password cracking tool for UNIX-based systems. 
      • Designed to test password strength, brute-force encrypted (hashed) passwords, and crack passwords using the dictionary attacks methods.
      • It takes text string samples from a word list using common dictionary words or common passwords, and also work with encrypted passwords. 
    • Example
Credit: https://www.unixmen.com/wp-content/uploads/2015/08/213.png


  • THC Hydra
    • Command
      • THC Hydra is a parallelized network login cracker. 
      • Hydra works by using different approaches to perform brute-force attacks in order to guess the right username and password combination.
    • Example
Credit: https://www.cyberpratibha.com/wp-content/uploads/2015/12/hydra-h.png

  • Powershell / Bash
    • Command
      • Powershell is for windows and Bash is for linux kind of operating systems, for task automation consisting the execution of command line tools.
    • Example
Credit: https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Windows_PowerShell_1.0_PD.png/640px-Windows_PowerShell_1.0_PD.png

  • Python
    • Command
      • Python is a useful programming language for cybersecurity professionals because it can perform a variety of cybersecurity functions, like malware analysis, penetration testing, and scanning.

    • Example
Credit: https://cdn.educba.com/academy/wp-content/uploads/2016/01/Basic-Calculations-in-Python.png



Credits and References

https://t3.ftcdn.net/jpg/02/42/44/52/360_F_242445276_i1rZNvghK4Go26ELyRiHuGeT7innmykK.jpg

Scarcity Brings Efficiency: Python RAM Optimization

  In today’s world, with the abundance of RAM available, we rarely think about optimizing our code. But sooner or later, we hit the limits a...