Mac OSX: Altering the OS route table to re-direct the traffic of a website to a different interface (eg re-routing whatsapp traffic to en0)

This was a hard article to figure out the title for! Put simply, your mac book has a route table and if you want to move a specific IP address or dns from one interface to another, then follow the steps below:

First find the IP address of the website that you want to re-route the traffic for:

$ nslookup web.whatsapp.com
Server:		100.64.0.1
Address:	100.64.0.1#53

Non-authoritative answer:
web.whatsapp.com	canonical name = mmx-ds.cdn.whatsapp.net.
Name:	mmx-ds.cdn.whatsapp.net
Address: 102.132.99.60

We want to re-route traffic the traffic from: 102.132.99.60 to the default interface. So first lets find out which interface this traffic is currently being routed to?

$ route -n get web.whatsapp.com
   route to: 102.132.99.60
destination: 102.132.99.60
    gateway: 100.64.0.1
  interface: utun0
      flags: <UP,GATEWAY,HOST,DONE,WASCLONED,IFSCOPE,IFREF>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0        34        21         0      1400         0

So this is currently going to a tunnelled interface called utun0 on gateway 100.64.0.1.

Ok, so I want to move if off this tunnelled interface. So lets first display the kernel routing table. The -n option forces netstat to print the IP addresses. Without this option, netstat attempts to display the host names.

$ netstat - rn | head -n 5
Active Internet connections
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)
tcp4       0    126  100.64.0.1.64770       136.226.216.14.https   ESTABLISHED
tcp4       0      0  100.64.0.1.64768       whatsapp-cdn-shv.https ESTABLISHED
tcp4       0      0  100.64.0.1.64766       52.178.17.3.https      ESTABLISHED

Now we want to re-route whatsapp to the default interface. So lets get the IP address of the default interface.

$ netstat -nr | grep default
default            192.168.8.1        UGScg                 en0
default                                 fe80::%utun1                            UGcIg               utun1
default                                 fe80::%utun2                            UGcIg               utun2
default                                 fe80::%utun3                            UGcIg               utun3
default                                 fe80::%utun4                            UGcIg               utun4
default                                 fe80::%utun5                            UGcIg               utun5
default                                 fe80::%utun0                            UGcIg               utun0

We can see that our en0 interface is on IP address: 192.168.8.1. So lets re-route the traffic from Whatsapp’s ip address to this interace’s IP address:

$ sudo route add 102.132.99.60 192.168.0.1
route: writing to routing socket: File exists
add host 102.132.99.60: gateway 192.168.8.1: File exists

Now lets test if we are routing via the correct interface:

$ route -n get 102.132.99.60
   route to: 102.132.99.60
destination: 102.132.99.60
    gateway: 192.168.8.1
  interface: utun6
      flags: <UP,GATEWAY,HOST,DONE,STATIC>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1400         0

Finally delete the route and recheck the routing:

$ sudo route delete 102.132.99.60
delete host 102.132.99.60

$ route -n get 102.132.99.60
   route to: 102.132.99.60
destination: 102.132.99.60
    gateway: 100.64.0.1
  interface: utun6
      flags: <UP,GATEWAY,HOST,DONE,WASCLONED,IFSCOPE,IFREF>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1400         0

AWS: Use the AWS CLI to delete snapshots from your account

The Amazon EC2 console allows you to delete up to 50 Amazon Elastic Block Store (Amazon EBS) snapshots at once. To delete more than 50 snapshots, use the AWS Command Line Interface (AWS CLI) or the AWS SDK.

To see all the snapshots that you own in a specific region, run the following. Note, replace af-south-1 with your region:

aws ec2 describe-snapshots --owner-ids self  --query 'Snapshots[]' --region af-south-1

Note: To run the code below, first make sure your in the correct account (or life will become difficult for you). Next replace BOTH instances “af-south-1” with your particular region. Finally, you can use a specific account number in place of –owner-ids=self (eg –owner-ids=1234567890).

for SnapshotID in $(aws ec2 --region af-south-1 describe-snapshots --owner-ids=self --query 'Snapshots[*].SnapshotId' --output=text); do
aws ec2 --region af-south-1 delete-snapshot --snapshot-id ${SnapshotID}
done

Macbook OSX: Using Touch ID / fingerprints to enable SUDO and permanently enabling this after Mac OSX updates

Each day that I wake up I try and figure out if I can do less work than yesterday. With this in mind I was playing around to see if there is a way to save me typing my password each time I SUDO. It turns out this is quite a simple change…

Open Terminal and run the following to edit sudos behaviour:

sudo nano /etc/pam.d/sudo

Next add the following to the top of the file:

auth       sufficient     pam_tid.so

The only issue with this is that /etc/pam.d/sudo is overwritten on every macOS update (major, minor or patch – it is always overwritten and reset back to its default state).

MacOS: Sonoma

In their “What’s new for enterprise in macOS Sonoma” document Apple listed the following in the “Bug fixes and other improvements” section:

Touch ID can be allowed for sudo with a configuration that persists across software updates using /etc/pam.d/sudo_local. See /etc/pam.d/sudo_local.template for details.

So lets create a template file in /etc/pam.d/sudo_local.template:

sudo nano /etc/pam.d/sudo_local.template

Next uncomment the auth line, as per:

# sudo_local: local config file which survives system update and is included fo$
# uncomment following line to enable Touch ID for sudo
auth       sufficient     pam_tid.so

This should mean that Touch ID now survive system updates!

Quick tests:

sudo ls
# exit sudo
sudo -k
sudo ls

To enable Touch ID access on Iterm2. You need to do the following. Go to Prefs -> Advanced -> Allow sessions to survive logging out and back in and set value to no . Restart Iterm2 and touch ID authentication will work on Iterm2.

Macbook OSX: Change the default image type of your screenshots from PNG to JPEG, GIF or PDF

There are a few things that I tweak when I get a new Macbook, one of which is the screenshot format (mainly because it doesnt natively render in Whatsapp). So I thought I would share the code snippet that you can run in Terminal to alter the default image type of your screenshots:

For JPEG use:

$ defaults write com.apple.screencapture type JPG

For GIF use:

$ defaults write com.apple.screencapture type GIF

For PDF use:

$ defaults write com.apple.screencapture type PDF

For PNG use:

$ defaults write com.apple.screencapture type PNG

How to make an offline copy of a static website using wget and hosting on AWS S3 with CloudFront

I have an old website that I want to avoid the hosting costs and so just wanted to download the website and run it from an AWS S3 bucket using Cloud Front to publish the content. Below are the steps I took to do this:

First download the website to your laptop

$ wget \
     --recursive \
     --no-clobber \
     --page-requisites \
     --html-extension \
     --convert-links \
     --no-check-certificate \
     --restrict-file-names=unix \
     --domains archive.andrewbaker.ninja \
     --no-parent \
         http://archive.andrewbaker.ninja/
$ cd archive.andrewbaker.ninja
$ ls

Below is a summary of the parameters (inc common alternatives):

–recursive: Wget is capable of traversing parts of the Web (or a single HTTP or FTP server), following links and directory structure. We refer to this as to recursive retrieval, or recursion.

–no-clobber: If a file is downloaded more than once in the same directory, Wget’s behavior depends on a few options, including `-nc’. In certain cases, the local file will be clobbered, or overwritten, upon repeated download. In other cases it will be preserved. When running Wget without `-N’`-nc’, or `-r’, downloading the same file in the same directory will result in the original copy of file being preserved and the second copy being named `file.1′. If that file is downloaded yet again, the third copy will be named `file.2′, and so on. When `-nc’ is specified, this behavior is suppressed, and Wget will refuse to download newer copies of `file. Therefore, “no-clobber” is actually a misnomer in this mode–it’s not clobbering that’s prevented (as the numeric suffixes were already preventing clobbering), but rather the multiple version saving that’s prevented. When running Wget with `-r’, but without `-N’ or `-nc’, re-downloading a file will result in the new copy simply overwriting the old. Adding `-nc’ will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored. When running Wget with `-N’, with or without `-r’, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file (see section Time-Stamping). `-nc’ may not be specified at the same time as `-N’. Note that when `-nc’ is specified, files with the suffixes `.html’ or (yuck) `.htm’ will be loaded from the local disk and parsed as if they had been retrieved from the Web.

–page-requisites: This causes wget to download all the files that are necessary to properly display a given HTML page which includes images, css, js, etc. –adjust-extension Preserves proper file extensions for . html, . css, and other assets

–html-extension: This adds .html after the downloaded filename, to make sure it plays nicely on whatever system you’re going to view the archive on

–convert-links: After the download is complete, convert the links in the document to make them suitable for local viewing. This affects not only the visible hyperlinks, but any part of the document that links to external content, such as embedded images, links to style sheets, hyperlinks to non-HTML content, etc.

–no-check-certificate: Don’t check the server certificate against the available certificate authorities. Also don’t require the URL host name to match the common name presented by the certificate.

–restrict-file-names: By default, Wget escapes the characters that are not valid or safe as part of file names on your operating system, as well as control characters that are typically unprintable. This option is useful for changing these defaults, perhaps because you are downloading to a non-native partition”. So unless you are not downloading to non-native partition you do not need to restrict file names by OS. its automatic. Additionally: “The values ‘unix’ and ‘windows’ are mutually exclusive (one will override the other)”

–domains: Limit spanning to specified domains

–no-parent: If you don’t want wget to descend down to the parent directory, use -np or –no-parent option. This instructs wget not to ascend to the parent directory when it hits references like ../ in href links.

Upload Files to S3 Bucket

Next upload the files to your S3 bucket. First move into the relevant bucket, then perform the recursive upload.

$ cd archive.andrewbaker.ninja
$ ls .
$ aws s3 cp . s3://vbusers.com/ --recursive

Create a CloudFront Distribution from an S3 Bucket

Finally go to CloudFront and create a distribution from the S3 Bucket you just created. You can pretty much use the default settings. Note: you will need to wait a few minutes before you browse to the distributions domain name:

AWS: Automatically Stop and Start your EC2 Services

Below is a quick (am busy) outline on how to automatically stop and start your EC2 instances.

Step 1: Tag your resources

In order to decide which instances stop and start you first need to add an auto-start-stop: Yes tag to all the instances you want to be affected by the start / stop functions. Note: You can use “Resource Groups and Tag Editor” to bulk apply these tags to the resources you want to be affected by the lambda functions you are going to create. See below (click the orange button called “Manage tags of Selected Resources”).

Step 2: Create a new role for our lambda functions

First we need to create the IAM role to run the Lambda functions. Go to IAM and click the “Create Role” button. Then select “AWS Service” from the “Trusted entity options”, and select Lambda from the “Use Cases” options. Then click “Next”, followed by “Create Policy”. To specify the permission, simply Click the JSON button on the right of the screen and enter the below policy (swapping the region and account id for your region and account id):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances",
                "ec2:StartInstances",
                "ec2:DescribeTags",
                "logs:*",
                "ec2:DescribeInstanceTypes",
                "ec2:StopInstances",
                "ec2:DescribeInstanceStatus"
            ],
            "Resource": "arn:aws:ec2:<region>:<accountID>:instance/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/auto-start-stop": "Yes"
                }
            }
        }
    ]
}

Hit next and under “Review and create”, save the above policy as ec2-lambda-start-stop by clicking the “Create Policy” button. Next, search for this newly created policy and select it as per below and hit “Next”.

You will now see the “Name, review, and create” screen. Here you simply need to hit “Create Role” after you enter the role name as ec2-lambda-start-stop-role.

Note the policy is restricted to only have access to EC2 instances that contains auto-start-stop: Yes tags (least privileges).

If you want to review your role, this is how it should look. You can see I have filled in my region and account number in the policy:

Step 3: Create Lambda Functions To Start/Stop EC2 Instances

In this section we will create two lambda functions, one to start the instances and the other to stop the instances.

Step 3a: Add the Stop EC2 instance function

  • Goto Lambda console and click on create function
  • Create a lambda function with a function name of stop-ec2-instance-lambda, python3.11 runtime, and ec2-lambda-stop-start-role (see image below).

Next add the lamdba stop function and save it as stop-ec2-instance. Note, you will need to change the value of the region_name parameter accordingly.

import json
import boto3

ec2 = boto3.resource('ec2', region_name='af-south-1')
def lambda_handler(event, context):
   instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
   for instance in instances:
       id=instance.id
       ec2.instances.filter(InstanceIds=[id]).stop()
       print("Instance ID is stopped:- "+instance.id)
   return "success"

This is how your Lambda function should look:

Step 3b: Add the Start EC2 instance function

  • Goto Lambda console and click on create function
  • Create lambda functions with start-ec2-instance, python3.11 runtime, and ec2-lambda-stop-start-role.
  • Then add the below code and save the function as start-ec2-instance-lambda.

Note, you will need to change the value of the region_name parameter accordingly.

import json
import boto3

ec2 = boto3.resource('ec2', region_name='af-south-1')
def lambda_handler(event, context):
   instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']},{'Name': 'tag:auto-start-stop','Values':['Yes']}])
   for instance in instances:
       id=instance.id
       ec2.instances.filter(InstanceIds=[id]).stop()
       print("Instance ID is stopped:- "+instance.id)
   return "success"

4. Summary

If either of the above lambda functions are triggered, they will start or stop your EC2 instances based on the instance state and the value of auto-start-stop tag. To automate this you can simply setup up cron jobs, step functions, AWS Event Bridge, Jenkins etc.

Finding and Setting the Maximum Transmission Unit (MTU) on a Windows Machine

If you have just changed ISPs or moved house and your internet suddenly starts misbehaving the likelihood is your Maximum Transmission Unit (MTU) is set too high for your ISP. The default internet facing MTU is 1500 bytes, BUT depending on your setup, this often needs to be set much lower.

Step 1:

First check your current MTU across all your ipv4 interfaces using netsh:

netsh interface ipv4 show subinterfaces
   MTU  MediaSenseState   Bytes In  Bytes Out  Interface
------  ---------------  ---------  ---------  -------------
4294967295                1          0          0  Loopback Pseudo-Interface 1
  1492                1        675        523  Local Area Connection

As you can see, the Local Area Connection interface is set to a 1492 bytes MTU. So how do we find out what it should be? We are going to send a fixed size Echo packet out, and tell the network not to fragment this packet. If somewhere along the line this packet is too big then this request will fail.

Next enter (if it fails then you know your MTU is too high):

ping 8.8.8.8 -f -l 1492

Procedure to find optimal MTU:

For PPPoE, your Max MTU should be no more than 1492 to allow space for the 8 byte PPPoE “wrapper”. 1492 + 8 = 1500. The ping test we will be doing does not include the IP/ICMP header of 28 bytes. 1500 – 28 = 1472. Include the 8 byte PPPoE wrapper if your ISP uses PPPoE and you get 1500 – 28 – 8 = 1464.

The best value for MTU is that value just before your packets get fragmented. Add 28 to the largest packet size that does not result in fragmenting the packets (since the ping command specifies the ping packet size, not including the IP/ICMP header of 28 bytes), and this is your Max MTU setting.

The below is an automated ping sweep, that tests various packet sizes until it fails (increasing in 10 bytes per iteration):

C:\Windows\system32>for /l %i in (1360,10,1500) do @ping -n 1 -w 8.8.8.8 -l %i -f

Pinging 8.8.8.8. with 1400 bytes of data:
Reply from 8.8.8.8: bytes=1400 time=6ms TTL=64

Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 6ms, Maximum = 6ms, Average = 6ms

Pinging 8.8.8.8 with 1401 bytes of data:
Reply from 8.8.8.8: bytes=1401 time<1ms TTL=64

Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

Pinging 8.8.8.8 with 1402 bytes of data:
Reply from 8.8.8.8: bytes=1402 time<1ms TTL=64

Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

Pinging 8.8.8.8 with 1403 bytes of data:
Reply from 8.8.8.8: bytes=1403 time<1ms TTL=64

Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms 

Once you find the MTU, you can set it as per below:

set subinterface “Local Area Connection” mtu=1360 store=persistent

Hacking: Using a Macbook and Nikto to Scan your Local Network

Nikto is becoming one of my favourite tools. I like it because of its wide ranging use cases and its simplicity. So whats an example use case for Nikto? When I am bored right now and so I am going to hunt around my local network and see what I can find…

# First install Nikto
brew install nikto
# Now get my ipaddress range
ifconfig
# Copy my ipaddress into to ipcalculator to get my cidr block
eth0      Link encap:Ethernet  HWaddr 00:0B:CD:1C:18:5A
          inet addr:172.16.25.126  Bcast:172.16.25.63  Mask:255.255.255.224
          inet6 addr: fe80::20b:cdff:fe1c:185a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2341604 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2217673 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:293460932 (279.8 MiB)  TX bytes:1042006549 (993.7 MiB)
          Interrupt:185 Memory:f7fe0000-f7ff0000
# Get my Cidr range (brew install ipcalc)
ipcalc 172.16.25.126
cp363412:~ $ ipcalc 172.16.25.126
Address:   172.16.25.126        10101100.00010000.00011001. 01111110
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   172.16.25.0/24       10101100.00010000.00011001. 00000000
HostMin:   172.16.25.1          10101100.00010000.00011001. 00000001
HostMax:   172.16.25.254        10101100.00010000.00011001. 11111110
Broadcast: 172.16.25.255        10101100.00010000.00011001. 11111111
Hosts/Net: 254                   Class B, Private Internet
# Our NW range is "Network:   172.16.25.0/24"

Now lets pop across to nmap to get a list of active hosts in my network

# Now we run a quick nmap scan for ports 80 and 443 across the entire range looking for any hosts that respond and dump the results into a grepable file
nmap -p 80,433 172.16.25.0/24 -oG webhosts.txt
# View the list of hosts
cat webhosts.txt
$ cat webhosts.txt
# Nmap 7.93 scan initiated Wed Jan 25 20:17:42 2023 as: nmap -p 80,433 -oG webhosts.txt 172.16.25.0/26
Host: 172.16.25.0 ()	Status: Up
Host: 172.16.25.0 ()	Ports: 80/open/tcp//http///, 433/open/tcp//nnsp///
Host: 172.16.25.1 ()	Status: Up
Host: 172.16.25.1 ()	Ports: 80/open/tcp//http///, 433/open/tcp//nnsp///
Host: 172.16.25.2 ()	Status: Up
Host: 172.16.25.2 ()	Ports: 80/open/tcp//http///, 433/open/tcp//nnsp///
Host: 172.16.25.3 ()	Status: Up
Host: 172.16.25.3 ()	Ports: 80/open/tcp//http///, 433/open/tcp//nnsp///
Host: 172.16.25.4 ()	Status: Up
Host: 172.16.25.4 ()	Ports: 80/open/tcp//http///, 433/open/tcp//nnsp///
Host: 172.16.25.5 ()	Status: Up

Next we want to grep this webhost file and send all the hosts that responded to the port probe of to Nikto for scanning. To do this we can use some linux magic. First we cat to read the output stored in our webhosts.txt document. Next we use awk. This is a Linux tool that will help search for the patterns. In the command below we are asking it to look for “Up” (meaning the host is up). Then we tell it to print $2, which means to print out the second word in the line that we found the word “Up” on, i.e. to print the IP address. Finally, we send that data to a new file called niktoscan.txt.

cat webhosts.txt | awk '/Up$/{print $2}' | cat >> niktoscan.txt
cat niktoscan.txt
$ cat niktoscan.txt
172.16.25.0
172.16.25.1
172.16.25.2
172.16.25.3
172.16.25.4
172.16.25.5
172.16.25.6
172.16.25.7
172.16.25.8
172.16.25.9
172.16.25.10
...

Now let nikto do its stuff:

nikto -h niktoscan.txt -ssl >> niktoresults.txt
# Lets check what came back
cat niktoresults.txt

Macbook: Exploring DNS using DIG (Domain Information Groper)

DIG is an awesome command line utility to explore DNS. Below is a quick guide to get you started.

Query Specific Name Server

By default, if no name server is specified, dig will use the servers listed in /etc/resolv.conf file. To view the default server use:

% cat /etc/resolv.conf
#
# macOS Notice
#
# This file is not consulted for DNS hostname resolution, address
# resolution, or the DNS query routing mechanism used by most
# processes on this system.
#
# To view the DNS configuration used by this system, use:
#   scutil --dns
#
# SEE ALSO
#   dns-sd(1), scutil(8)
#
# This file is automatically generated.
#
nameserver 100.64.0.1

You can override the name server against which the query will be executed, use the @ (at) symbol followed by the name server IP address or hostname.

For example, to query the Google name server (8.8.8.8) for information about andrewbaker.ninja you would use:

% dig andrewbaker.ninja @8.8.8.8

; <<>> DiG 9.10.6 <<>> andrewbaker.ninja @8.8.8.8
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33993
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;andrewbaker.ninja.		IN	A

;; ANSWER SECTION:
andrewbaker.ninja.	300	IN	A	13.244.140.33

;; Query time: 1099 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu Nov 17 11:26:55 SAST 2022
;; MSG SIZE  rcvd: 62

Get a Short Answer

To get a short answer to your query, use the +short option:

% dig andrewbaker.ninja +short
13.244.140.33

Query a Record Type

Dig allows you to perform any valid DNS query by appending the record type to the end of the query. In the following section, we will show you examples of how to search for the most common records, such as A (the IP address), CNAME (canonical name), TXT (text record), MX (mail exchanger), and NS (name servers).

Querying A records

To get a list of all the address(es) for a domain name, use the a option:

% dig +nocmd andrewbaker.ninja a +noall +answer
andrewbaker.ninja.	156	IN	A	13.244.140.33

Querying CNAME records

To find the alias domain name use the cname option:

dig +nocmd mail.google.com cname +noall +answer
mail.google.com.	553482	IN	CNAME	googlemail.l.google.com.

Querying TXT records

Use the txt option to retrieve all the TXT records for a specific domain:

% dig +nocmd google.com txt +noall +answer
google.com.		3600	IN	TXT	"globalsign-smime-dv=CDYX+XFHUw2wml6/Gb8+59BsH31KzUr6c1l2BPvqKX8="
google.com.		3600	IN	TXT	"MS=E4A68B9AB2BB9670BCE15412F62916164C0B20BB"
google.com.		3600	IN	TXT	"docusign=1b0a6754-49b1-4db5-8540-d2c12664b289"
google.com.		3600	IN	TXT	"onetrust-domain-verification=de01ed21f2fa4d8781cbc3ffb89cf4ef"
google.com.		3600	IN	TXT	"apple-domain-verification=30afIBcvSuDV2PLX"
google.com.		3600	IN	TXT	"google-site-verification=TV9-DBe4R80X4v0M4U_bd_J9cpOJM0nikft0jAgjmsQ"
google.com.		3600	IN	TXT	"facebook-domain-verification=22rm551cu4k0ab0bxsw536tlds4h95"
google.com.		3600	IN	TXT	"webexdomainverification.8YX6G=6e6922db-e3e6-4a36-904e-a805c28087fa"
google.com.		3600	IN	TXT	"docusign=05958488-4752-4ef2-95eb-aa7ba8a3bd0e"
google.com.		3600	IN	TXT	"v=spf1 include:_spf.google.com ~all"
google.com.		3600	IN	TXT	"atlassian-domain-verification=5YjTmWmjI92ewqkx2oXmBaD60Td9zWon9r6eakvHX6B77zzkFQto8PQ9QsKnbf4I"
google.com.		3600	IN	TXT	"google-site-verification=wD8N7i1JTNTkezJ49swvWW48f8_9xveREV4oB-0Hf5o"

Querying MX records

To get a list of all the mail servers for a specific domain using the mx option:

% dig +nocmd google.com mx +noall +answer
google.com.		48	IN	MX	10 smtp.google.com.

Querying All Records

Use the any option to get a list of all DNS records for a specific domain:

dig +nocmd andrewbaker.ninja any +noall +answer
andrewbaker.ninja.	300	IN	A	13.244.140.33
andrewbaker.ninja.	21600	IN	NS	ns-1254.awsdns-28.org.
andrewbaker.ninja.	21600	IN	NS	ns-1514.awsdns-61.org.
andrewbaker.ninja.	21600	IN	NS	ns-1728.awsdns-24.co.uk.
andrewbaker.ninja.	21600	IN	NS	ns-1875.awsdns-42.co.uk.
andrewbaker.ninja.	21600	IN	NS	ns-491.awsdns-61.com.
andrewbaker.ninja.	21600	IN	NS	ns-496.awsdns-62.com.
andrewbaker.ninja.	21600	IN	NS	ns-533.awsdns-02.net.
andrewbaker.ninja.	21600	IN	NS	ns-931.awsdns-52.net.
andrewbaker.ninja.	900	IN	SOA	ns-1363.awsdns-42.org. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

Tracing DNS Resolution

DNS query resolution follows a simple recursive process outlined below:

  1. You as the DNS client (or stub resolver) query your recursive resolver for www.example.com.
  2. Your recursive resolver queries the root name server for www.example.com.
  3. The root name server refers your recursive resolver to the .com Top-Level Domain (TLD) authoritative server.
  4. Your recursive resolver queries the .com TLD authoritative server for www.example.com.
  5. The .com TLD authoritative server refers your recursive server to the authoritative servers for example.com.
  6. Your recursive resolver queries the authoritative servers for www.example.com, and receives 1.2.3.4 as the answer.
  7. Your recursive resolver caches the answer for the duration of the time to live (TTL) specified on the record, and returns it to you.

Below is an example trace:

% dig +trace andrewbaker.ninja

; <<>> DiG 9.10.6 <<>> +trace andrewbaker.ninja
;; global options: +cmd
.			62163	IN	NS	g.root-servers.net.
.			62163	IN	NS	j.root-servers.net.
.			62163	IN	NS	e.root-servers.net.
.			62163	IN	NS	l.root-servers.net.
.			62163	IN	NS	d.root-servers.net.
.			62163	IN	NS	a.root-servers.net.
.			62163	IN	NS	b.root-servers.net.
.			62163	IN	NS	i.root-servers.net.
.			62163	IN	NS	m.root-servers.net.
.			62163	IN	NS	h.root-servers.net.
.			62163	IN	NS	c.root-servers.net.
.			62163	IN	NS	k.root-servers.net.
.			62163	IN	NS	f.root-servers.net.
.			62163	IN	RRSIG	NS 8 0 518400 20221129170000 20221116160000 18733 . MbE0OpdxRbInDK0olZm8n585L4oPq3q8iVbn/O0S7bfelS9wauhHQnnY Ifuj3D6Owp6R7H2Om6utfeB2kjrocJG9ZQPy0UQhWvgcFp9I4KnWRr1L H/yvmSM2EejR7kQHp4OBrb55RBsX4tojvr1UU+fWRuy988prwBVBdKj6 EElNwteQCosJHxVzqP0z6UpP9i5rUkRNGOD7OvdwF8ynBV93F4FpOI9r yuKzz0hdE3YAQJztOY84VuLkXM2DPs51LR6ftibxswUwoeUg04QUS7py gzn1z9en99oUgX+Lic6fLKc5Q0LpeZGhW0qBCY2CB9KEaRth+ZCD6WEU tjOBCw==
;; Received 525 bytes from 8.8.8.8#53(8.8.8.8) in 249 ms

ninja.			172800	IN	NS	v0n2.nic.ninja.
ninja.			172800	IN	NS	v2n1.nic.ninja.
ninja.			172800	IN	NS	v0n0.nic.ninja.
ninja.			172800	IN	NS	v0n1.nic.ninja.
ninja.			172800	IN	NS	v2n0.nic.ninja.
ninja.			172800	IN	NS	v0n3.nic.ninja.
ninja.			86400	IN	DS	46082 8 2 C8F816A7A575BDB2F997F682AAB2653BA2CB5EDDB69B036A30742A33 BEFAF141
ninja.			86400	IN	RRSIG	DS 8 1 86400 20221130050000 20221117040000 18733 . xoEolCAm4d+f6LxulPa/lnCwKuwWLPI8LzlgmOVvMNL7z8J/21FqTWBu 4tZT8KZTciAvcTcRo3TDAg0Qr48QvJI30ld4yYa81HGHpVKVuTSoNCtn FnxvCuZmqDY+aFM/zn9jSTdCcT8EhwLJrsHq/zj/iasymLZ/UvanJo8j X/PRSorGfWJjUeDSSjCOpOITjRLqzHeBcY9+Qpf7O5fDguqtkhzc/8pS qKmjUh2B+yJA4QgDSaoxdv9LRQIvdSL1Iwq9eAXnl9azJy3GbVIUVZCw bA8ZsFYhw9sQbk39ZDi3K4pS717uymh4RBlk4r/5EuqdKBpWFYdOW4ZC EGDBcg==
;; Received 763 bytes from 198.41.0.4#53(a.root-servers.net) in 285 ms

andrewbaker.ninja.	3600	IN	NS	ns-1363.awsdns-42.org.
andrewbaker.ninja.	3600	IN	NS	ns-1745.awsdns-26.co.uk.
andrewbaker.ninja.	3600	IN	NS	ns-462.awsdns-57.com.
andrewbaker.ninja.	3600	IN	NS	ns-983.awsdns-58.net.
4vnuq0b3phnjevus6h4meuj446b44iqj.ninja.	3600 IN	NSEC3 1 1 10 332539EE7F95C32A 4VVVNRI7K3EH48N753IKM6TUI5G921J7  NS SOA RRSIG DNSKEY NSEC3PARAM
4vnuq0b3phnjevus6h4meuj446b44iqj.ninja.	3600 IN	RRSIG NSEC3 8 2 3600 20221208121502 20221117111502 22878 ninja. RIuQHRcUrHqMNg1lab6s/oRNmflV4e+8r2553miiZdlGqCl8Q05+e1f5 /AY0enkAaG4DvoXCAlwroL7B7iYgivgrmPXklPTEahnzdeZV76UWimRs 2WjKLI9DSUsSl5yPZBDloqYBxhQlHwY7RPcKxELX2wO7ld8Dk+cSpQIu CQQ=
dg8umbqgrvdemk76n4dtbddckfghtloo.ninja.	3600 IN	NSEC3 1 1 10 332539EE7F95C32A DGG261SH46I7K27S1MPEID8CER0BFH07  NS DS RRSIG
dg8umbqgrvdemk76n4dtbddckfghtloo.ninja.	3600 IN	RRSIG NSEC3 8 2 3600 20221130155636 20221109145636 22878 ninja. b3g1om7FYmaboSk49ZuQC/wiyuZ0zQXOs/HbfrtDP1wUGyvXMAG1ofik //wSTVEvi7bufrbKUCSkBrxiBweSkRIKokaB/5j90Izpb9znaN0MWmOQ gywML7TQ3etOWb9s8L/oUmiBUUUtBtPGAy/e4hsbuYKQt+awJZVhR4G/ GBM=
;; Received 691 bytes from 65.22.21.4#53(v0n1.nic.ninja) in 892 ms

andrewbaker.ninja.	300	IN	A	13.244.140.33
andrewbaker.ninja.	172800	IN	NS	ns-1254.awsdns-28.org.
andrewbaker.ninja.	172800	IN	NS	ns-1514.awsdns-61.org.
andrewbaker.ninja.	172800	IN	NS	ns-1728.awsdns-24.co.uk.
andrewbaker.ninja.	172800	IN	NS	ns-1875.awsdns-42.co.uk.
andrewbaker.ninja.	172800	IN	NS	ns-491.awsdns-61.com.
andrewbaker.ninja.	172800	IN	NS	ns-496.awsdns-62.com.
andrewbaker.ninja.	172800	IN	NS	ns-533.awsdns-02.net.
andrewbaker.ninja.	172800	IN	NS	ns-931.awsdns-52.net.
;; Received 328 bytes from 205.251.195.215#53(ns-983.awsdns-58.net) in 53 ms

As you can see above, the first set of results are the NS (nameservers) for the root domain (.), followed by the NS for .ninja, then finally the NS for andrewbaker.ninja (hosted in AWS).

Macbook: Show which applications have ports open and to what IP address

Below is a dump of examples of doing pretty much the same thing differently. I mostly use netstat and lsof, coupled with some bash scripts.

You can argue that this is overkill, but below is a simple bash function that you can paste into terminal and call it whenever you want to see which application/process IDs have open ports:

macnst (){ netstat -Watnlv | grep LISTEN | awk '{"ps -o comm= -p " $9 | getline procname;colred="\033[01;31m";colclr="\033[0m"; print colred "proto: " colclr $1 colred " | addr.port: " colclr $4 colred " | pid: " colclr $9 colred " | name: " colclr procname; }' | column -t -s "|" }

## Example: 
proto: tcp46 addr.port: *.8770 pid: 1459 name: /usr/libexec/sharingd proto: tcp4 addr.port: 127.0.0.1.9000 pid: 787 name: /Applications/Zscaler/Zscaler.app/Contents/PlugIns/ZscalerTunnel proto: tcp4 addr.port: 100.64.0.1.9000 pid: 787 name: /Applications/Zscaler/Zscaler.app/Contents/PlugIns/ZscalerTunnel proto: tcp6 addr.port: *.56365 pid: 1080 name: /usr/libexec/rapportd proto: tcp4 addr.port: *.56365 pid: 1080 name: /usr/libexec/rapportd proto: tcp4 addr.port: 100.64.0.1.9010 pid: 787 name: /usr/libexec/rapportd proto: tcp6 addr.port: ::1.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::1%lo0.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::244b:70ff:fe0a:ffaa%anpi2.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::244b:70ff:fe0a:ffa8%anpi0.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::244b:70ff:fe0a:ffa9%anpi1.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::109d:a6ff:fed1:244c%awdl0.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp6 addr.port: fe80::109d:a6ff:fed1:244c%llw0.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq proto: tcp4 addr.port: 127.0.0.1.53 pid: 784 name: /opt/homebrew/opt/dnsmasq/sbin/dnsmasq

Below is an alternative to the above using netstat:

$ netstat -ap tcp | grep ESTABLISHED 
tcp4 0 0 192.168.123.227.57278 52.114.104.174.https ESTABLISHED tcp4 0 0 100.64.0.1.cslistener 52.114.104.174.57277 ESTABLISHED tcp4 0 0 100.64.0.1.57277 52.114.104.174.https ESTABLISHED tcp4 0 0 100.64.0.1.57275 13.89.179.10.https ESTABLISHED tcp4 0 0 100.64.0.1.57262 40.79.141.153.https ESTABLISHED tcp4 0 0 100.64.0.1.57258 52.97.201.226.https ESTABLISHED tcp4 0 0 192.168.123.227.57250 52.113.194.132.https ESTABLISHED tcp4 0 0 100.64.0.1.cslistener 52.113.194.132.57249 ESTABLISHED tcp4 0 0 100.64.0.1.57249 52.113.194.132.https ESTABLISHED tcp4 0 0 100.64.0.1.57240 193.0.160.129.https ESTABLISHED tcp4 0 0 100.64.0.1.57239 jnb02s11-in-f6.1.https ESTABLISHED tcp4 0 0 100.64.0.1.57238 944.bm-nginx-loa.https ESTABLISHED tcp4 0 0 100.64.0.1.57237 159.248.227.35.b.https ESTABLISHED tcp4 0 0 100.64.0.1.57236 ip98.ip-51-75-86.https ESTABLISHED tcp4 0 0 100.64.0.1.57235 185.94.180.126.https ESTABLISHED tcp4 0 0 100.64.0.1.57234 a-0001.a-msedge..https ESTABLISHED tcp4 0 0 100.64.0.1.57233 a-0001.a-msedge..https ESTABLISHED

If you want to find the processes listening on a specific port, use the following:

sudo lsof -nP -i4TCP:9000 | grep LISTEN
ZscalerTu 787 root   49u  IPv4 0xfa4872984902c87f      0t0  TCP 100.64.0.1:9000 (LISTEN)
ZscalerTu 787 root   64u  IPv4 0xfa48729849d9138f      0t0  TCP 127.0.0.1:9000 (LISTEN)
## Then you can kill the process using: sudo kill -9 <PID>
sudo kill 787

Following the theme of creating bash scripts for the sake of it, below is a simple listening script:

listening() {
    if [ $# -eq 0 ]; then
        sudo lsof -iTCP -sTCP:LISTEN -n -P
    elif [ $# -eq 1 ]; then
        sudo lsof -iTCP -sTCP:LISTEN -n -P | grep -i --color $1
    else
        echo "Usage: listening [pattern]"
    fi
}

## Example
% listening 9000
ZscalerTu 38629     root   13u  IPv4 0xfa48729848a2f4bf      0t0  TCP 100.64.0.1:9000 (LISTEN)
ZscalerTu 38629     root   14u  IPv4 0xfa48729849edffcf      0t0  TCP 127.0.0.1:9000 (LISTEN)

Next up, using lsof to view TCP sessions (-i4 : IPV4; -n : prevent conversion to host name):

sudo lsof -i4 -n -P | grep TCP | grep ESTABLISHED
identitys  1205       cp363412   37u  IPv6 0xfa487293786896c7      0t0    TCP [fe80:16::c79c:1b6f:a073:9eca]:1024->[fe80:16::e858:3f4a:1724:69c1]:1024 (ESTABLISHED)
identitys  1205       cp363412   38u  IPv6 0xfa4872937868cb47      0t0    TCP [fe80:16::c79c:1b6f:a073:9eca]:1025->[fe80:16::e858:3f4a:1724:69c1]:1026 (ESTABLISHED)
identitys  1205       cp363412   39u  IPv6 0xfa4872937868cb47      0t0    TCP [fe80:16::c79c:1b6f:a073:9eca]:1025->[fe80:16::e858:3f4a:1724:69c1]:1026 (ESTABLISHED)
Google     2149       cp363412   20u  IPv4 0xfa48729848bee74f      0t0    TCP 100.64.0.1:58416->172.217.170.10:443 (ESTABLISHED)
Google     2149       cp363412   26u  IPv4 0xfa48729848bfb25f      0t0    TCP 100.64.0.1:58600->216.58.223.132:443 (ESTABLISHED)
Google     2149       cp363412   30u  IPv4 0xfa48729848aa938f      0t0    TCP 100.64.0.1:58388->151.101.3.9:443 (ESTABLISHED)
Google     2149       cp363412   33u  IPv4 0xfa4872984590512f      0t0    TCP 100.64.0.1:58601->216.58.223.132:443 (ESTABLISHED)
Google     2149       cp363412   35u  IPv4 0xfa487298489734bf      0t0    TCP 100.64.0.1:58602->172.217.170.170:443 (ESTABLISHED)
Google     2149       cp363412   36u  IPv4 0xfa487298489cf25f      0t0    TCP 100.64.0.1:58470->13.244.140.33:443 (ESTABLISHED)
Google     2149       cp363412   41u  IPv4 0xfa487298458fde9f      0t0    TCP 100.64.0.1:58231->172.217.170.10:443 (ESTABLISHED)
Google     2149       cp363412   42u  IPv4 0xfa48729848b25e9f      0t0    TCP 100.64.0.1:58451->142.250.27.188:443 (ESTABLISHED)
Google     2149       cp363412   45u  IPv4 0xfa48729848a8fd6f      0t0    TCP 100.64.0.1:58452->142.250.27.188:443 (ESTABLISHED)
Google     2149       cp363412   47u  IPv4 0xfa48729848b19c3f      0t0    TCP 100.64.0.1:58473->172.217.170.99:443 (ESTABLISHED)
Google     2149       cp363412   57u  IPv4 0xfa48729849ee1c3f      0t0    TCP 100.64.0.1:57722->192.0.78.23:443 (ESTABLISHED)
Google     2149       cp363412   60u  IPv4 0xfa4872984908325f      0t0    TCP 100.64.0.1:57973->198.252.206.25:443 (ESTABLISHED)
WhatsApp   2225       cp363412   21u  IPv4 0xfa4872984590674f      0t0    TCP 192.168.123.227:58288->102.132.100.60:443 (ESTABLISHED)
UPMServic  2333           root  248u  IPv4 0xfa48729848b1325f      0t0    TCP 192.168.123.227:56364->147.161.204.128:443 (ESTABLISHED)
Microsoft 25966       cp363412   44u  IPv4 0xfa48729849d9dc3f      0t0    TCP 100.64.0.1:58615->52.112.238.155:443 (ESTABLISHED)
Microsoft 37667       cp363412   20u  IPv4 0xfa48729849ef9e9f      0t0    TCP 100.64.0.1:58566->52.113.194.132:443 (ESTABLISHED)
Microsoft 37667       cp363412   22u  IPv4 0xfa4872984901887f      0t0    TCP 100.64.0.1:58378->52.112.120.216:443 (ESTABLISHED)
Microsoft 37667       cp363412   23u  IPv4 0xfa487298489e34bf      0t0    TCP 100.64.0.1:58536->20.42.65.84:443 (ESTABLISHED)
Microsoft 37667       cp363412   24u  IPv4 0xfa4872984591487f      0t0    TCP 100.64.0.1:58613->52.112.238.155:443 (ESTABLISHED)
Microsoft 37667       cp363412   27u  IPv4 0xfa48729848bed12f      0t0    TCP 100.64.0.1:58549->52.114.228.1:443 (ESTABLISHED)
Microsoft 37678       cp363412   51u  IPv4 0xfa487298489ddc3f      0t0    TCP 192.168.123.227:56382->52.112.120.204:443 (ESTABLISHED)
Microsoft 37678       cp363412   59u  IPv4 0xfa4872984902912f      0t0    TCP 100.64.0.1:56147->52.114.224.23:443 (ESTABLISHED)
ZscalerTu 38629           root    8u  IPv4 0xfa48729848bde74f      0t0    TCP 100.64.0.1:9000->52.114.228.1:58549 (ESTABLISHED)
ZscalerTu 38629           root    9u  IPv4 0xfa48729849061c3f      0t0    TCP 192.168.123.227:58330->13.244.131.129:443 (ESTABLISHED)
ZscalerTu 38629           root   10u  IPv4 0xfa48729848a9de9f      0t0    TCP 192.168.123.227:58550->52.114.228.1:443 (ESTABLISHED)
ZscalerTu 38629           root   16u  IPv4 0xfa48729849eea74f      0t0    TCP 100.64.0.1:9000->52.113.194.132:58566 (ESTABLISHED)
ZscalerTu 38629           root   17u  IPv4 0xfa4872984904f25f      0t0    TCP 192.168.123.227:58567->52.113.194.132:443 (ESTABLISHED)
ZscalerTu 38629           root   20u  IPv4 0xfa487298489e725f      0t0    TCP 100.64.0.1:9000->52.112.238.155:58613 (ESTABLISHED)

For analysing what is listening to a port lsof also gives you a short history of the state of the connection:

sudo lsof -i tcp:9000
COMMAND     PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ZscalerTu 53971 root   13u  IPv4 0xfa4872984902f4bf      0t0  TCP 100.64.0.1:cslistener (LISTEN)
ZscalerTu 53971 root   14u  IPv4 0xfa48729848bdf25f      0t0  TCP localhost:cslistener (LISTEN)
ZscalerTu 53971 root   18u  IPv4 0xfa487298489f112f      0t0  TCP 100.64.0.1:cslistener->147.161.204.128:63038 (ESTABLISHED)
ZscalerTu 53971 root   19u  IPv4 0xfa487298489f69af      0t0  TCP 100.64.0.1:cslistener->147.161.204.128:63036 (CLOSE_WAIT)
ZscalerTu 53971 root   24u  IPv4 0xfa4872984897674f      0t0  TCP 100.64.0.1:cslistener->a23-2-112-62.deploy.static.akamaitechnologies.com:63040 (ESTABLISHED)
ZscalerTu 53971 root   28u  IPv4 0xfa487298489d138f      0t0  TCP localhost:63045->localhost:cslistener (CLOSE_WAIT)
ZscalerTu 53971 root   29u  IPv4 0xfa4872984900912f      0t0  TCP localhost:cslistener->localhost:63045 (FIN_WAIT_2)

Above you can see port 9000 (the zscaler port); after I have restarted zscaler. It shows the state transitions of the port.