Wednesday, 22 December 2021

Kubectl Sheetcheat

 Pods

List all pods in namespace <default>

or

or

kubectl get pods

kubectl get pod

View a pod in watch mode

View all pods in watch mode

List sroted pods

List pods using a different output

Examples:

JSON output

or

or

Wide output:

Custom columns:

or

or

kubectl get po

kubectl get pod <pod> --watch

kubectl get pods -A --watch

kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

kubectl get pods -o <json|yaml|wide|custom-columns=...|custom-columnsfile=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>

kubectl get pods -o json

kubectl get pods -ojson

kubectl get pods -o=json

kubectl get pods -o wide

kubectl get pods -o custom-columns='DATA:spec.containers[*].image'

kubectl get pods -o custom-columns='DATA:spec.containers[*].volumeMounts'

kubectl get pods -o custom-columns='DATA:metadata.*'

Output format Description

-o=custom-columns=

<spec>

Print a table using a comma separated list of custom columns

-o=custom-columns-file=

<filename>

Print a table using the custom columns template in the

<filename> file

-o=json Output a JSON formatted API object

-o=jsonpath=<template> Print the fields defined in a jsonpath expression

-o=jsonpath-file=

<filename>

Print the fields defined by the jsonpath expression in the

<filename> file

-o=name Print only the resource name and nothing else

-o=wide

Output in the plain-text format with any additional

information, and for pods, the node name is included

-o=yaml Output a YAML formatted API object

Formatting output

To output details to your terminal window in a specific format, add the -o (or --output ) flag to a

supported kubectl command (source: K8s docs)

List all pods in a namespace

or

or

List all pods in all namespaces

or

Create from an image

kubectl get pods -n <namespace>

kubectl -n <namespace> get pods

kubectl --namespace <namespace> get pods

kubectl get pods --all-namespaces

kubectl get pods -A

kubectl run <pod> --generator=run-pod/v1 --image=<image>

In the following cheatsheet, we will be using images such as nginx or busybox.

Example:

Run pod in an interactive shell mode

Run a command after creating a pod

Executing a command in a running pod

Or pass stdin to the container in TTY mode:

Example:

Create a pod: dry run mode (without really creating it)

Patch a pod

Example:

Another example:

Create from a YAML file

kubectl run nginx --generator=run-pod/v1 --image=nginx

kubectl run busybox --generator=run-pod/v1 --image=busybox

kubectl run -i --tty nginx --image=nginx -- sh

kubectl run busybox --image=busybox -- sleep 100000

kubectl exec <pod> -- <command>

kubectl exec -it <pod> -- <command>

kubectl exec -it nginx -- ls -lrth /app/

kubectl run <pod> --generator=run-pod/v1 --image=nginx --dry-run

kubectl patch pod <pod> -p '<patch>'

kubectl patch pod <pod> -p '{"spec":{"containers":[{"name":"kubernetes-servehostname","image":"new image"}]}}'

kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path":

"/spec/containers/0/image", "value":"new image"}]'

Export YAML from the dry run mode

Create from STDIN

Create multiple resources from STDIN

Create in a namespace

Create in a namespace from a file

kubectl create -f pod.yaml

kubectl run nginx --generator=run-pod/v1 --image=nginx --dry-run -o yaml

cat <<EOF | kubectl create -f -

apiVersion: v1

kind: Pod

metadata:

name: nginx-pod

spec:

containers:

- name: nginx

image: nginx:latest

EOF

cat <<EOF | kubectl create -f -

apiVersion: v1

kind: Pod

metadata:

name: nginx-pod

spec:

containers:

- name: nginx

image: nginx:latest

---

apiVersion: v1

kind: Pod

metadata:

name: busybox

spec:

containers:

- name: busybox

image: busybox

args:

- sleep

- "100"

kubectl run nginx --generator=run-pod/v1 --image=nginx -n <namespace>

kubectl create -f pod.yaml -n <namespace>

Delete pods

or

If you create the pod from a file, you can also use:

To force deletion:

Get pod logs

or

Sometimes a pod contains more than 1 container. You need to filter the output to get logs for a

specific container(s)

To follow the logs output (tail -f):

If you need to output the logs for all pods with a label

Example:

You can also view logs in a multi container case with labels:

Or view all cotainers logs with a given label:

List all container id of init container of all pods

kubectl delete pod/<pod>

kubectl delete pod <pod>

kubectl delete -f pod.yaml

kubectl delete pod <pod> --grace-period=0 --force

kubectl logs <pod>

kubectl logs <pod> -c <container>

kubectl logs -f <pod>

kubectl logs -l <label_name>=<label_value>

kubectl logs -l env=prod

kubectl logs -l <label_name>=<label_value> -c <container>

kubectl logs -f -l <label_name>=<label_value> --all-containers

Show metrics for a given pod

Show metrics for a given pod and all its containers

Deployments

Create a deployment

or

Create a deployment with a predefined replica number

Create a deployment with a predefined replica number and

opening a port

Example:

Note: The default generator for kubectl run is --generator=deployment/apps.v1 .

Note: --generator=deployment/apps.v1 is deprecated and will be removed in future versions.

Use kubectl run --generator=run-pod/v1 or kubectl create instead.

Create a deployment with a predefined replica number,

opening a port and exposing it

Get a deployment

kubectl get pods --all-namespaces -o jsonpath='{range

.items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -

f3

kubectl top pod <pod>

kubectl top pod <pod> --containers

kubectl run <deployment> --image=<image>

kubectl create deployment <deployment> --image=<image>

kubectl run <deployment> --image=<image> --replicas=<number>

kubectl run <deployment> --image=<image> --replicas=<replicas> --port=<port>

kubectl run nginx --image=nginx --replicas=2 --port=80

kubectl run nginx --image=nginx --replicas=2 --port=80 --expose

Watch a deployment

or

Or using a shorter version:

Or even the longer one:

List all deployments

Same as listing pods, you have multiple options from namespace to output formatters:

Update the image

Rolling update "nginx" containers of "nginx" deployment, updating the image:

Rolling update "api" containers of "backend" deployment, updating the image:

Scale a deployment

Note: You can use a shorter version:

kubectl get deploy <deployment>

kubectl get deployment <deployment> --watch

kubectl get deployment <deployment> -w

kubectl get deploy <deployment> -w

kubectl get deployments.apps <deployment> --watch

kubectl get deploy -n <namespace>

kubectl get deploy --all-namespaces

kubectl get deploy -A

kubectl get deploy -oyaml

kubectl get deploy -owide

kubectl set image deployment/nginx nginx=nginx:1.9.1

kubectl set image deployment/backend api=image:v2

kubectl scale --replicas=5 deployment/<deployment>

kubectl scale --replicas=5 deploy/<deployment>

Dry run and YAML output

Create a deployment from a file

Edit a deployment

Rollback deployment

After editing your deployment, you had an error, a solution can be rolling back to the old

deployment status:

Get rollout history

You can check the rollout history:

Example:

gives you:

Roll back to a previous revision

Using the information from the rollout history, we can get back our deployment to a given

revision:

Example:

kubectl run nginx --image=nginx --replicas=2 --port=80 --dry-run -o yaml

kubectl apply -f deployment.yaml

kubectl edit deployment/<deployment>

kubectl rollout undo deployment <deployment>

kubectl rollout history deployment <deployment>

kubectl rollout history deployment <deployment>

kubectl rollout history deployment nginx

REVISION CHANGE-CAUSE

2 kubectl set image deployment/nginx nginx=nginx:1.9.1 --record=true

3 <none>

kubectl rollout undo deployment <deployment> --to-revision=<revision>

kubectl rollout undo deployment nginx --to-revision=2

Execute deployment rollout operations

Port Forwarding

Choosing localhost port

Example:

Forward to localhost 8090 from pod 6379:

Listening on the same port

Example: Listen on ports 8000 and 9000 on localhost, forwarded from the same ports in the pod

(8000 and 9000)

Listen on a random port locally

Example:

Listen on port on localhost + another IP

Example:

Listen on a forwarded port on all addresses

kubectl rollout status deployment <deployment>

kubectl rollout pause deployment <deployment>

kubectl rollout resume deployment <deployment>

kubectl port-forward deployment <deployment> <locahost-port>:<deployment-port>

kubectl port-forward pod <pod> <locahost-port>:<pod-port>

kubectl port-forward redis 8090:6379

kubectl port-forward pod <pod> <port>

kubectl port-forward pod nginx 8000 9000

kubectl port-forward pod <pod> :<pod-port>

kubectl port-forward pod nginx :80

kubectl port-forward --address localhost,<IP.IP.IP.IP> pod <pod> <locahostport>:<pod-port>

kubectl port-forward --address localhost,10.10.10.1 pod redis 8090:6379

kubectl port-forward --address 0.0.0.0 pod <pod> <hosts-port>:<pod-port>

Services

Create a service

Examples:

You can use svc instead of service .

Delete service(s)

or

Describe a service

Nodes

Get node

Get a specific node

Show node metrics

Get external IPs of cluster nodes

kubectl create service <clusterip|externalname|loadbalancer|nodeport> <service>

[flags] [options]>

kubectl create service clusterip myclusterip --tcp=5678:8080

kubectl create service loadbalancer myloadbalancer --tcp=80

kubectl delete service myclusterip

kubectl delete service myloadbalancer

kubectl delete svc myclusterip

kubectl delete svc myloadbalancer

kubectl delete service myclusterip myloadbalancer

kubectl describe service <service>

kubectl get nodes

kubectl get nodes <node>

kubectl top node <node>

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?

(@.type=="ExternalIP")].address}'

Describe commands with verbose output

Check which nodes are ready

Mark a node as unschedulable

Drain a node for maintenance

Mark a node as schedulable

Namespaces

List namespaces

or

List or describe a namespace

Create namespace

or

or

kubectl describe nodes <node>

JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}

{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" |

grep "Ready=True"

kubectl cordon <node>

kubectl drain <node>

kubectl uncordon <node>

kubectl get namespaces

kubectl get ns

kubectl get namespace <namespace>

kubectl describe namespace <namespace>

kubectl create namespace <namespace>

kubectl create -f namespace.yaml

Delete namespace

or

Service accounts

List service accounts

or

Get a service account

or

or

or

Create a service account

Delete a service account

cat <<EOF | kubectl create -f -

apiVersion: v1

kind: Namespace

metadata:

name: mynamespace

EOF

kubectl delete namespace <namespace>

kubectl delete -f namespace.yaml

kubectl get serviceaccounts

kubectl get sa

kubectl get serviceaccount <serviceaccount>

kubectl get serviceaccounts <serviceaccount>

kubectl get sa <serviceaccount>

kubectl get sa/<serviceaccount>

kubectl create serviceaccount <serviceaccount>

or

Describe a service account

Events

List events

List sorted events

Example: Sorted by timestamp

List formatted events

Example:

Documentation

Get the documentation for pod manifests

Get the documentation for service manifests

Describing resources

kubectl delete serviceaccount <serviceaccount>

kubectl delete -f myserviceaccount.yaml

kubectl describe serviceaccount <serviceaccount>

kubectl get events -A

kubectl get events --sort-by=<JSONPath>

kubectl get events --sort-by=.metadata.creationTimestamp

kubectl get events -o <json|yaml|wide|custom-columns=...|custom-columnsfile=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>

kubectl get events -owide

kubectl explain pod

kubectl explain service

kubectl describe <resource> <reosurce_name>

Example:

or

Other possible resources you can use with describe :

kubectl describe pod busybox

kubectl describe nodes minikube

apiservices.apiregistration.k8s.io

certificatesigningrequests.certificates.k8s.io

clusterrolebindings.rbac.authorization.k8s.io

clusterroles.rbac.authorization.k8s.io

componentstatuses

configmaps

controllerrevisions.apps

cronjobs.batch

csidrivers.storage.k8s.io

csinodes.storage.k8s.io

customresourcedefinitions.apiextensions.k8s.io

daemonsets.apps

daemonsets.extensions

deployments.apps

deployments.extensions

endpoints

events

events.events.k8s.io

horizontalpodautoscalers.autoscaling

ingresses.extensions

ingresses.networking.k8s.io

jobs.batch

leases.coordination.k8s.io

limitranges

mutatingwebhookconfigurations.admissionregistration.k8s.io

namespaces

networkpolicies.extensions

networkpolicies.networking.k8s.io

nodes

persistentvolumeclaims

persistentvolumes

poddisruptionbudgets.policy

pods

podsecuritypolicies.extensions

podsecuritypolicies.policy

podtemplates

priorityclasses.scheduling.k8s.io

replicasets.apps

replicasets.extensions

replicationcontrollers

resourcequotas

rolebindings.rbac.authorization.k8s.io

roles.rbac.authorization.k8s.io

runtimeclasses.node.k8s.io

secrets

serviceaccounts

Editing resources

Edit a service

Edit a service with your favorite text editor

Note: Change service by any editable resource type like pods.

Deleting Resources

Delete a resource using the type and name specified in

<file>

Delete pods and services with same names

Delete pods and services with a custom label

Delete all pods and services in a namespace

Delete all resources in a namespace

All get commands

services

statefulsets.apps

storageclasses.storage.k8s.io

validatingwebhookconfigurations.admissionregistration.k8s.io

volumeattachments.storage.k8s.io

kubectl edit service <service>

KUBE_EDITOR="vim" edit service <service>

kubectl delete -f <file>

kubectl delete pod,service <name1> <name2>

kubectl delete pods,services -l <label-name>=<label-value>

kubectl -n <namespace> delete pods,services --all

kubectl delte <namespace>

Resource type Abbreviations

componentstatuses cs

configmaps cm

daemonsets ds

deployments deploy

endpoints ep

event ev

horizontalpodautoscalers hpa

ingresses ing

limitranges limits

namespaces ns

nodes no

persistentvolumeclaims pvc

persistentvolumes pv

pods po

podsecuritypolicies psp

replicasets rs

replicationcontrollers rc

resourcequotas quota

serviceaccount sa

services svc

Abbreviations / Short forms of resource types

Verbose Kubectl

kubectl get all

kubectl get pods

kubectl get replicasets

kubectl get services

kubectl get nodes

kubectl get namespaces

kubectl get configmaps

kubectl get endpoints

kubectl run nginx --image=nginx --v=5

Verbosity Description

--v=0 Generally useful for this to always be visible to a cluster operator.

--v=1 A reasonable default log level if you don't want verbosity.

--v=2

Useful steady state information about the service and important log

messages that may correlate to significant changes in the system. This is the

recommended default log level for most systems.

--v=3 Extended information about changes.

--v=4 Debug level verbosity.

--v=6 Display requested resources.

--v=7 Display HTTP request headers.

--v=8 Display HTTP request contents.

--v=9 Display HTTP request contents without truncation of contents.

(Table source: K8s docs)

Cluster

Display addresses of the master and services

Dump cluster state to STDOUT

Dump cluster state to a file

Compares the current cluster state against the state that

the cluster would be in if the manifest was applied

List all images running in a cluster

Kubectl context

Show merged kubeconfig settings

kubectl cluster-info

kubectl cluster-info dump

kubectl cluster-info dump --output-directory=</file/path>

kubectl diff -f ./my-manifest.yaml

kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'

Use multiple kubeconfig

Get a list of users

Display the first user

Get the password for the "admin" user

Display the current context

Display list of contexts

Set the default context to <cluster>

Sets a user entry in kubeconfig

Sets a user with a client key

Sets a user with basic auth

Sets a user with client certificate

kubectl config view

KUBECONFIG=~/.kube/config1:~/.kube/config2:~/.kube/config3

kubectl config view -o jsonpath='{.users[*].name}'

kubectl config view -o jsonpath='{.users[].name}'

kubectl config view -o jsonpath='{.users[?(@.name == "admin")].user.password}'

kubectl config current-context

kubectl config get-contexts

kubectl config use-context <cluster>

kubectl config set-credentials <username> [options]

kubectl config set-credentials <user> --client-key=~/.kube/admin.key

kubectl config set-credentials --username=<username> --password=<password>

kubectl config set-credentials <user> --client-certificate=<path/to/cert> --

embed-certs=true

Set a context utilizing a specific config file

Set a context utilizing a specific username and namespace.

Alias

Create an alias on *nix

Create an alias on Windows

Kubectl imperative (create) vs declarative (apply)

Create

You tell your cluster what you want to create, replace or delete, not how you want you it to look

like.

Apply

You tell your cluster how you want it to look like.

The creation, deletion and modification of objects is done via a single command. The declarative

approach is a statement of the desired end result.

If the deployment is deleted in <deployment-filename> , it will also be deleted from the cluster.


Sunday, 30 August 2020

How to Stop FireWall on Centos 7 and Red Hat7


[1]It's possible to show Service Status of FireWall like follows. (enabled by default)
[root@kida ~]# 
systemctl status firewalld

● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: active (running) since Thu 2015-03-31 19:36:27 JST; 2s ago
 Main PID: 1308 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─1308 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
.....
.....

 

[2]
If you use FireWall service, it needs to modify settings of it because incoming requests for services are mostly not allowed by default. 
[3]If FireWall service does not need for you because of some reasons like that some FireWall Machines are running in your Local Netowrk or others, it's possbile to stop and disable it like follows.

# stop service

[root@kida ~]# 
systemctl stop firewalld

# disable service

[root@kida ~]# 
systemctl disable firewalld

rm '/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service'
rm '/etc/systemd/system/basic.target.wants/firewalld.service'

SELinux
[4]It's possible to show Status of SELinux (Security-Enhanced Linux) like follows. (enabled by default)

[root@kida ~]# 
getenforce

Enforcing     
# SELinux is enabled
[5]If SELinux function does not need for you because of some reasons like that your server is running only in Local safety Network or others, it's possbile to disable it like follows.

[root@kida ~]# 
vi /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled   # change to disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

# restart to apply new setting

[root@kida ~]# 

Friday, 14 August 2020

Exploring the Snort Intrusion Detection System





Modern enterprises need IT for smooth and efficient functioning. The almost universal use of the Internet has spawned many bad actors and malicious agents. There are hackers out there waiting to break into computer systems for espionage, theft of industrial secrets and for information. Intrusion detection systems help address this problem.

An intrusion detection system (IDS) is a network security technology built to detect vulnerabilities and has the ability to block threats. According to Brian Rexroad, vice president of security platforms for AT&T, “The overall purpose of an IDS is to inform IT personnel that a network intrusion may be taking place. Alerts will generally include information about the source address of the intrusion, the target’s/victim’s address, and the type of attack that is suspected.”

What is involved in network intrusion?

To detect and to prevent hackers and attackers from penetrating a system, we need to have a basic understanding of the attacks that can be possibly performed on it.

Scanning attack: This involves sending packets/information to a network in an attempt to gather data about the network, e.g., blind SQL injection.


Figure 1: Verifying the installation

Figure 2: Sniffer output1

Buffer overflow attack: This is an attempt to penetrate sections of the memory in the devices connected to the network, replacing the normal data with malicious code. This can cause the entire system to crash and create chaos, which helps in hiding an attack on another point in the system.

Protocol-specific attack: This targets specific protocols such as ICMP, TCP and ARP.

  • ICMP stands for Internet Control Message Protocol; ping floods attack can be performed, which overwhelm the device with ICMP echo-request packets. There are also smurf attacks and port scanning.
  • TCP stands for Transmission Control Protocol, which is vulnerable to TCP syn attacks in which a port stays open as the ACK message is never received; the open port can be used to send malicious packets.
  • ARP stands for Address Resolution Protocol, in which the attack takes place by ARP Poisoning where false ARP messages are sent to link the attacker’s MAC address with the IP address of a legit device.

Malware: This includes worms, trojans, viruses and bots. Basically, as the word itself says, this software is designed to damage or disrupt the system.

Traffic flooding: This is also known as DDoS attack.

Types of intrusion detection systems

Network-based intrusion detection systems (NIDS) are deployed at strategic points throughout the network, basically to keep a watch over places where the traffic is most likely to be vulnerable. They are relatively easy to secure and thus, an intruder may not realise that an attack is being detected. NIDS analyses a large volume of network traffic, which means it has low specificity. So, there are chances of it missing an attack or not detecting something in encrypted traffic.

A host intrusion detection system (HIDS) is established on all devices in the network. It works as a second line of defence against malicious data if NIDS fails to detect something. It looks at the entire system’s file set and compares it to previous logs of the file set.

Approaches to detecting intrusion

Signature based IDS:  This focuses on searching for ‘signature’ patterns, or an identity of an intrusion, or a specific intrusion event. Signature-based IDS is only as good as how up-to-date its database is at that given moment. But it is very easy to bypass it by making tiny changes to the code. As the database increases, the processing load increases and so the system takes time to analyse each connection and verify it.

Anomaly based IDS: This uses machine learning to detect intrusions by comparing trustworthy models with new models. As a result, strange looking anomalies are flagged. However, the problem is that even a legitimate model can be flagged, depending on the network’s response. Anomaly-based IDS is good for determining when someone is probing a network prior to an attack taking place. These probes create signals in the network that the anomaly based IDS will pick up.

Challenges of managing an IDS

  1. False positives are a major problem with an IDS. This refers to the generation of alerts even when there is no real problem or any issue.
  2. Staffing means that an IDS cannot work as a one-for-all system — it changes from enterprise to enterprise.
  3. There are chances that an IDS may miss a legitimate risk.

Snort

Snort is a free and open source network intrusion prevention and detection system. It uses a rule-based language combining signature, protocol and anomaly inspection methods to detect any kind of malicious activity. Snort is also capable of performing real-time traffic analysis and packet logging on IP networks. It was developed in 1999 but it went on to become so popular that it was purchased by Cisco in 2014.

Anyone, a novice or an experienced person, who wants to head out into the world of security must be familiar with Kali Linux. This is a Debian based distribution, which has been specifically made keeping in mind network analysts and penetration testers. A Linux distribution is a bundle which contains the Linux kernel, a collection of core utilities and applications, and some default settings. Kali comes pre-installed with a palette of tools to choose from, making it the Swiss knife for hackers. We will now use Snort on Kali.


Figure 3: Sniffer output2

Installing Snort

Let us install Snort from the repositories. You can first directly try running it from the terminal, by using the following command — if your machine is properly configured with the repositories, then Snort will be installed.

kali > sudo apt-get install snort

Now let us suppose that your machine does not have the required repositories listed, so we may edit them by using the following command:

 kali > sudo mousepad /etc/apt/sources.list

Once done, install Snort. You may verify the installation by running the following command:

kali > sudo snort -V

As we can see in Figure 1, Snort responds with its currently installed version number.


Figure 4: Conf file sections

Basic configuration of Snort

Like all Linux commands and applications, Snort also has the help of the command line, which can be invoked by using the following code:

kali > sudo snort –-help

I have highlighted a few switches from the Help section of Snort:

  • -c gives us the location of the Snort rules and tells it to use its rules. They are the signature against which the new packets are verified.
  • -d tells Snort to show the application layer of data.
  • e displays the Data Link layer of information, which contains the MAC address of the system.
  • i allows the user to designate the interface we want to use. By default, Snort uses eth0.
  • k allows the users to define how they want to store the details of the data capture performed by Snort.
  • -v is like in most of the programs — verbose, providing all the information.

Figure 5: Conf variable

Starting Snort

Let’s get to know some of the basic switches of Snort, by first running iy. What makes Snort fabulous is that it can be run as a sniffer, packet logger, or even as a NIDS. In this article, we will look at Snort as a packet sniffer and NIDS.

To run Snort in packet dump mode, use the following command:

kali > sudo snort -vde

The output we get is pretty self-explanatory (Figures 2). For using Snort as a NIDS, we need to instruct Snort to include the configuration file and rules. Generally, we can find the conf file at /etc/snort/snort.conf and that file will point to Snort rules. We need to give the -c switch and then the location.

kali > sudo snort -vde -c /etc/snort/snort.conf

We can also customise the rules to suit our needs.


Figure 6: Conf output

Snort — rules and configuration

Like all general Linux applications, Snort is configured via a conf file, which can be opened as a simple text file. Edit this text file, restart the application and we have a new working configuration.

Before going any further, let’s take a brief look into the syntax of Snort rules.

  • Snort rules must be contained in a single line or we can use the multi-line character \. For example:
log tcp !x.x.x/xx     OR 
 
log tcp !x.x.x/xx any -> xxx \
 
(msg: “some command”)
  •  All rules should contain a rule header (which identifies the actions) and rule options (which identify the rule’s alert messages).
  • The rules must describe situations like a violation of the security policy of the company, or correctly detect the exploitable vulnerabilities.

There are three kinds of rules in Snort:

  1. Alert rules: This generates alerts using the alert method.
  2. Log rules: Upon generation of any alert, it logs that specific alert.
  3. Pass rules: Ignores the packet if deemed malicious and drops it.

Now we can move on to the configuration file, which can be opened using the following command:

kali > mousepad /etc/snort/snort.conf

In the Snort configuration file, we may see nine sections, as shown in Figure 4.

For the most basic configuration, we will address only Sections 1, 6 and 7 as seen in Figure 5, 6, 7.


Figure 7: Conf rules

Setting variables

In the screenshot in Figure 5, we can see the highlighted line ‘ipvar HOME_NET’. This variable denotes the network is protected. ‘HOME_NET’ is the variable name to which the IP address is assigned. This can be a single IP address, a list of IP addresses, or a subnet in CIDR notation, or even can be left as any.

Checking the output

Using Ctrl+F, we then move on to output plugins (Figure 6). By default, Snort sends the output in log format. But if we want, we can comment out that line (unified2) and uncomment the bottom line (log_tcpdump), enabling the output in tcpdump format, which is saved in the /var/log/snort directory.

Disable rules

Depending on your enterprise, we may need to change the rules that Snort relies upon, and customise them in Section 7, as shown in Figure 7.

To not let Snort use a given set, simply comment out the include part.

After making any change, simply save the file and test the configuration using the -T switch.

kali > sudo snort -T -c  /etc/snort/snort.conf

The output can be seen in Figure 8.


Figure 8: Conf validation

So, is that all?

Well, we have not even scratched the surface of Snort. For the geeks out there, think of this as just the beginning to a Cristopher Nolan or a Quentin Tarantino movie — it still has many layers to go through. We can write our own rules, create our own NIDS for the enterprise and even sniff packets.