old notes

i take one breath / mint at a time

#python #devstudy #datatypes

yes its good practice, it allows python and editors to make your life easier used for the reader, and for linters

used in classes

but for example, if I were to pass a class instance in there without the type hint, I wouldnt know what methods I can access, however with the type hints it will give me these options. (editor sepcific)

class Test:
    def __init__(self):
        self.test = False

def func(x : Test):
  print(x.test)

t = Test()
func(t)

example of type error

class MyClass:
    a: int
    b: str
    c: float

    def __init__(self, a: float, b: list[int], c: dict[str, str]) -> None:
        self.a = a
        self.b = b
        self.c = c

examples of type hints

x: int
s: str
l: list
l2: list[str]
t: tuple[]
t2: tuple[int]
t3: tuple[int, ...]
d: dict
d2: dict[str, int]
etc...

typehint with a return:

def func(x: int, y: int) -> int:
  return x + y

for tuples, you need to declare the type

so this will cause a linter alert because if you don't use ... you're declaring a fixed length

my_tuple: tuple[int] = (1, 2)

but this will work (for tuples)

my_tuple2: tuple[int, int] = (1, 2)
my_tuple3: tuple[int, ...] = (1, 2, 5, 1, 7, 1, 8, 1)

Protocol??

class Test: test: bool def init(self) –> None: self.test = False

def func(x: Test) –> None: print(x.test)

t: Test = Test() func(t)

Seperating typehints with initializations

also note that you can seperate typehints and initializations

type aliases

Coord = tuple[int, int]

def func(x: int, y: int) -> Coord:
  return (x, y)

Using TypeVar

a typevar is a type that is defined at call of the function and you can use that typevar to ensure multiple variables are of the same type by the linter it is also what will get assigned to a return value typevars get super fun with bindings, covariants, and generics

from typing import TypeVar

T = TypeVar("T")

def foo(x: T) -> None:
    m: T
    if isinstance(x, int):
        m = 1
    else:
        m = True

for m: T in above function it only assigns its type so any assignment of m later in the function will be bound to that type because there is no memory given to m it's not like int x; in C++ for example

add example of without the typeVar

x: int
print(x)

gives NameError – why

this is NOT valid:

from typing import TypeVar, Generic

T = TypeVar("T")

class Foo(Generic[T]):
    thing: T

#devstudy #algorithmns #datastructures #problemsolving

Read Before Starting

STOP SKIPPING STEPS EVEN ON EASY QUESTIONS!!!!!!!!!! YOU WILL REGRET IT EVERYTIME!!!!!!!!!!!!!

Most Common Mistakes

EFFY PLEASE VISUALIZE/WRITE MORE TEST CASES – misinterpreting the problem bc going too fast – misunderstanding the problem bc going too fast – implementation issues with scoping

If Stuck

  1. Can you reverse the interpretation?
  2. Can you start the approach with the another input and/or direction?
  3. Can you use a set or a map to store something you're manually reaching for at a later point?
  4. Can you break down the problem more?
  5. Did you make a table of cases to fully visualize the pattern or did you trust your assumptions? Don't trust your assumptions.

Interpretation Patterns

If input array is sorted then – Binary search – Two pointers

If asked for all permutations/subsets then – Backtracking

If given a tree then – DFS – BFS

If given a graph then – DFS – BFS

If given a linked list then – Two pointers

If recursion is banned then – Stack

If must solve in-place then – Swap corresponding values – Store one or more different values in the same pointer

If asked for maximum/minimum subarray/subset/options then – Dynamic programming

If asked for top/least K items then – Heap

If asked for common strings then – Map – Tree

Else – Map/Set for O(1) time & O(n) space – Sort input for O(nlogn) time and O(1) space

#UofTBootcamp #netsec #cyberkillchain #c2 #homework #classwork

Follow-up Questions

11.1 Notes – how does firewall affect zoom/signal? – review TCP flags – meaning of “stateness” as agnostic of network connection? – ACTIVITY: blocking all ICMP pings – i thought this was not a good practice


Homework

Layered Security: multiple products to address a single aspect of security

  • gateway (hardware) and firewall (hard and soft) to restrict access
  • subset of defense in depth
  • evaluated in three areas: administrative, physical, technical
  • admin: policies and procedures, i.e. role-based access control (RBAC) or employee training against phishing scams
  • physical: locking server rooms

Defense in Depth: Redundancy approach

  • strategy leveraging multiple security measures so if one line of defense is compromised, additional layers are backup
  • buys time to launch countermeasures if infiltrated
  • addresses hardware, software, people re: negligence, human error
  • includes anti-virus, firewalls, secure gateways, VPNs, machine learning to detect anomalies in behaviour of employees and endpoints

common issues organizations have to deal with when implementing a cybersecurity strategy:

  • anti-malware software not updated or is not installed on all devices.
  • Employees have not been trained and are falling victim to phishing schemes.
  • Software patches are not being updated or are ignored.
  • Security policies are not enforced or even known by employees.
  • Missing or poorly implemented encryption.
  • Remote employees are connecting to unsecured networks, such as the public internet.
  • Physical security flaws, such as unsecured server rooms.
  • Business partners, such as cloud service providers, are not fully secure.

Elements of Defense in Depth System:

1. Physical Controls: key cards to enter a building or scanners to read fingerprints 2. Net Sec controls: software authenticating employee to enter network/use device/application 3. Admin controls: authorizes employees, once authenticated, to access only certain applications or parts of the network 4. Antivirus: stops malicious software from entering network/spreading 5. Behavioural Analysis: algorithmns/ML can detect anomalies in the behaviour of employees and in the application and devices themselves

Core layers of defense in depth strategy should include:

  • Strong, complex passwords
  • Antivirus software
  • Secure gateway
  • Firewall
  • Patch management
  • Backup and recovery
  • least privilege

  • As companies grow and the number of devices, applications, and services used across the organization increases, these serve as important security layers in a defense-in-depth strategy:

  • Two-factor authentication (2FA) or multi-factor authentication (MFA)

  • Intrusion detection and prevention systems

  • Endpoint detection and response (EDR)

  • Network segmentation

  • Encryption

  • Data loss prevention

  • VPNs

Intrusion Detection and Attack indicators

difference-between-ids-ips-venn-diagram-768x611.webp

1. What's the difference between an IDS and an IPS?

IDS (Intrusion Detection System) is a detection and monitoring tool that doe snot take action on its own so a human (or another system) has to read and interpret the results. IPS (Intrusion Prevention System) is a control system that accepts or rejects a packet based on the rulelist — this means that unlike IDS, the IPS can take action against potential attacks.

Another difference is that IPS sits on the network in the same area as a firewall might (between the outside and internal network) so traffic has to flow through the IPS. An IDS only monitors the traffic, it is not in the line of traffic.

The last difference is that while both are known for generaeting false positives, in the event of an IDS, the false positive will only create alerts whereas for the IPS, this coudl cause the loss of important data or functions (again because it sits on the network).

2. What's the difference between an Indicator of Attack and an Indicator of Compromise?

An Indicator of Attack (IOA) focuses on detecting the intent of what an attacker is trying to accomplish regardless of the malware or exploit being used and is typically an alert before a network or application is exploited. On the other hand, an Indicator of Compromise (IOC) is regarded as the evidence that indicates a network security breach. It is usually gathered after a suspicious incident, on a scheduled basis or after an unusual discovery.

The Cyber Kill Chain

Name each of the seven stages for the Cyber Kill chain and provide a brief example of each.

1. Stage 1: Reconnaisance – Attackers pick a target and perform analysis, collect information (such as email addresses, conference information, technology stack, etc) and evaluate their target's weaknesses.

Example: Trying to discover what firewalls or intrusion prevention systems are in place for a targeted network. Using tools such as nmap, stan, or Strobe to search for vulnerabilities.

2. Stage 2: Weaponization – Attackers determine how best to get inside the network by exploiting the discovered vulnerabilities.

Example: Using a malware tailored to exploit the specific techhology that they discovered in the Reconnaisance stagethat the target network uses. Using a Zero-day vulnerability they have discovered.

3. Stage 3: Delivery – The chosen attack method is delivered to the target encironment.

Example: An infected USB drive is dropped off at the target office, a malicious attachment is sent via a phishing email, etc.

4. Stage 4: Exploitation– The attackers leverage the vulnerabilities and execute the malicious code on the target network.

__Example: __Triggering a Buffer overflow/underflow on a vulnerable database.

5. Stage 5: Installation – The malware weapon is installed, giving the attaker's an access point to the target environment, ideally one that they can return to effortlessly.

Example: A DLL Hijacking attack that exploits the way some Windows applicatons search and load Dynamic Link Libraries (DLL) by copying the name of a legitimate DLL and placing the malicious DLL in a position that the application will search first so that the malicious DLL will load instead. The malicious DLL could be written to launch the malware and then the legitimate DLL can be loaded to avoid suspicion, creating a persistent point of entry for the attacker.

6. Stage 6: Command and Control (C2) – The attackers have uninterrupted remote access to the target environment and can manipulate it to their choosing.

__Example: __

7. Stage 7: Actions on Objective – The original goal(s) of the attack can be executed.

Week 11.1 Notes: Intro Netsec + Firewalls

Defense in Depth: Perimeter || Network || Host || Application || Data

Net Sec Definition from SANS:

  • physical and software preventative measures to protect underlying network infrastructure from unauthorized access, misuse, malfunction, modification, destruction, or improper disclosure
  • goal is to create a secure platform for computers, user, programs to perform permitted critical functions within secure environment

Firewall: between application servers and routers to provide access control

  • control access to single host or network
  • first layer of defense on perimeter of the network's edge
  • can slow connections, affect lack of connection, break networked apps like zoom, messager
  • filter incoming/outgoing packets
  • access policies / rules

Firewall Steps:

(1) Intercept traffic before it reaches target host or router (2) Inspect source and destination address, ports, TCP flags, and other features of incoming packets (3) Allow/deny packets

Firewall Types + OSI

MAC: useless comparison to approval list, can be spoofed easily

STATELESS Packet Filtering : create checkpoints within a router and examine packets as they progress through an interface; if not pass inspection, drop – stateless = does not care about network connection – layer 3-4 – statically evaluate contents of packets and do not keep track of the state of a network connection – use rules based on individual packets such as: source/destination IP, source/destination port info, IP protocols, Ingress and egress interface – vulnerable to spoofing, no custom rules

STATELESS Packet Filtering : still L3-4 but is stateful so it can determine whether a packet is NEW, ESTABLISHED, or rogue bc it understands context of entire data stream. – statefull firewalls do not look at individual packets but connection as a whole – inspect packets' conversation and routing tables, use a combination of TCP handshake verification and packet inspection tech – cannot determine what traffic is doing, only identify that a connection is using x protocol, not what the payload is

Circuit-level gateways: SESSION LAYER – verify the TCP handshake by looking at the HEADER of a packet only – NOT PAYLOAD – TCP handshake checks verify: unique session identifier, state of connection (established vs closed), sequencing info – ensures that session packets are from legit sources – fast/easy but does not check contents of packets – if packet contains malware but has correct TCP, data is allowed to pass

Application gateways: Proxy firewalls L3-7, STATEFUL – inspect actual contents of packet, including authentication and encryption – use deep packet inspection and stateful inspection to determine if incoming traffic is safe or harmful – intercept all traffic without data source knowing – connection is established to proxy firewall which inspects traffic and passes/drops – more secure, provides log/file audit – resource intensive, requires hardware, bypassed with encryption

UFW: Uncomplicated Firewall: provides stateless and stateful packet filtering

  • works on all kinds of network address and port translation, i.e. NAT, NAP (Network Addressing Protection)
  • manage multiple devices over CLI UFW features:
  • host-based
  • multi-level logs, great insight into attacks
  • remote management – security concern?
  • rules for allow/deny regarding: source/destination IP addresses, port numbers, packet types — all without opening packet
  • TCP handshake, packet inspection
  • rate-limited connections to protect from brute force DISADVANTAGE: all firewall services must be stopped/restarted for changes, interrupting service

firewalld: dynamically managed firewall w/o disruption using zones to divide network interfaces into groups of shared trust level

Zones: each zone has rules/configs that can runtime (valid until next reboot or service reload, used for testing) or permanent Services: designate which service you want ot allow, it will automatically open those ports

11.1 Activities

Activity UFW (Uncomplicated Firewall) – need to have ports 110, 143, 587, 80, 443 to be open at all times as part of its daily operations. -


#cryptography

Intro to Crypto

Definitions

encryption: process of modifying a message or informationto prevent authorized access; plaintext to ciphertext w/ key

encoding: digital to binary; publicly available schemes for different circumstances

cypher: method of designing secret or hidden messages

Binary Encoding

  • 8 bits = 1 byte
  • 1 byte: 00000000 to 11111111
  • each byte can represent a number called a decimal

ASCII Encoding

  • convert decimal numbers to text encoding
  • Example: 84 = T, 118 = v, etc

Hex Encoding

  • numeric system made up of 16 symbols of A-F and 0-9
  • example: 52 = R, 7A = z

Octal Encoding

  • digits zero through seven.
  • octal value 042 represents the decimal 34.

https://www.rapidtables.com/

Goals of Cryptography

PAIN Model: Privacy, Authentication, Integrity, Non-Repudiation

  • privacy at rest & in motions
  • authentication: confirm the identities of the sender and receiver of data
  • integrity: not altering message
  • non-repudiation: cannot change history

Cryptography Cyphers

Stream cipher: algorithmn applied one bit (char) at a time

  • enigma
  • caesar cypher: shifting letters a set of number of positions from the original letter

Block cipher: applied in blocks of characters

  • transposition cypher: break input message into equal-sized blocks, rearrange letters of each block

OpenSSL: generate a random key and IV (init vector) to encrypt/decrypt terminal commands

  • create the key and initialization vector (IV) aka randomness
  • openssl enc -pbkdf2 -nosalt -aes-256-cbc -k mypassword -P > key_and_IV

  • enc stands for encryption.

  • -pbkdf2 specifies the encryption key type.

  • -nosalt specifies that salting will not be applied.

  • (Salting, which will be covered in more depth later, adds a random value.)

  • -aes-256-cbc is the name of the cipher used.

  • -k PASSWORD creates a key, with the password mypassword.

  • -P > key_and_IV prints out the key and IV to a file called key_and_IV.

  • For example: key=89E01536AC207279409D4DE1E5253E01F4A1769E696DB0D6062CA9B8F56767C8 iv =EE99333010B23C01E6364E035E97275C

decrypt openssl enc -pbkdf2 -nosalt -aes-256-cbc -in plainmessage.txt.enc -d -base64 -K 89E01536AC207279409D4DE1E5253E01F4A1769E696DB0D6062CA9B8F56767C8 -iv EE99333010B23C01E6364E035E97275C

  • The syntax is the same as the encryption except for -d

Modern Cryptography

key space = 2^bit size

  • key space: the possible range of numbers that can be used as a key for the encryption algo that is defined by the number of binary bits used in the key called bit size

Symmetric Key algos: single shared key

  • DES Data Encryption Standard – 56-bit from 70s
  • 3DES
  • AES Advanced Encryption Standard: 128, 192, 256-bits

Issues with SKE

  • offline exchange: you have to somehow exchange key yo
  • key management when too many

Asymmetric Key Encryptions

  • two-key pair: public & private
  • RSA from 70s = factorization of the product of two prime numbers to deliver encryption of 1024-bits and up to 2048-bit key length

GPG: GNU Privacy Guard

  • CLI tool to simplify creation, encryption, decryption of asymmetric key cryptography
  • see day 2

Hashing: SHA, SHA2, MD, LM, NTLM

  • irreversible/ one way
  • fixed lengths
  • used to store passwords verified against hash
  • see day 2

Encryption

  • bitlocker for Windows – symmetric disk encryption
  • Filevault for mac
  • S/MIME and PGP for emails
  • SSL Secure Socket Layer for web = public key cryp

Stenagraphy: hidden messages within files, images, or videos

SSL Certificates: X.509 is standard

  • data files that use public key cryp to secure connections between browser and web server
  • certificate authority (CA) to issue __ Steps to Issue SSL Cert__ (1) company documents to validate application authentic (2) unique IP address (3) CSR Certificate Signing Request: a block of encrypted data that is created on the web server where the SSL cert will be installed
  • when generating CSR, public key is sent to CA, private is on web server

root store: per-established list of trusted CAs for browsers; – root cert authorities top of trust chain, typically not org that issue SSL cert – intermediate cert authirities – issue cert, report to root auth

Steps to Access Web Traffic: (1) access a secure website, browser asks for cert details (2) server responds with copy of SSL cert and public key (3) browser validates cert by checking expiry and root CA (4) browser uses servers public key to create, encrypt and send a session key (5) server decrypts key, sends acknowledge, starts an encrypted session (6) secure web traffic begins w/ session key

Crytographic Attacks

Statistical Attack: exploits weakness in crypto algo by attemoting to determine in “random” values produced are actually predictable – mitigation: be sure algos use random values

Brute Force Attack: no shit

Birthday/Collision/Hashing Collusion Attack: exploit probability that two separate plaintexts that use the same hash algo will product the same ciphertext – based on probability theory called Birthday Paradox: for any given number of people, there will always be two that share a bday – mitigation: stronger hashing algo limit possibilities

Frequency Analysis for cracking substitution algos – analyze most frequently used letters and infer – mitigation: use a stronger encryption

Replay Attacks: attacker intercepts an encrypted message and replays it to the receiving party to get access, i.e. signal for garage door – mitigation: add an expiration time for data so it cant be used later

hashcat, steghide

#networking #dns #nslookup #dig #cname #aircrackng #UofTBootcamp

Follow-Up Questions from Homework9

Q2 – does it matter that we are getting non-authoritative answers from a recursive resolver (8.8.8.8) vs getting an authoritative one? – what is the difference between using this: nslookup -type=cname www.theforce.net And getting: Non-authoritative answer: www.theforce.net canonical name = theforce.net.

VS.

nslookup -type=cname theforce.net and getting: Non-authoritative answer: *** Can't find theforce.net: No answer

Authoritative answers can be found from: theforce.net origin = WebPublish_Othe mail addr = hostmaster serial = 2017110901 refresh = 900 retry = 600 expire = 86400 minimum = 3600

https://stackoverflow.com/questions/66014432/how-to-find-the-canonical-name-with-nslookup

Q3: – what does NX DOMAIN tell us for sure? https://bluecatnetworks.com/blog/what-you-can-learn-from-an-nxdomain-response/ – follow-up on conclusion


Networking Fundamentals: Homework 9

Your task is a crucial one: Restore the Resistance's core DNS infrastructure and verify that traffic is routing as expected.

Mission 1:

Network Issue:

The Resistence has taken down their primary DNS and email servers in order to a build and deply a new DNS and mail server but they are not currently receiving emails because they have no configured MX Records for the new email servers.

DNS record type found:

We want to check the MX records (mail exchanger records) which specify which mail servers can accept email that's sent to our domain with: starwars.com: nslookup -type=mx starwars.com

DNS records that can explain the reasons for existing network issue:

According to our nslookup results, the new mail servers are not listed. The primary mail server for starwars.com should be asltx.l.google.com and the secondary email should be asltx.2.google.com.

`Server: 192.168.2.1 Address: 192.168.2.1#53

Non-authoritative answer: starwars.com mail exchanger = 5 alt2.aspmx.l.google.com. starwars.com mail exchanger = 1 aspmx.l.google.com. starwars.com mail exchanger = 10 aspmx2.googlemail.com. starwars.com mail exchanger = 10 aspmx3.googlemail.com. starwars.com mail exchanger = 5 alt1.aspx.l.google.com.`

Instead, the primary server (indicated by the numeric value of 1 before the server address) is: aspmx.l.google.com. The secondary server is either: aspmx.l.google.com. or alt1.aspx.l.google.com. as both addresses have the next priority value of 5.

It's likely that these are the old servers and someone has forgotten to change the MX record configuration to the new servers at: asltx.l.google.com and asltx.2.google.com.

Recommended fixes to save the Galaxy!

The corrected MX record should be:

starwars.com mail exchanger = 1 asltx.l.google.com starwars.com mail exhanger = 2 asltx.2.google.com

Mission 2:

Network Issue:

Official emails are going into spam or being blocked because the SPF record has not been updated to reflect the new IP address of their mail server. Since the SPF record is used to indicate which mail servers are allowed to send emails on behalf of a domain, emails from the IP address of the new mail server (missing from the current SPF record) is likely to be filtered out as spam.

DNS record type found:

Looking up the SPF (Sender Policy Framework) record using nslookup -type=txt theforce.net | grep spf to find the following SPF record::

theforce.net text = "v=spf1 a mx mx:smtp.secureserver.net include:aspmx.googlemail.com ip4:104.156.250.80 ip4:45.63.15.159 ip4:45.63.4.215"

Alternatively, we can also use the dig DNS lookup utility: dig theforce.net txt | grep spf which confirms the same SPF record:

theforce.net. 3498 IN TXT "v=spf1 a mx mx:smtp.secureserver.net include:aspmx.googlemail.com ip4:104.156.250.80 ip4:45.63.15.159 ip4:45.63.4.215"

DNS records that can explain the reasons for existing network issues:

The servers currently configured to be allowed to send emails for the domain are from the following IPv4 hosts: 104.156.250.80, 45.63.15.159, and 45.63.4.215. The new one (45.23.176.21) has not beed added. It is likely that similar to Mission 1, someone has forgotten to update changes made while the network was down.

Recommended fixes to save the Galaxy!

We have not been given data regarding the other mail server IP addresses — if we assume that those are still correct and do not need to removed, we only need to add the missing IP so that the corrected record should be:

theforce.net. 3498 IN TXT "v=spf1 a mx mx:smtp.secureserver.net include:aspmx.googlemail.com ip4:104.156.250.80 ip4:45.63.15.159 ip4:45.63.4.215 ip4:45.23.176.21

Mission 3:

Network Issue:

DNS record type found:

We need to check the CNAME record of the resistance.theforce.net domain in order to see why it is not redirecting to theforce.net. A CNAME record is used to point one domain to another so if we want the resistance.theforce.net subdomain to point to theforce.net, we need to have the CNAME configured to do so.

DNS records that can explain the reasons for existing network issues:

Looking up the CNAME (Canonical Name) of www.theforce.net with nslookup in interactive mode in order to examine a correct CNAME configuration where www.theforce.net will be redirected to theforce.net:

nslookup to enter into interactive mode

> set query=CNAME to set the query type to CNAME > www.theforce.net to set the domain to query

This gives the following (relevant) output:

www.theforce.net canonical name = theforce.net.

Alternatively, we can also use single line command nslookup -type=CNAME www.theforce.net or dig www.theforce.net | grep CNAME if we like to confirm things in multiple ways before moving forward:

www.theforce.net. 2321 IN CNAME theforce.net. is the output from dig indicating the correct configuration.

Looking up why our resistance.theforce.net is not redirecting to theforce.net:

Using nslookup -type=CNAME resistance.theforce.net we get:** server can't find resistance.theforce.net: NXDOMAIN which is an error message indicating the DNS query failed because the domain name queried (resistance.theforce.net does not exist or that the query could not “know” that it exists.

This could mean (if we assume we have not made a user error in our query, i.e. mistyping the address): – the domain is currently offline or is having server issues – a security control blocking the domain – domain could be compromised or that malware exists

To follow-up, we can first check if the domain is offline using https://isitup.org/resistance.theforce.net which indicates that the domain is down. This makes sense because we are supposed to be redirecting resistance.theforce.net to the CNAME domain theforce.net so the subdomain should not exist on its own.

Recommended fixes to save the Galaxy!

To fix this, we need to correct the CNAME record configuration to have this line:

resistance.theforce.net canonical name = theforce.net.

Mission 4

Network Issue: DNS record type found: DNS records that can explain the reasons for existing network issues: Recommended fixes to save the Galaxy!

Mission 5:

Network Issue:

Slow network traffic from the planet of Batuu to Jedha due to an attack on Planet N.

The routing protocol in use is OSPF Open Shortest Path First.

Recommended fixes to save the Galaxy!

The new path to use is:

Mission 6:

Your Mission:

  • Figure out the Dark Side's secret wireless key by using Aircrack-ng.

Results from running Aircrack-ng with the password list downloaded from: https://github.com/danielmiessler/SecLists/blob/master/Passwords/WiFi-WPA/probable-v2-wpa-top4800.txt

`[00:00:00] 3432/4800 keys tested (10349.88 k/s)

Time left: 0 seconds 71.67%

KEY FOUND! [ dictionary ]

Master Key : B3 52 50 D0 9F 8E AB BD 0D 9E 3D D3 A3 62 12 82 9E FA 89 FC 19 1D A4 4A 3E 7A 40 9C D4 DF 68 DC

Transient Key : DF 26 D4 B0 47 58 E5 AB 33 66 35 14 87 70 7E 46 9E 93 3F 48 3A AE BE F5 0A 58 81 82 B1 59 56 A4 05 C4 04 F4 F0 E2 27 45 49 3D 51 9C A0 E0 AA 83 5F 63 D5 35 A5 56 52 24 35 70 31 08 BE 99 F6 15

EAPOL HMAC : 3E B9 D6 B8 63 69 A7 8B 83 EA 2A 3A 71 ED CF 59`

The password is: dictionary. We use this password to decrypt the WPA traffic via Wireshark.

  • Once you have decrypted the traffic, figure out the following Dark Side information:

    • Host IP Addresses and MAC Addresses by looking at the decrypted ARP traffic.

Host: Sender MAC address: IntelCor_55:98:ef (00:13:ce:55:98:ef) Sender IP address: 172.16.0.101 (172.16.0.101)

Looking for: Sender MAC address: Cisco-Li_e3:e4:01 (00:0f:66:e3:e4:01) Sender IP address: 172.16.0.1 (172.16.0.1)

Mission 7:

Viewing the DNS record from Mission #4, specifically looking for a hidden message in the TXT record:

nslookup -type=txt princessleia.site to find this message:

princessleia.site text = "Run the following in a command line: telnet towel.blinkenlights.nl or as a backup access in a browser: www.asciimation.co.nz"

Take a screen shot of the results:

Note: This was the coolest last homework question ever! And thank you for reading.

#devstudy #algorithmns #datastructures #problemsolving

  1. Can you reverse the interpretation?
  2. Can you start the approach with the another input and/or direction?
  3. Can you use a set or a map to store something you're manually reaching for at a later point?
  4. Can you break down the problem more?
  5. Did you make a table of cases to fully visualize the pattern or did you trust your assumptions? Don't trust your assumptions.

#wireshark #networking #ip #tcp #udp #arp #http #dns #aircrack #nslookup #cheatsheet #UofTBootCamp


General

!(arp or icmp or dns) filter out whatever udp contains xx:xx:xx filter for certain HEX values at any offset

Search by string/regex/hex value: Edit > Find Next > Select your Filter/Search Input


802.11

Wireshark Beacon Filter: wlan.fc.type_subtype = 0x08 Wireshark broadcast filter: eth.dst == ff:ff:ff:ff:ff:ff Wireshark multicast filter: (eth.dst[0] & 1)


ARP

arp.opcode == 1 for requests arp.opcode == 2 for responses

Operation code params: https://www.iana.org/assignments/arp-parameters/arp-parameters.xhtml#arp-parameters-1


DNS

queries: dns.flags.response == 0 responses: dns.flags.response == 1

errors: dns.flags.rcode == 0 no error dns.flags.rcode != 0 dns requests couldn't be correctly resolved. dns.flags.rcode == 3 no such name

examples dns.a dns.cname dns.qry.name == example.com dns.resp.name == example.com dns.resp.name == example.com and dns.time > 0.01


HTTP

http.request.method==GET http.request.method==POST. ip.addr==93.184.216.34 and http.request.method==GET


IP

ip.addr == < ip > ip.dest == < ip > ip.src == < ip > !(ip.addr == <ip>) range: ip.addr >= 10.10.50.1 and ip.addr <= 10.10.50.100 multiple: ip.addr == <ip> and ip.addr == <ip> subnet: ip.addr == 10.10.50.1/24 port: tcp.port == 25 or tcp.dstport == 23 ip and port: ip.addr == <ip> and Tcp.port == 25


TCP

handshake: SYN, SYN/ACK, ACK tcp.flags.syn ==1 && tcp.flags.ack == 0 to view only SYN tcp.flags.syn ==1 && tcp.flags.ack == 1 to view only SYN/ACK requests tcp.flags.syn == 0 && tcp.flags.ack == 1 to view only ACK

termination packets: tcp.flags.fin == 1

look for open port: (since it will respond with SYN/ACK) tcp.flags.syn == 1 && tcp.flags.ack == 1

display all TCP resets: (connection killed) tcp.flags.reset==1

packets that contain a certain term in packet: tcp contains xxx

Follow a tcp stream: tcp.stream eq X

Filter by seq num: tcp.seq == x

Detects push events for troubleshooting: tcp.flags.push == 1


nslookup

Syntax: nslookup -type=[NS record type] [domain] look up name server records

nslookup Option Description -domain=[domain-name] Change the default DNS name. -debug Show debugging information. -port=[port-number] Specify the port for queries. The default port number is 53. -timeout=[seconds] Specify the time allowed for the server to respond. -type=a View information about the DNS A address records. -type=any View all available records. -type=hinfo View hardware-related information about the host. -type=mx View Mail Exchange server information. -type=ns View Name Server records. -type=ptr View Pointer records. Used in reverse DNS lookups. -type=soa View Start of Authority records.

nslookup -type=txt <domain> for spf records


Aircrack-ng

  • syntax: Aircrack-ng [.pcap file name]
  • Note: the Wireless Toolbar no longer exists in view > it is now in: Wireshark > Preferences > Protocols > IEEE 802.11 for putting in relevant key

Word lists for WPA https://www.aircrack-ng.org/doku.php?id=faq#where_can_i_find_good_wordlists

#networking #OSI #wireshark #dns #nslookup #tcp #ip #80211 #email #UofTBootcamp #arp

Follow-Up Questions from Class Activities

  • Activity 9.2.09 on Email Security: missing emails? Why is SPF failing – can't see the email Networking Review Activity:
  • What networking devices use these values for mac addresses- don't they all?
  • What is the original source IP? 0.0.0.0??
  • CIDR & ip range review!! Network Attacks Review Activity:
  • if this is the only data, how can you know for sure which is good/which is mac address of hacker's device? [Duplicate IP address detected for 192.168.47.254 (00:0c:29:1d:b3:b1) - also in use by 00:50:56:f9:f5:54 (frame 2013)]

DNS

  • translates URI into IP address
  • DNS zone file: actual file containing all the DNS records for a particular domain
  • lives in DNS server
  • contains a TTL indicating how long a DNS cache will remember the information

DNS Record Types: CONTAINED IN DNS ZONE FILE

  • A Record: Translates domain to IP address
  • PTR Record: Translates IP into domain
  • CNAME Record: Alias record used to point one domain to another domain
  • SOA record: Contains administrative details about a domain, such as: email address of the administrator, TTL value, when the domain was last updated

MX Record: mail exchange: directs emails to specific mail server; if multiple, can be set with preferences

TXT Record: created to include human-readable notes

SPF record: Sender Policy Framework: determines if email is from a trusted server

  • type of TXT Record
  • indicates which mail servers are allowed to send emails on behalf of a domain by checking:
  • Check the sending mail server's IP address, 12.54.54.23.
  • Validate the DNS record of widget.com's SPF record to confirm the sending mail server's IP address is either 23.43.54.235 or 23.43.54.236 (the valid mail server IPs)
  • Since the sender's IP is 12.54.54.23 (not 23.43.54.235 or 23.43.54.236), gadgets.com's mail server can identify the email as spam and potentially reject it or send it to the recipient's spam folder.

nslookup

nslookup -type=[NS record type] [domain] look up name server records

To look up the MX record: nslookup -type=MX gadget.com

To look up the A record: nslookup -type=A gadget.com

To look up the SOA record: nslookup -type=SOA gadget.com

nslookup Option Description -domain=[domain-name] Change the default DNS name. -debug Show debugging information. -port=[port-number] Specify the port for queries. The default port number is 53. -timeout=[seconds] Specify the time allowed for the server to respond. -type=a View information about the DNS A address records. -type=any View all available records. -type=hinfo View hardware-related information about the host. -type=mx View Mail Exchange server information. -type=ns View Name Server records. -type=ptr View Pointer records. Used in reverse DNS lookups. -type=soa View Start of Authority records.

Email Headers

Some of the most important fields in this raw email are:Return-Path: Specifies the sender's return email. – Delivered-To: Specifies the recipients email. – Received: Shows a list of mail servers, illustrating the path taken by the email from its source to destination. – Message-ID: A unique string created by the sending mail server as an identifier of the email. – Received SPF: The SPF verification field, which we will cover in more detail in the next activity.

Security Concerns for Emails

__ SPAM__: mitigate with using SPF records, matching list of known spam senders, and keyword identification Sending Confidential Emails across encrypted channels: – emails are typically routed across multiple mail servers – encryption tools: PGP: Pretty Good Privacy or S/MIME: Secure/Multipurpose Internet Mail ExtensionsEmail Spoofing

Detecting Email Spoofing:

(1) Check the From email header (2) Check the Received-SPF email header – Received-SPF uses the IP address from the Received field and determines if it's an IP of an authorized sender with pass/fail (3) Check the Received Email Header – look up the source IP of the mail server that sent the email – For example, the ARIN Whois/RDAP tool.


Class Activities

Analyzing DNS Records:

MX Record: splunk.com mail exchanger = 20 mx1.splunk.iphmx.com. splunk.com mail exchanger = 20 mx2.splunk.iphmx.com. Type A Record: Non-authoritative answer: Name: splunk.com Address: 52.5.196.118 Name Server Non-authoritative answer: splunk.com nameserver = ha2.markmonitor.zone. splunk.com nameserver = ha1.markmonitor.zone. splunk.com nameserver = ha4.markmonitor.zone. splunk.com nameserver = ha3.markmonitor.zone.

Bonus: dig nmap.org txt | grep "spf" gives us 3 servers authorized to send mail from:

nmap.org. 3600 IN TXT "v=spf1 a mx ptr ip4:45.33.49.119 ip6:2600:3c01::f03c:91ff:fe98:ff4e ip6:2600:3c01:e000:3e6::6d4e:7061 `include:_spf.google.com ~all"

Analyzing Email Headers Activity:

determine the following data points: Email 1: – Delivered-To: juliejones@acme.com – Return-Path: jonathanthomas@microsoft.com – IP address of source domain: 40.76.4.15 from: Received-SPF: pass (google.com: domain of jonathanthomas@microsoft.com designates 40.76.4.15 as permitted sender) client-ip=40.76.4.15; – Message-ID: 1689837351.2998569.1568044304435@mail.microsoft.com

Email 2: permitted by SPF but clearly spam – Delivered-To: juliejones@acme.com – Return-Path: xzvvvret34344@yahoo.com – IP address of source domain: 74.6.130.41 from: Received-SPF: pass (google.com: domain of xzvvvret34344@yahoo.com designates 74.6.130.41 as permitted sender) client-ip=74.6.130.41; – Message-ID: 1689837351.2998569.1568044304435@mail.yahoo.com

Email 3: – Delivered-To: juliejones@acme.com – Return-Path: timmytom@widgets.com – IP address of source domain: 34.86.130.4 from: Received-SPF: fail (google.com: domain of timmytom@widgets.com does not designate 34.86.130.49 as permitted sender) client-ip=34.86.130.49 ; – Message-ID: 1gytrdd9837351.987987abs9.1568044304435@mail.widgets.com

Networking Review Activity

A. Answer the following questions on HTTP: 7. What is the the port number range that this port is part of? 58424 or 62412 There are 49,152 – 65,535 dynamic and/or private ports.

  • Under Ethernet II is a value of Destination: Technico_65:1a:36 (88:f7:c7:65:1a:36)
    1. What does this value represent? MAC address of physical device where this is going
    2. Which OSI layer does this exist in? Datalink (2)
    3. What networking devices use these values? Don't all devices?

Part Two: ARP

  1. What type of networking request does ARP first make? Broadcast

B. Use a filter to find the count of ARP responses, and answer the following questions:

arp.opcode 0 Reserved [RFC5494] 1 REQUEST [RFC826][RFC5227] 2 REPLY [RFC826][RFC5227]

arp.opcode == 1 for requests arp.opcode == 2 for responses

  1. What is the IP of the device that is responding? Sender MAC address: IntelCor_10:ac:c0 (a0:a4:c5:10:ac:c0) Sender IP address: 10.0.0.32 (10.0.0.32)

  2. To what IP is the device responding to? Target IP address: c66251b0-093d Target MAC address: c66251b0-093d-7d9c-4f7c-c2fc9df7c3ca.local (e4:f0:42:3b:7a:de) -7d9c-4f7c-c2fc9df7c3ca.local (10.0.0.10)

  3. Write out in simple terms what has taken place, describing the request and response. Host makes a broadcast to find the MAC address of the IP = request. Response = information locating the MAC address.

DHCP B. Use a filter to view the DHCP Discover, and answer the following questions on that packet:

###1. What is the original source IP? 0.0.0.0????###

  1. Why does it have that value? Unknown IP – usually to indicate that the local IP address is not assigned.

  2. What is the original destination IP? Internet Protocol Version 4, Src: 0.0.0.0 (0.0.0.0), Dst: 255.255.255.255 (255.255.255.255)

  3. What does that value signify? broadcast

C. Use a filter to view the DHCP ACK, and answer the following questions on that packet. dhcp.option.dhcp == 5

### 1. Explain in simple terms what is happening in this packet.

  • DHCP Ack server which received the DHCP request message fro client checks if the IP address shown in the DHCP Server Identifier matches its own
  • broadcasts a DHCP Ack message ensuring client can receive the message -transfer net config data to client including:

    • IP address
    • Subnet mask
    • Default gateway IP address
    • DNS server IP address
    • Lease time (during which a client can use the IP address allocated/leased by a DHCP server)
    1. Define the term “DHCP lease.” Amount of time in minutes or seconds a network device can use an IP address in a network. IP is reserved for that device until expiration.

    2. What is the DHCP lease time provided in this packet? IP Address Lease Time: (604800s) 7 days

    3. What are the steps in a TCP connection? SYN, SYN-ACK, ACK

    4. What are the steps in a TCP termination? FIN. ACK, FIN, ACK

    5. What steps appear in the packets displayed? the handshake steps

    6. What type of activity/protocol is TCP establishing a connection for? in this case httpTCP is generally used to provide reliable stream delivery service, i.e. delivering data as a stream of bytes and deceiving data as a stream of bytes.

    7. What is the website name being accessed after the TCP connection? Host: sportingnews.com\r\n

Topologies

  1. What are the Topologies for A, B, C? Tree, Hybrid of Bus and Tree, Disconnected ring?

  2. What are the advantages and disadvantages for each?

    • Network Devices
  3. In the network devices illustration, what are numbers one through four? Internet, Firewall, router, Switch

  4. What does the dashed line represent in number five? firewall security?

  5. What is a load balancer? distributes traffic across multiple servers to improve application availability and responsiveness and prevent server overload

4. Where would you place a load balancer? Between access and servers? Internet || servers or switch || servers?

  • Network Routing
  • Which routing protocols use distance as criteria? Distance Vector Routing Protocols:
  • RIP (Routing Information protocol)
  • EIGRP (Enhanced Interior Gateway Routing Protocol)
  1. Which routing protocols use speed as criteria? Link-State Routing Protocols
  2. OSPF: Open Shortest Path First

Part Six: Network Addressing:

  1. Define binary. base-2 number system (0 and 1s) used to write machine code

  2. What are IP addresses used for? network interface identification and location addressing

  3. What are the two primary versions of IP addresses? IPv4 and IPv6

  4. How many octets are in a IPV4 address? IPv4 – 32 bits – 4 octects IPv6 – 128 bits – 16 octets

  5. What is the difference between primary and public IP addresses? private is within a network or subnet, public is on the internet and unique.

8. What is CIDR? “Classless Inter-Domain routing”

  • allocating IP addesses and IP routing

9. What is the range of IP addresses in: 192.18.65.0/24?


Network Attacks Review Activity

  • ARP spoof attack – redirects traffic
  • DHCP starvation attack – floods with DHCP requests so runs out of IP, type of denial of service
  • TCP packets show port scanning,
  • Wireless Attacks:
  • What are the different security types available for Wireless communications? List them in order from least to most secure. WEP – WPA – WPA2
  1. What is 802.11? Wifi Standard (protocol)

  2. What is an SSID? a more recognizable format of how a networking hardware device identifies itself as broadcasting a wireless signal beacon

  3. What is the name of the the signal a WAP sends out identifying its SSID? beacon

  4. If a user has WEP encrypted wireless, what is a potential negative outcome? it's old and hackable easily with aircrack-ng

#datastructures #algorithmns #devstudy #BigONotation #timecomplexity #spacecomplexity

jarednielsen-big-o.png

Time Complexity: Time taken to run as a function of the length of the input

  • number of operations it takes to complete for length Input
  • find the WORST CASE scenario > drop the non-dominant terms

Not the most useful chart but that pastel-tone charcoal = yes

timecomplexity.png

Better chart but less aesthetic:

big-o-cheatsheet.png

From Fastest to Slowest:

O(1) time: One Operation

  • takes a constant amount of time even with more input
  • ex: mathematical calculation of sum: s = n(a+1)/2 as opposed iterative calculation which is O(n) linear bc for every additional input value, the rate of growth re: time scales proportionally.

Examples

  • accessing Array Index
  • Inserting a node in Linked List
  • Pushing and Popping on Stack
  • Insertion and Removal from Queue
  • Finding out the parent or left/right child of a node in a tree stored in Array
  • Jumping to Next/Previous element in Doubly Linked List

O(log n) time: Recursion?

Examples

  • Binary Search
  • Finding largest/smallest number in a binary search tree
  • Certain Divide and Conquer Algorithms based on Linear functionality
  • Calculating Fibonacci Numbers – Best Method premise = NOT using the complete data, and reducing the problem size with every iteration

O(n) time: Linear, i.e. Brute Force, Noob ones that I write bc my brain is stuck on iteration

Examples

  • Traversing an array
  • Traversing a linked list
  • Linear Search
  • Deletion of a specific element in a Linked List (Not sorted)
  • Comparing two strings
  • Checking for Palindrome
  • Counting/Bucket Sort and here too you can find a million more such examples....

O(n*log n) time: linear time complexity multiplied by log n

  • factor of log n is introduced by bringing into consideration Divide and Conquer.
  • some of the most optimized and frequently used

Examples

  • Merge Sort (recursive)
  • Heap Sort
  • Quick Sort
  • Certain Divide and Conquer Algorithms based on optimizing O(n^2) algorithms

O(n^2) time: Quadratic.

  • nested loops bc each loop is performing n iterations so n*n
  • less efficient algorithms if their O(n*logn) counterparts are present??
  • general application may be Brute Force here

Examples

  • Bubble Sort :'(
  • Insertion Sort
  • Selection Sort
  • Traversing a simple 2D array

Space Complexity: The space an algo needs to run

  • sorting algorithmns need at least O(n) space to save the list of length n that they have to sort but can often work in place meaning that it needs no additional space
  • number representation can be saved in either (1) binary (or any other base equal or less than 2) so this needs O(log n) space bc n = 2^logn; or (2) as a sum of n so you need O(n) space bc you need to save each n

O(1) space: In-place

  • a function that counts the elements of an array: don't need to allocate or copy new data even if the array is large, the counter is the same var

O(log n) space:

Examples

  • Binary Search
  • Finding largest/smallest number in a binary search tree
  • Certain Divide and Conquer Algorithms based on Linear functionality
  • Calculating Fibonacci Numbers – Best Method premise = NOT using the complete data, and reducing the problem size with every iteration

O(n) space:

  • everytime we make a new function call = new stack frame
  • recursion: if n = 100, then O(n)

#datastructures #recursion #devstudy #algorithmns

Characteristics of a Recursive Problem

  • Can the problem be broken down into a smaller version of itself?
  • Can I re-use the solution to solve the problem?
  • Do I have an abstracted solution that already exists??

THE PROCESS: DO NOT SKIP STEPS you will regret it

1. What is the simplest input? This is your base case. There might be more than one.

2. Visualize the Problem Without Words. Find the smallest subproblem and focus ONLY on the sub-problem. – do not think about the implementation beyond the subproblem

3. What is the relationship between the Second-To-Last to Last Case? If I am given the answer for the Second-To-Last case, can I find the Last Case? Can I solve?

4. Generalize the pattern: This is your recursive function.

5. Trust the abstraction. If the logic is sound, solving the sub problem will solve the problem.


MISTAKES I KEEP MAKING

  1. Breaking the Problem using syntax short cuts to express my thoughts and letting this draw me into assumption patterns without consciously realizing the pull.

What to do: Visualize the problem WITHOUT WORDS. Just do it.

  1. Thinking too much about the implementation in the rest of the problem instead of trusting that the recursion will work if the logic for the subproblem is sound.

What to do: Set a timer and spent 80% of time on thinking.

  1. Not spending enough time visualizing different examples.

What to do: See 1.

  1. Not trust that my logic IS sound and seeing all errors are evidence that there is a fundamental misunderstanding of the problem rather than realizing that sometimes, it's IS an implementation error.

What to do: Build more confidence by listening to positive feedback without immediately dismissing it. Spend more time coding so I know the idiosyncrasies of the language better.

  1. Implementation Errors: Going too fast to notice incorrect assumptions of what I am asking CREATOR to do.

What to do: More puts, debug line by line. Go slower....