Archive for the ‘ How tos ’ Category

Every visit to a site such as google.com starts with resolving the domain name or FQDN to an IP address. And this resolution is done by a dns service. The domain name to IP address(A record in dns terminology) mapping is cached by both dns servers and client as most domain names do not change IPs that often.

Sometimes though you might know that the A record or IP address of a domain has changed and yet your local cache is holding the old IP. Before clearing the cache, you can view the contents of the dns cache by sending a USR1 signal to systemd-resolved

sudo killall -USR1 systemd-resolved

This will dump the contents of dns cache and name servers to systemd log, which you can view with journalctl command –

sudo journalctl -u systemd-resolved

As the bottom of the log, you should see the CACHE entries –


Oct 30 22:53:04 hidmo systemd-resolved[23811]: CACHE:
Oct 30 22:53:04 hidmo systemd-resolved[23811]:         csi.gstatic.com IN A 209.85.202.120
Oct 30 22:53:04 hidmo systemd-resolved[23811]:         csi.gstatic.com IN A 209.85.202.94
Oct 30 22:53:04 hidmo systemd-resolved[23811]:         connectivity-check.ubuntu.com IN A 35.222.85.5
Oct 30 22:53:04 hidmo systemd-resolved[23811]:         connectivity-check.ubuntu.com IN A 35.224.99.156

....

TLTR; systemd-resolve –flush-caches

systemd-resolve is a CLI tool for resolving domain names, IPv4 and IPv6 addresses, DNS records and services.

It also provides dns resolution statistics, settings and ability to flush cache. Before flushing cache, check the cache size and hit/miss statistics. Additional information such as transactions count is also reported.

$ sudo systemd-resolve --statistics
DNSSEC supported by current servers: no

Transactions                
Current Transactions: 0     
  Total Transactions: 105240
                            
Cache                       
  Current Cache Size: 15     
          Cache Hits: 50425 
        Cache Misses: 66235 
                            
DNSSEC Verdicts             
              Secure: 0     
            Insecure: 0     
               Bogus: 0     
       Indeterminate: 0     

As you can see above, the cache size is 15. In order to clear or flush the dns cache, run below command –

systemd-resolve --flush-caches

Running systemd-resolve --statistics should show a current cache size of 0.

Get HTTP headers

Linux – view HTTP header response using curl, httpie, GET, nmap


Most users are interested in the content they receive when they visit a web site. There is an extra information web clients and servers exchange – HTTP headers. HTTP headers let the client and the server pass additional information with an HTTP request or response.

So how do we view the HTTP response from a remove web server? There are several tools for these

1. Curl : use ‘-I’ flag

   -I, --head
          (HTTP FTP FILE) Fetch the headers only! HTTP-servers feature the command HEAD which this uses to get nothing but  the  header  of  a
          document. When used on an FTP or FILE file, curl displays the file size and last modification time only.
$ curl -I google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sun, 02 Aug 2020 13:48:01 GMT
Expires: Tue, 01 Sep 2020 13:48:01 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN

2. httpie : Use ‘-h h’ flag

--print WHAT, -p WHAT
       String specifying what the output should contain:
      'H' request headers
      'B' request body
      'h' response headers
      'b' response body
$ http www.google.com --print h
 HTTP/1.1 200 OK
 Cache-Control: private, max-age=0
 Content-Encoding: gzip
 Content-Length: 5256
 Content-Type: text/html; charset=ISO-8859-1
 Date: Sun, 02 Aug 2020 13:50:50 GMT
 Expires: -1
 P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
 Server: gws
 Set-Cookie: 1P_JAR=2020-08-02-13; expires=Tue, 01-Sep-2020 13:50:50 GMT; path=/; domain=.google.com; Secure
 Set-Cookie: NID=TRUNCATED; expires=Mon, 01-Feb-2021 13:50:50 GMT; path=/; domain=.google.com; HttpOnly
 X-Frame-Options: SAMEORIGIN
 X-XSS-Protection: 0

3. GET – lwp-request : ‘Ed’ flag

In many Linux distros, GET is an alias for lwp-request. It gives way more detailed information in the response header, including SSL parameters.

  -E  Print response status chain with full response headers.

  -d  Do not print the content of the response.
$ GET linux.com -Ed
GET http://linux.com
User-Agent: lwp-request/6.31 libwww-perl/6.31

301 Moved Permanently
Cache-Control: public, max-age=86400
Connection: close
Date: Sun, 02 Aug 2020 13:56:35 GMT
Via: 1.1 varnish
Accept-Ranges: bytes
Age: 43368
Location: https://linux.com/
Server: nginx
Vary: Cookie, Cookie
Content-Length: 162
Content-Type: text/html
Client-Date: Sun, 02 Aug 2020 13:56:35 GMT
Client-Peer: REDACTED
Client-Response-Num: 1
Title: 301 Moved Permanently
X-Cache: HIT, HIT
X-Cache-Hits: 1, 1
X-Pantheon-Styx-Hostname: styx-fe3-a-745747b57-x7rhq
X-Served-By: cache-mdw17324-MDW, cache-fty21379-FTY
X-Styx-Req-Id: 01697a62-d463-11ea-a64f-aabcb0e0cfdc
X-Timer: S1596376596.936127,VS0,VE1

GET https://linux.com/
User-Agent: lwp-request/6.31 libwww-perl/6.31

301 Moved Permanently
Cache-Control: public, max-age=86400
Connection: close
Date: Sun, 02 Aug 2020 13:56:36 GMT
Via: 1.1 varnish
Accept-Ranges: bytes
Age: 43368
Location: https://www.linux.com/
Server: nginx
Vary: Cookie, Cookie
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Client-Date: Sun, 02 Aug 2020 13:56:36 GMT
Client-Peer: REDACTED
Client-Response-Num: 1
Client-SSL-Cert-Issuer: /C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
Client-SSL-Cert-Subject: /CN=linux.com
Client-SSL-Cipher: ECDHE-RSA-AES128-GCM-SHA256
Client-SSL-Socket-Class: IO::Socket::SSL
Strict-Transport-Security: max-age=300
X-Cache: HIT, HIT
X-Cache-Hits: 1, 1
X-Pantheon-Styx-Hostname: styx-fe3-b-64d9844f89-tc7zl
X-Served-By: cache-mdw17340-MDW, cache-pdk17820-PDK
X-Styx-Req-Id: 01bf3709-d463-11ea-baef-1ede833e594e
X-Timer: S1596376596.065153,VS0,VE1

GET https://www.linux.com/
User-Agent: lwp-request/6.31 libwww-perl/6.31

200 OK
Cache-Control: public, max-age=1800
Connection: close
Date: Sun, 02 Aug 2020 13:56:36 GMT
Via: 1.1 varnish
Accept-Ranges: bytes
Age: 1659
Server: nginx
Vary: Accept-Encoding, Cookie, Cookie
Content-Length: 126289
Content-Type: text/html; charset=UTF-8
Client-Date: Sun, 02 Aug 2020 13:56:36 GMT
Client-Peer: REDACTED
Client-Response-Num: 1
Client-SSL-Cert-Issuer: /C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
Client-SSL-Cert-Subject: /CN=linux.com
Client-SSL-Cipher: ECDHE-RSA-AES128-GCM-SHA256
Client-SSL-Socket-Class: IO::Socket::SSL
Link: <https://www.linux.com/wp-json/>; rel="https://api.w.org/"
Link: <https://www.linux.com/>; rel=shortlink
Strict-Transport-Security: max-age=300
Title: Linux.com - News For Open Source Professionals
X-Cache: HIT, MISS
X-Cache-Hits: 5, 0
X-Meta-Charset: UTF-8
X-Meta-Description: Linux.com is the go-to resource for open source professionals to learn about the latest in Linux and open source technology, careers, best practices, and industry trends. Get news, information, and tutorials to help advance your next project or career – or just to simply stay informed.
X-Meta-Generator: WordPress 5.4.2
X-Meta-Twitter-Card: summary_large_image
X-Meta-Twitter-Description: Linux.com is the go-to resource for open source professionals to learn about the latest in Linux and open source technology, careers, best practices, and industry trends. Get news, information, and tutorials to help advance your next project or career – or just to simply stay informed.
X-Meta-Twitter-Image: https://www.linux.com/wp-content/uploads/2019/08/ldc_social.jpg
X-Meta-Twitter-Title: Linux.com - News For Open Source Professionals
X-Meta-Viewport: width=device-width, initial-scale=1.0
X-Pantheon-Styx-Hostname: styx-fe3-a-745747b57-mfmk7
X-Served-By: cache-mdw17340-MDW, cache-pdk17866-PDK
X-Styx-Req-Id: 1df2da1b-d4c4-11ea-84e9-925461917092
X-Timer: S1596376596.261327,VS0,VE18

Nmap : –script=http-headers flag

Nmap is a network discovery tool but it can be used for scanning http headers as well. The port number has to be specified, otherwise nmap will scan several common ports.

$ nmap --script=http-headers google.com -p 80

Starting Nmap 7.60 ( https://nmap.org ) at 2020-08-02 10:00 PDT
Nmap scan report for google.com (172.217.15.110)
Host is up (0.026s latency).
rDNS record for 172.217.15.110: iad30s21-in-f14.1e100.net

PORT   STATE SERVICE
80/tcp open  http
| http-headers: 
|   Location: http://www.google.com/
|   Content-Type: text/html; charset=UTF-8
|   Date: Sun, 02 Aug 2020 14:00:10 GMT
|   Expires: Tue, 01 Sep 2020 14:00:10 GMT
|   Cache-Control: public, max-age=2592000
|   Server: gws
|   Content-Length: 219
|   X-XSS-Protection: 0
|   X-Frame-Options: SAMEORIGIN
|   Connection: close
|   
|_  (Request type: GET)

Nmap done: 1 IP address (1 host up) scanned in 0.69 seconds



$ nmap --script=http-headers google.com -p 443

Starting Nmap 7.60 ( https://nmap.org ) at 2020-08-02 10:00 PDT
Nmap scan report for google.com (172.217.15.110)
Host is up (0.027s latency).
rDNS record for 172.217.15.110: iad30s21-in-f14.1e100.net

PORT    STATE SERVICE
443/tcp open  https
| http-headers: 
|   Location: https://www.google.com/
|   Content-Type: text/html; charset=UTF-8
|   Date: Sun, 02 Aug 2020 14:00:13 GMT
|   Expires: Tue, 01 Sep 2020 14:00:13 GMT
|   Cache-Control: public, max-age=2592000
|   Server: gws
|   Content-Length: 220
|   X-XSS-Protection: 0
|   X-Frame-Options: SAMEORIGIN
|   Alt-Svc: h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
|   Connection: close
|   
|_  (Request type: GET)

Nmap done: 1 IP address (1 host up) scanned in 0.74 seconds


Deleting files with rm and getting
rm: invalid option –Try ‘rm –help’ for more information.

In Linux, trying to delete a file its name starts with dash(‘-‘) or double dashes(‘–‘) will fails, as dash or ‘-‘ is interpreted as an option by the rm and most linux commands.

Here are two files with filenames starting with ‘-‘ and ‘–‘ and the typical rm command deletion attempt fails with an error –

$ ls -1
-tempfile1
--tempfile2

$ rm -tempfile1
rm: invalid option -- 't'
Try 'rm ./-tempfile1' to remove the file '-tempfile1'.
Try 'rm --help' for more information.

$ rm --tempfile2
rm: unrecognized option '--tempfile2'
Try 'rm ./--tempfile2' to remove the file '--tempfile2'.
Try 'rm --help' for more information.

There are several ways of addressing this – you can precede the file name with ./ OR pass double dash after rm to end all option processing.

$ ls
-tempfile1  --tempfile2

$ rm -- -tempfile1

$ mv -- --tempfile2 tempfile2

$ rm ./-tempfile1


References –

http://www.gnu.org/software/coreutils/faq/coreutils-faq.html#How-do-I-remove-files-that-start-with-a-dash_003f

Terraform – show logging


Enable debugging terraform


By default, a terraform plan or apply run only shows the resources to create, update or delete. It doesn’t give much detail on the activity terraform is doing behind the scene. All the debug logging would especially be helpful when you encounter an error.

Here is a typical terraform plan output, in this case it is a code for creating a firewall rule in Google cloud platform(GCP) –

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
...
------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

# google_compute_firewall.glb-allow will be created
  + resource "google_compute_firewall" "glb-allow" {
      + creation_timestamp = (known after apply)
      + description        = "Allow GLB proxies"
      + destination_ranges = (known after apply)
      + direction          = (known after apply)
      + id                 = (known after apply)
      + name               = "allow-glb-access"
      + network            = "internal"
      + priority           = 1000
      + project            = "my-gcp-project"
      + self_link          = (known after apply)
      + source_ranges      = [
          + "130.211.0.0/22",
          + "35.191.0.0/16",
        ]
      + target_tags        = [
          + "webservers",
        ]

      + allow {
          + ports    = [
              + "80",
              + "443",
              + "8080",
              + "8443",
            ]
          + protocol = "tcp"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Terraform supports an environment variable – TF_LOG – for detailed logging purposes. You can set the logging to different severity levels which includes – TRACE, DEBUG, INFO, WARN, and ERROR

$ TF_LOG=DEBUG terraform plan
2020/03/20 17:03:39 [WARN] Log levels other than TRACE are currently unreliable, and are supported only for backward compatibility.
  Use TF_LOG=TRACE to see Terraform's internal logs.
  ----
2020/03/20 17:03:39 [INFO] Terraform version: 0.12.20  
2020/03/20 17:03:39 [INFO] Go runtime version: go1.12.13
2020/03/20 17:03:39 [INFO] CLI args: []string{"/usr/local/bin/terraform", "plan"}
2020/03/20 17:03:39 [DEBUG] Attempting to open CLI config file: /home/daniel/.terraformrc
2020/03/20 17:03:39 [DEBUG] File doesn't exist, but doesn't need to. Ignoring.
2020/03/20 17:03:39 [INFO] CLI command args: []string{"plan"}
2020/03/20 17:03:39 [DEBUG] checking for provider in "." 
2020/03/20 17:03:39 [DEBUG] checking for provider in "/usr/local/bin"
2020/03/20 17:03:39 [DEBUG] checking for provider in ".terraform/plugins/linux_amd64"
2020/03/20 17:03:39 [DEBUG] found provider "terraform-provider-google_v3.13.0_x5"
....

Terraform also supports saving logs to a file with the TF_LOG_PATH environment variable.

$ TF_LOG=DEBUG TF_LOG_PATH=/tmp/terraform-debug.log terraform plan
...
$ ls -lh /tmp/terraform-debug.log
-rw-r--r-- 1 daniel daniel 15K Mar 20 17:06 /tmp/terraform-debug.log


References

https://www.terraform.io/docs/internals/debugging.html


Creating a text file in Linux


In Unix, everything is a file. In this particular case though we will be demonstrating how to create a text file. Of course, these are some of the many ways of creating a file

touch

Just touch it! – touch command followed by some file name and a file will magically appear.

$ ls linuxfreelancer
ls: cannot access 'linuxfreelancer': No such file or directory

$ touch linuxfreelancer

$ $ ls -l linuxfreelancer 
-rw-rw-r-- 1 daniel daniel 0 Feb  8 16:53 linuxfreelancer

vi

vi or any text editor. In fact, any process which writes to a file.

$ vi linuxfreelancer

Save with “:wq” in vi to save the file.

cat

Write multi-line text with “Here Document” syntax in bash.

$ cat <<EOF>linuxfreelancer
my blog is at https://www.linuxfreelancer.com
EOF

$ cat linuxfreelancer 
my blog is at https://www.linuxfreelancer.com
$

echo

The echo command with some redirection –

$ echo 'My blog is at https://linuxfreelancer.com' > linuxfreelancer

$ cat linuxfreelancer 
My blog is at https://linuxfreelancer.com

Redirection

You can redirect the output of any command to a new file

$ ps > ps.output
$ cat ps.output 
  PID TTY          TIME CMD
 2703 pts/0    00:00:00 bash
 3290 pts/0    00:00:00 ps

tee

$ tee linuxfreelancer
Writing for my blog linuxfreelancer.com
Writing for my blog linuxfreelancer.com
...Crl+X

$ cat linuxfreelancer 
Writing for my blog linuxfreelancer.com

$ 

Why does the tee command repeat what I typed? that is what it does – it reads from standard input and write to standard output and file at the same time.