> For the complete documentation index, see [llms.txt](https://phiph.gitbook.io/foundation-1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://phiph.gitbook.io/foundation-1/network/f5.md). Agents can also search and read this documentation through its [MCP server](https://phiph.gitbook.io/foundation-1/~gitbook/mcp).

# F5

## Architechture

* Big-IP
* Hardware
* VE
* TMOS
  * TMM
    * LTM

**86 Arch**

* TMM interfaces > Broadcom switch > CPUs and RAM
* mgmt interface > small switch > CPUs and RAM
* Linux > TMM processes on every even Core (traffic goes directly to TMM process without routing table...etc)
* On uneven cores control plane is launched
* If TMM takes many memory it does not give it back
* After uneven distribution of resources only reboot will help

**Config files**

On the BIG-IP device, the configuration is actually stored in three different states

* Text configuration - /config/bigip.conf, /config/bigip\_base.conf
* The running configuration – The running configuration contains all of the configuration that are stored in the text configuration and the changes that have been made since the last save. This configuration is running in the memory of the BIG-IP system, which means that if you have unsaved configuration on the BIG-IP system, if the system is shut down without being saved, you will lose all of the unsaved settings
* The binary configuration – Starting with BIG-IP 9.4.0 when the BIG-IP system first boots up, the mcpd process builds a binary configuration which creates the following two files: /var/db/mcpd.bin, /var/db/mcpd.info
* /config/bigip.license

**Modules**

* ASM - Application Security Manager - IPS, WAF, DDoS
* APM - Access Policy Manager - authentication, authorization, SSL VPNs
* AFM - Advanced Firewall Manager - L3/L4 attacks, DDos attacks
* AAM - Application Acceleration Manager - optimization LTM - It’s a full proxy between users and application servers, creating a layer of abstraction to secure, optimize, and load balance application traffic
* GTM - global application delivery with DNS, acts as DNS server, replies with IP address based on location and other options
* WOM - WAN optimization manager

Master Control Program (MCP)

* Maintains the primary data plane configuration database used by BIG-IP.
* The tmsh utility connects to MCP to read and write configuration properties.
* MCP feeds configuration to TMM, APMD, and other BIG-IP processes.
* Reads configuration from the stardard BIG-IP configuration files

Rest Database

* The REST database holds BIG-IP and iAppLX data, including the SSLO configuration, current device status, peer status, CMI information, ASM/Advanced WAF information, and more.
* Apache Lucene Database running in restjavad
* Data is organized into REST blocks
* Each single block is one iAppLX Application
  * SSLO uses multiple blocks to store a typical deployment
  * In contrast, Access Guided Configuration and other iapps use a single block to store a typical deployment
* SSLO relays SSLO config change operations through BlockCollectionWorker
* SSLO relays MCP config change operations through MCP
* Database files in /var/config/rest/storage

Acceleration Technologies

* TCP Express
* HTTP Compression uses highly configurable GZIP compression capabilities to reduce the size of bytes transferred over a line.
* Fast Cache offloads servers and saves server CPU by caching priority applications and extending control for hosting multiple applications on a shared system. Cache storage of compressed data generates even faster content delivery and improves BIG-IP scalability.
* OneConnect increases server capacity up to 60% by offloading TCP connections from servers.
* Content Spooling reduces the TCP overhead on servers to increase server capacity up to 15% by lowering the amount TCP segmentation that must be performed on servers.

HTSplit

* K23505424: Overview of the HTSplit feature
* K15003: Data and control plane tasks use separate logical cores when the BIG-IP system CPU uses Intel Hyper-Threading Technology
* Only even logical cores process traffic
* When they are more than 80% load, odd logical cores limit control plane to 20% and leave 80% to data plane
* Idle enforcer process is responsible for switch
* When this happens, in /var/log/kern.log we can see

```
info kernel: ltm driver: Idle enforcer starting - tid: <pid> cpu: 1/1
info kernel: ltm driver: Idle enforcer exiting - tid: <pid> cpu: 1
```

determine if your platform supports the HTSplit feature:

```
tmsh show sys tmm-info | grep Sys::TMM
Sys::TMM: 0.0
Sys::TMM: 0.2
Sys::TMM: 0.4
Sys::TMM: 0.6
```

Disable this feature

```
tmsh modify sys db scheduler.splitplanes.ltm value false
reboot
```

Show if feature is enabled

```
tmsh list sys db scheduler.splitplanes.ltm
```

UCS archive

Contains:

* Configuration files
* License
* User accounts with passwords
* DNS zone files
* Zone Runner configuration
* SSL certs + private keys

Files included in archive are defined in /usr/libdata/configsync/cs.dat If we restore from UCS arcive, hostnames should match. If another hardware is used, do not install license

```
tmsh load sys ucs no-license
```

* when you install UCS on another hardware platform, consider that you need a master key - <https://support.f5.com/csp/article/K9420>
* no platform check - option to restore UCS archive without platform check, used to move between different appliances
* Create archive: `save sys ucs <filename>`
* Restore archive - `load sys ucs filename`
* `/var/local/ucs/`

Single Configuration File

/var/local/scf

```
tmsh save /sys config file big-ip-1.txt no-passphrase
tmsh load /sys config file
```

**Qkview**

.tar.qkview /var/tmp

Create Qkview without limits: `qkview -s0`

Includes the following:

* 30 days of performance graphs
* 5 Mb of logs
* Configuration objects
* Serial number
* Model number
* List of modules
* Module data
* BIG-IP version

**Core file**

```
/var/core
/shared/core
```

Files are named as daemons in gz format.

4 severity levels:

1. * Site Down - 1 hour
2. * Site at Risk - 2 hours
3. * Performance Degraded - 3-4 hours
4. * General Assistance - 24 hours, next business day

## Initial Installation

* DHCP
* 192.168.1.245
* admin/admin
* root/default
* Mgmt port
* License
* Provision
* Device cert
* Platform properties
* VLANs
* NTP
* DNS
* HA

Change admin password

```
modify auth user admin password <password>
```

Change root/admin passwords

```
modify auth password admin
save sys config
```

Show current DNS servers

```
tmsh list sys dns
```

Add DNS server

```
tmsh modify sys dns name-servers add { 8.8.8.8 }
save sys config
```

Show and verify current NTP servers

```
tmsh list sys ntp
tmsh show /sys service ntpd
ntpq -np
```

Check if there is a time difference between cluster members

```
show /cm device
```

Add NTP server

```
modify sys ntp servers add { 88.147.254.235 }
modify sys ntp timezone Europe/Moscow
save sys config
```

Restart NTP - it will switch cluster!!!

```
bigstart restart ntpd
```

Reset to factory defaults

```
load /sys config default
save /sys config partitions all
reboot

image2disk --format=volumes --nosaveconfig /shared/images/BIGIP-13.0.1-0.0.3.iso
```

## Platform

```
list /cm all-properties | grep -i "chassis-id"
show sys software
show sys hardware
```

## License

* License reactivation - restarts all services, failover
* Show license
*

```
/config/bigip.license
show sys license
```

* secure.f5.com - we can get a report about service contracts and modules based on appliance serial numbers
* Service Check Date is located in the BIG-IP license and is the same as the date the license was last activated or the date the service contract for the device expires, whichever date is earlier. For example, if you have an active service contract that ends on December 31, and you license a device on June 30, the service check date is set to June 30.
* Note: The service check date in the BIG-IP license is updated each time the license is reactivated, if there is an active service contract for this BIG-IP system

```
grep "Service check date" /config/bigip.license
```

* License Check Date is a static date built into the software for BIG-IP and Enterprise Manager systems
* If service check date is earlier than license check date, then we need to reactivate license on device. It will REBOOT all services.
* 27 character string
* Preinstalled on hardware
* After activation the system permanently associates the base registration key to the BIG-IP system's serial number; therefore, you cannot move licenses and base registration keys.
* Production licenses do not expire
* License activation - traffic interruption - it is better to activate in standby mode
* RMA: courier comes twice: first bring new device, then take back the brocken one

Show throughput limit for VE

```
show /sys license detail | grep perf_VE_throughput_Mbps
```

## Upgrade

* During reboot device my not boot again, this should be considered and warn everyone
* 15.x to 16.x upgrade: SSLO deletes all config and creates it back
* Make sure all Active/Standby pairs are in sync. Sync as required
* Verify config files
* tmsh save sys config partitions all
* tmsh load sys config partitions all verify
* Make sure advanced routing config is saved (CLI)
* imish, enable, wr mem
* Collect and save master key (CLI) - bash - f5mku -K
* The master key is a system-specific encryption key that F5 uses to encrypt and decrypt sensitive configuration data |\~
* Can be used for restoring a UCS file to another device |\~
* Statistics → Module Statistics → Local Traffic
* show ip bgp summary
* Загрузка образов на обе ноды
* Бэкап обоих нод
* Проверить состояние iApps > Application Services > Applications LX.
* Проверить состояние SSLO HA
* Проверить, что на обоих нодах все виды траффика работают корректно
* Проверить УРЛ категории
* Установка нового образа на резервной ноде
* Перевести резервную ноду в статус оффлайн
* Перезагрузить резервную ноду
* Кластер уходит в Дисконнектед из-за разных версий
* SSLO HA status red
* Резервная нода включается
* Переводим ее в режим Online
* Переключаем траффик на резервную ноду
* Проверка всех видов траффика через резервную ноду, в случае проблем - откат обратно на основную
* Проверка логов
* Установка нового образа на основной ноде
* Перевод основной ноды в оффлайн режим
* Перезагрузка основной ноды
* Перевод основной ноды в режим Online
* Проверка статуса кластера и SSLO - возможно пересборка кластера и переключение нод + возможны проблемы с SSLO HA
* Перевод траффика на основную ноду
* Проверка всех видов траффика на основной ноде, в случае ошибок откат на резервную
* После обновления могут быть выбиты ручные настройки - проверить и восстановить
* Upgrade: A version that introduces new features, hardware support, and specific performance improvements - The first two numbers of your software version
* Update: A version that introduces product defect and security fixes - The last two numbers of your software version
* Long-Term Stability Release versions have 1 for their minor release number (x.1.x), and they are not available for a period of time after a major release (x.0.x).
* The latest maintenance release of a Long-Term Stability Release version (x.1.latest) can be between x.1.0 and x.1.n.
* When possible, upgrade to a Long-Term Stability Release (x.1.0) for the following reasons:
* The Standard Support phase for the Long-Term Stability Release continues for five years past the initial x.1.0 release
* The Standard Support phase for the Major Release continues for 15 months past the initial x.0.0 release
* Show installed images wit all properties, including verification

```
tmsh list sys software all-properties
```

Show detailed information about soft

```
tmsh show /sys software
```

```
tmsh show /sys software status
---------------------------------------------------
Sys::Software Status
Volume Product Version Build Active Status
---------------------------------------------------
HD1.1 BIG-IP 11.5.2 0.0.141 no  complete
HD1.2 BIG-IP 11.5.3 0.0.163 yes complete
```

Reboot to particular volume

```
tmsh reboot volume MD1.3
```

Install image from tmsh

```
tmsh install sys software image BIGIP-12.0.0.0.0.606.iso volume HD1.5 create-volume
```

To view the complete list of imported software images or hotfixes, use the following syntax:

```
list /sys software <image | hotfix>
```

Delete image

```
delete /sys software image BIG-IP-11.6.1.0.0.317.iso
```

* Secure copy (SCP) the .iso file and corresponding .md5 file from your desktop computer to the /shared/images directory on the BIG-IP system
* Verify the software image file integrity using either the MD5 checksum, SIG, or PEM files
* For information about verifying the software image using the MD5 checksum, refer to K8337: Verifying the MD5 checksum for the downloaded F5 software file.
* For information about verifying the software image using the SIG or PEM files, refer to K24341140: Verifying BIG-IP software images using SIG and PEM files.

## CPU

* K71764661: Understanding BIG-IP CPU usage
* Troubleshooting high CPU utilisation on BIG-IP systems

Show CPU and memory utilization

```
tmsh show sys performance system
```

CPU per plane + per Core

```
Statistics -> Performance Reports -> Performance Reports > System CPU Usage graph > View Detailed Graph
tmsh show sys performance system detail
```

Only when CPUs support Hyper Threading info about planes is displayed, otherwise only per Core Show if CPU supports HT:

```
lscpu
```

Show CPU usage in LInux

```
top and then press 1
```

Show CPU for all Virtual servers

```
tmctl -d /var/tmstat/blade/ virtual_server_cpu_stat -s name,avg_5sec,avg_1min,avg_5min -K avg_5sec -O
name                            avg_5sec    avg_1min    avg_5min    slot_id
Totals                            5705           5089           4780            0
/Common/VS_1            5671           5045           4722            0         <<<<---- top used VS
/Common/VS_9            26               27               30                0
/Common/VS_7            2                 4                 5                  0
/Common/VS_4            2                 4                 7                  0
/Common/VS_6            2                 2                 2                  0
/Common/VS_2            1                 6                 13                0
/Common/VS_3            1                 1                 1                  0
```

Beginning in BIG-IP 11.5.0, data and control plane tasks use separate logical cores on systems with HT Technology CPUs. The new split planes (HTSplit) behavior improves performance by dedicating and prioritizing resources for TMM. Meanwhile, all other processes can still perform control plane tasks (that is, non-TMM tasks), even while TMM is fully utilized. All even cores process data via tmm and they usually highly utilized. And odd cores process control plane and they are always free. BIG-IP starts to use odd cores for tmm only after 80 percent of CPU is used on even cores.

Show if system supports HTSPlit

```
tmsh show sys tmm-info | grep Sys::TMM
```

Disable HTSplit

```
tmsh
modify sys db scheduler.splitplanes.ltm value false
reboot
```

Clustered Multiprocessing (CMP)

The system creates separate Traffic Management Microkernel (TMM) instances for each CPU, sharing the workload among all CPUs.

Show bytes and connections for every tmm process

```
tmsh show sys tmm-traffic
```

Show CPU utilization for every TMM process

```
tmsh show sys tmm-info
```

Show irule CPU usage

```
tmsh show ltm rule x-forwarded-for header: HTTP REQUEST
```

Shows all types of CPU load, total load, amount of CPUs, amount of memory

```
tmsh show sys host-info global

------------------------------------------------------------------------
Sys::Host
------------------------------------------------------------------------
Global
  CPU Count                           36
  Active CPU Count                    18

Memory (bytes)
  Total                           251.8G
  Used                             63.2G

CPU (clock ticks)             Last 5 sec  Last 1 min  Last 5 min   Total
  -                            (avg/sec)   (avg/sec)   (avg/sec)       -
  User                                52          53          52   55.8M
  Niced                                0           0           0       0
  System                               1           1           1    2.0M
  Idle                                42          42          43  190.3M
  Irq                                  0           0           0       0
   Softirq                             0           0           0    1.6K
  Iowait                               0           0           0    2.2K
  Stolen                               0           0           0       0
  Utilization % (last 5 sec)           -           -           -      55
```

Total utilization via SNMP for 1 min

```
snmpwalk -v2c -c public localhost sysGlobalHostCpuUsageRatio
snmpwalk -v2c -c public localhost  .1.3.6.1.4.1.3375.2.1.1.2.20.29.0
```

## Memory

The memory is proportioned out for 'tmm' use and 'other' use. When the BIG-IP was initially provisioned, a portion of memory was marked exclusively for tmm, and the remaining memory is marked for other processes not related to tmm. The tmm memory is managed exclusively by tmm, and other memory is managed by the linux kernel. The standard OID will accurately report the total memory , but will give a false reading on the used memory, often it can be somewhere between 90% and 95% on a relatively quiet device. Therefore you must monitor both parts of the memory independently to get accurate information.

Show all details about the memory

```
tmsh show sys mem
```

This OID is used to get the size of total tmm memory:

```
snmpget -Of -c public -v2c 127.0.0.1  .1.3.6.1.4.1.3375.2.1.1.2.21.28.0
```

This OID is used to get the size of used tmm memory:

```
snmpget -Of -c public -v2c 127.0.0.1  .1.3.6.1.4.1.3375.2.1.1.2.21.29.0
```

Total Other memory

```
snmpget -Of -c public -v2c 127.0.0.1 .1.3.6.1.4.1.3375.2.1.1.2.20.44.0
```

Used Other memory

```
snmpget -Of -c public -v2c 127.0.0.1  .1.3.6.1.4.1.3375.2.1.1.2.20.45.0
```

## Disks

Show HDDs which system can see and how much free space is available

```
tmsh list /sys disk
```

Show how many gigs each folder is

```
tmsh show /sys disk directory
```

Change size for /config directory to 2.1 Gb - for example if there is not enough space

```
tmsh modify /sys disk directory /config new-size 2171984
tmsh save /sys config
reboot
```

Reduce app data size

```
tmsh stop sys service all
lvreduce --resizefs --size -80G /dev/mapper/vg--db--cpmirror-dat.appdata
tmsh start sys service  all
show sys raid array
```

Show resources consumed by each module

```
show /sys provision
```

Diskmonitor script checks periodically free space and sends alerts to /var/log/ltm

In System > Disk management it shows amount of free space in Virtual Group You can also see it using LVM command

```
vgdisplay
```

## Hardware Acceleration

* Статистику по работе функционала SSL Acceleration можно посмотреть в разделе `System > Crypto Offloading > Acceleration Strategy > Statistics`
* Там описано какие шифры и чем обработаны : CPU или специальными чипами
* Или `show sys crypto acceleration-strategy`
* Аппаратное ускорение SSL на нашей платформе и версии ПО поддерживает следующие алгоритмы: DES, 3DES, AES, AES-GCM, AES-GMAC, RSA, DSA, DH, ECDSA, ECDH, MD5, SHA, SHA2
* К сожалению, функции мониторинга загруженности чипов аппаратного ускорения SSL не предусмотрено
* Единственное, что есть это в случае сбоя чипов, система переключится на резервную ноду
* При этом можно во время сбоя отправлять SNMP traps или уведомления по email на основе сообщений в логах:

```
crit tmm[6789]: 01010025:2: Device error: cn0 device requires hard reset; trying soft reset
crit tmm2[6789]: 01010025:2: Device error: cn2 PCI write master retry timeout
tmm[123456]: 01010025:2: Device error: crypto codec cn-crypto-3 queue is stuck.
tmm[123456]: 01010260:2: Hardware Error(Co-Processor): n3-crypto1 request queue stuck
```

* Также существует утилита для диагностики аппаратных ошибок на этих чипах: nitrox\_diag
* Через SNMP можно мониторить следующие параметры deprecated - <https://cdn.f5.com/product/bugtracker/ID1127881.html>:
* Количество клиентских соединений, полностью обработанных аппаратно – sysClientsslStatFullyHwAcceleratedConns
* Количество клиентских соединений, частично обработанных аппаратно – sysClientsslStatPartiallyHwAcceleratedConns
* Количество клиентских соединений, не обработанных аппаратно – sysClientsslStatPartiallyHwAcceleratedConns
* Количество серверных соединений, полностью обработанных аппаратно – sysServersslStatFullyHwAcceleratedConns
* Количество серверных соединений, частично обработанных аппаратно - sysServersslStatPartiallyHwAcceleratedConns
* Количество серверных соединений, не обработанных аппаратно – sysServersslStatNonHwAcceleratedConns
* Также эти параметры можно мониторить не глобально, а для виртуального сервера.
* Мы можем использовать параметр, который отвечает за количество неускоренных соединений, для определения того, что возможности ускорителей исчерпаны и вся нагрузка идет на CPU. Если этот параметр начинает расти, в Заббиксе срабатывает уведомление. Таким образом мы можем косвенно мониторить загрузку SSL ускорителей
* Для этого используется статистика SSL профиля: `show ltm profile client-ssl ssloT_default.app/ssloT_default-cssl-vht`

## Connections

tmsh show sys performance connections show sys connections delete sys connections cs-client-addr

## Throughput

```
tmsh show sys performance throughput
tmsh show sys performance throughput detail

```

* Service: то есть это либо client in + server in либо client out + server out
  * In: The ingress traffic to the system through its interfaces
  * Out: The egress traffic from the system through its interfaces
  * Service: The larger of the two values of combined client and server-side ingress traffic(client in + server in - whole path from client to server) or egress(Server out + client out) traffic, measured within TMM. You can compare this to VE-licensed bandwidth.
* типа сколько коробка держит
* это та самая цифра которая в лицензию считается у виртуалок

In summary:

* Client In (ingress) and Server In (egress) are the same direction through BIG-IP from client to server
* Client Out (egress) and Server Out (ingress) are the same direction through BIG-IP from server to client
* Server IN - traffic entering Server from F5
* Client IN - traffic entering client from F5

## HA

* K13946: Troubleshooting ConfigSync and device service clustering issues
* K95002127: Troubleshooting BIG-IP failover events
* BIG-IP Device Service Clustering: Administration
* A Sync-Failover device group supports a maximum of eight devices
* If you have two BIG-IP devices only, you can create either an active-standby or an active-active configuration. With more than two devices, you can create a configuration in which multiple devices are active and can fail over to one of many, if necessary.
* Parity requirements
  1. In most cases, the units in a redundant configuration should be identically licensed, provisioned, and configured, and should also run on the same hardware platform
  2. The BIG-IP units in a device group must run the same major, minor, and maintenance software version numbers
  3. Beginning in BIG-IP 11.4.0, F5 supports redundant devices in a device group on different hardware or virtual platforms through the load-aware failover feature
  4. License and modules provisioned should be the same
* `Device service clustering`, or DSC® , is an underlying architecture within BIG-IP® Traffic Management Operation System® (TMOS®). DSC provides synchronization and failover of BIG-IP configuration data at user-defined levels of granularity, among multiple BIG-IP devices on a network
* DSC components:
  * Device
  * Device group - devices trust each over and sometimes failover,
  * Traffic group - group of configuration objects(VIP), traffic group float to another device in device group
  * Device trust
  * Folders
* Configuration workflow: `Start > Specify Self IPs for config sync, failover, mirroring > Establish device trust > Create Sync-Failover device group > Sync the config > Create traffic groups (optional) > Enable mirroring on virtual servers (optional) > Sync the config > Finish`
* Configure manually without wizard, First configure configsync interface on both devices, `Device Trust > Device Group > Traffic Group`
* Connection mirroring bandwidth - If L7 protocol is enabled for virtual server and mirroring enabled then HA interface should send whole IP packet with payload - so it should have the same bandwidth as Internal + External interfaces
* device\_trust\_group and datasync-global-dg - these device groups are system and created automatically
* CMI (centralized management infrastructure) communication channel exchange MCP (Master Control Program) messages via MCPd (Master Control Program)
* Notably, SSL Orchestrator does not rely on native BIG-IP synchronization processes. Configuration sync is handled directly through a separate REST-based communication between the peers.
* SSL Orchestrator sync happens via REST communications on port 443.
* The local mcpd process connects to the local TMM process using TCP port 6699. The local TMM then creates secure connections to remote CMI peer TMMs using TCP port 4353
* F5 does not recommend deploying BIG-IP systems in an Active-Active configuration without a standby device in the cluster, due to the potential loss of high availability
* Application Service Clustering - delivers sub-second failover and comprehensive connection mirroring for a highly available cluster of up to eight devices at the application layer, providing highly available multi-tenant deployments
* Device Service Clustering can synchronize full device configurations in an all-active deployment model, enabling consistent policy deployment and enforcement across devices—up to 32 active nodes.Starting in BIG-IP 11.0.0, the Device Service Clustering (DSC) feature allows you to configure more than two BIG-IP systems in an HA configuration. The DSC feature also allows you to configure multiple devices as active and one or more devices as standby
* `Basic cluster will fail over only if there are no heartbeats between nodes`
* Device service Clustering - more then 2 devices in a cluster
* Floating Shared IP for every interface
* First configure networking, DNS, NTP, routes on both devices....
* Mirroing - synchronization of sessions
* Only LTM part(Local traffic section in GUI: virtual servers, pools, nodes...) of configuration is synced, this is done manually
* We configure completely the primary one, and then just sync config to secondary
* Run config sync/HA utility on main page in GUI
* Separate interface for config syncronization, we use special HA vlan for it - only one interface can be used
* And one interface for failover monitoring (heartbeats) - usually used 2: HA and management, Data interfaces are also possible. Device management > Devices > Failover network. We configure here on which interface and port the device will listen for heartbeat UDP messages. Multicast can be used as well
* And we also configure interface for mirroing (state and sessions replication) - not supported for SSLO
* On the secondary device we configure IP of primary one and provide credentials for it
* Floating IP is created as a regular interface and connected to traffic group. But first you have to create a regular interface.
* You have to create similar IPs and floating IPs on both devices
* Connection mirroring data is shared via a TCP connection using port 1028. 1029 in newer versions
* Persistence mirroring data is shared via a TCP connection using port 1028 - 1029 in newer versions
* Separate process for HA in SSLO
* An SSL Orchestrator system must be configured for MANUAL with INCREMENTAL SYNC
* HA must be configured and stable BEFORE deploying SSLO
* The SSLO peers will sync their configs via REST calls between them
* Device management > Devices: Configsync, mirroring, failover network
* Device trust > Device Trust members > Add peer - configsync IP of the secondary, on one device is enough
* Device management > Device groups > Create one: Manual is usually used
* Traffic group is created automajically. In traffic group we configure Failover method (how F5 will determine who will be primary):
  * HA Score (group)
  * Preferred device order
  * Load Aware - usually used in traffic groups where several devices used with different power and for more correct distribution of load
* Failover objects: what will switch in case of failure
* Active active in F5 world: one app on one device, another app on second device
* Many traffic groups are used for active active
* What triggers failover?
* System fail-safe: With system fail-safe, the BIG-IP system monitors various hardware components, as well as the heartbeat of various system services. You can configure the system to initiate failover whenever it detects a heartbeat failure.Reason to switch is configured in traffic group as well
* Gateway fail-safe: With gateway fail-safe, the BIG-IP system monitors traffic between an active BIG-IP system in a device group and a pool containing a gateway router. You can configure the system to initiate failover whenever some number of gateway routers in a pool of routers becomes unreachable.
  * Configure failover if gateway is unreachable from one node: Gateway fail-safe
  * Create a pool and add a router as member and add ICMP as a health check
  * System ›› High Availability : Fail-safe : Gateway - Add gatewayy pool, select device, select action
  * `Create separate pool for every HA member!!!!!!!!!!!!!!!!!!!!!!!!`
* VLAN fail-safe: With VLAN fail-safe, the BIG-IP system monitors network traffic going through a specified VLAN. You can configure the system to initiate failover whenever the system detects a loss of traffic on the VLAN and the fail-safe timeout period has elapsed
* HA groups: With an HA group, the BIG-IP system monitors trunk, pool, or cluster health to create an HA health score for a device. You can configure the system to initiate failover whenever the health score falls below configurable levels
  * Failover if some services are not accesible from main node:
  * System > High Availability > HA group list
  * HA Score - configured on both devices and then linked in traffic group
  * HA score checks availability of services
  * Primary node will not become active again based on HA score
  * It can be done via script, ti is run on main node, check if it is active and its HA score, if score is ok it ends to secondary node via api Force standby command
* Auto-failback: When you enable auto-failback, a traffic group that has failed over to another device fails back to a preferred device when that device is available. If you do not enable auto-failback for a traffic group, and the traffic group fails over to another device, the traffic group remains active on that device until that device becomes unavailable

About traffic groups

A traffic group is a collection of related configuration objects, such as a floating self IP address, a virtual IP address, and a SNAT translation address, that run on a BIG-IP device. Together, these objects process a particular type of application traffic on that device. When a BIG-IP device becomes unavailable, a traffic group floats (that is, fails over) to another device in a device group to ensure that application traffic continues to be processed with little to no interruption in service. In general, a traffic group ensures that when a device becomes unavailable, all of the failover objects in the traffic group fail over to any one of the available devices in the device group. A traffic group is initially active on the device on which you create it, until the traffic group fails over to another device. For example, if you initially create three traffic groups on Device A, these traffic groups remain active on Device A until one or more traffic groups fail over to another device. If you want an active traffic group to become active on a different device in the device group when failover has not occurred, you can intentionally force the traffic group to switch to a standby state, thereby causing failover to another device. Only objects with floating IP addresses can be members of a floating traffic group. An example of a set of objects in a traffic group is an iApps application service. If a device with this traffic group is a member of a device group, and the device becomes unavailable, the traffic group floats to another member of the device group, and that member becomes the device that processes the application traffic. Note: A Sync-Failover device group can support a maximum of 15 floating traffic groups.

Any traffic group that you explicitly create on the BIG-IP system is a floating traffic group. The types of configuration objects that you can associate with a floating traffic group are:

* Virtual IP addresses
* NATs
* SNAT translation addresses
* Self IP addresses
* Folders (such as an iApps folder)

You can associate configuration objects with a traffic group in these ways:

* You can rely on the folders in which the objects reside to inherit the traffic group that you assign to the root folder
* You can use the BIG-IP Configuration utility to directly associate a traffic group with an iApp application service, a virtual IP address, a NAT or SNAT translation address, or a floating self IP address
* You can use the BIG-IP Configuration utility to directly associate a traffic group with a folder.
* Important: By default, floating objects that you create with the BIG-IP Configuration utility are associated with traffic-group-1. Non-floating objects are associated with traffic-group-local-only. You can change these associations by using the BIG-IP Configuration utility to change the traffic group that is associated with each floating IP address on the system.
* Note: The only non-floating traffic group that resides on the system is the default non-floating traffic group named traffic-group-local-only

**Remove and Re-Create Device Trust**

* Break HA; Break Trust; Recreate Trust; Recreate HA (all this after the upgrade):
* Go to Device Management > Device Groups
* Click on the device group . I believe this can be done on any of the devices at this point
* Remove both the members & click on update
* Go to Device Management > Device Trust. => Perform this step on both devices -Click on Reset Device Trust & select the option Generate new self-signed authority. => Perform this step on both devices
* Go to Device Management > Device Trust > Device Trust Members & add the peer device
* Go to Device Management > Device Groups
* Click on the device group
* Add both the devices & click on update
* Go to Device Management > Overview & do a sync.
* Now verify the HA status is good & both the devices are in sync

Commands

* `tmsh show sys ha-status all-properties`
* Force Standby: `tmsh run /sys failover standby`
* Show configsync status: `tmsh show /cm sync-status`
* The BIG-IP system logs messages related to ConfigSync and DSC to the /var/log/ltm file
* To display log messages related to DSC or CMI, use a command similar to the following example: `grep -i cmi /var/log/ltm`
* To display log messages related to ConfigSync, use a command similar to the following example: `grep -i configsync /var/log/ltm`
* To show the failover status of the BIG-IP system, enter the following command: `show /cm failover-status`
* To list the devices in the local trust domain, enter the following command: `show /cm device-group device_trust_group`
* Check the time delta between all configured devices by entering the following command: `show /cm device all`
* For example, the following command pushes the local device's configuration to remote devices in the Syncfailover device group: `run /cm config-sync to-group Syncfailover`
* Check logs why failover happend: `grep -iE 'active|standby|traffic group|ha|configsync|cmi' /var/log/ltm`
* SSL Chips Failover

```
tmsh modify sys db crypto.ha value < enable | disable >
tmsh modify sys db crypto.ha.action value < failover | none | reboot | restart-all | go-offline-downlinks | go-offline-downlinks-restart >
```

## Network

* `Interfaces > VLAN(tagged or untagged) > Self IPs`
* Trunk = LAG
* QSFP+ 40G - if it is bundled in configuration then it means QSFP+ transievers on both sides, no breakout cable is involved
* To use breakout cable, interface should be unbundled and then connected with a trunk in configuration
* Show interfaces in the form of config code

```
root@(sslo1)(cfg-sync Disconnected)(Active)(/Common)(tmos)# list net interface
net interface 1.1 {
    if-index 48
    mac-address 00:50:56:8a:a8:9d
    media-active 10000T-FD
    media-fixed 10000T-FD
    media-max auto
}
net interface 1.2 {
    if-index 64
    mac-address 00:50:56:8a:5e:80
    media-active 10000T-FD
    media-fixed 10000T-FD
    media-max auto
}
```

Show interface stats and status in the form of a table

```
Disconnected)(Active)(/Common)(tmos)# show net interface

-------------------------------------------------------------------
Net::Interface
Name  Status    Bits    Bits   Pkts    Pkts  Drops  Errs      Media
                  In     Out     In     Out
-------------------------------------------------------------------
1.1       up    4.5T  155.6M   9.3G  214.9K      0     0  10000T-FD
1.2       up  207.7G    4.1G  33.0M    7.6M      0     0  10000T-FD
1.3       up    4.5T   90.7M   9.3G  269.9K      0     0  10000T-FD
1.4       up    4.4T  188.5M   9.3G  355.8K      0     0  10000T-FD
1.5       up    4.4T   33.9M   9.3G    5.3K      0     0  10000T-FD
mgmt      up    4.7G    2.3G   5.5M    2.4M      0     0   100TX-FD
```

Show drops statistics

```
tmsh show sys ip-stat 
tmsh show sys tmm-traffic
```

Interface statuses

* Up
* Down
* Disabled
* Unpopulated - No optic
* Uninitialized - No VLAN configured
* MISS - No SFP

**VLANs**

Create VLAN untagged and tagged

```
create /net vlan test-vlan interfaces add { 1.1 }
create /net vlan test-vlan interfaces add { 1.1 { tagged }} tag 4093
save /sys config
```

Show detailed info about VLAN

```
show /net vlan

-------------------------------------
Net::Vlan: HA
-------------------------------------
Interface Name      HA
Mac Address (True)  00:50:56:8a:92:f4
MTU                 1500
Tag                 4092
Customer-Tag

  | Incoming Discard Packets             1
  | Incoming Error Packets               0
  | Incoming Unknown Proto Packets       0
  | Outgoing Discard Packets            12
  | Outgoing Error Packets               0
  | HC Incoming Octets                1.1T
  | HC Incoming Unicast Packets       9.3G
  | HC Incoming Multicast Packets   989.8K
  | HC Incoming Broadcast Packets     9.3G
  | HC Outgoing Octets              111.6M
  | HC Outgoing Unicast Packets         32
  | HC Outgoing Multicast Packets   959.1K
  | HC Outgoing Broadcast Packets   441.1K
  | PVA Incoming Packets                 0
  | PVA Incoming Octets                  0
  | PVA Outgoing Packets                 0
  | PVA Outgoing Octets                  0

  -----------------------
  | Net::Vlan-Member: 1.3
  -----------------------
  | Tagged    no
  | Tag-Mode  none

     -----------------------------------------------------------------
     | Net::Interface
     | Name  Status  Bits   Bits  Pkts    Pkts  Drops  Errs      Media
     |                 In    Out    In     Out
     -----------------------------------------------------------------
     | 1.3       up  4.5T  90.9M  9.3G  270.5K      0     0  10000T-FD
```

Show VLAN configuration in the form of config file

```
list /net vlan

net vlan HA {
    fwd-mode l3
    if-index 176
    interfaces {
        1.3 { }
    }
    tag 4092
}
```

**VLAN Group** `We add to group external and internal vlan and then F5 works like a switch.`

**Self IPs**

Create Self-IP

```
create net self test1 address 1.1.1.1/32 vlan test1
```

Show self-ip in the form of config

```
root@(sslo1)(cfg-sync Disconnected)(Active)(/Common)(tmos)# list net self
net self from_PA_vip {
    address 192.168.3.3/24
    allow-service all
    floating enabled
    traffic-group traffic-group-1
    unit 1
    vlan from_PA
}
```

Show self-ip details

```
show net self

------------------------
Net::Self IP: 10.0.1.148
------------------------

  ---------------------------------------
  | Net::Vlan: external
  ---------------------------------------
  | Interface Name      external
  | Mac Address (True)  00:50:56:8a:5e:80
  | MTU                 1500
  | Tag                 4093
  | Customer-Tag

     -----------------------
     | Net::Vlan-Member: 1.2
     -----------------------
     | Tagged    no
     | Tag-Mode  none

        -----------------------------------------------------------------
        | Net::Interface
        | Name  Status    Bits  Bits   Pkts  Pkts  Drops  Errs      Media
        |                   In   Out     In   Out
        -----------------------------------------------------------------
        | 1.2       up  208.4G  4.1G  33.1M  7.6M      0     0  10000T-FD
```

**ARP**

```
tmsh show net arp all
```

**Assymetric and wrong traffic**

If we send traffic to interface IP it will send Reset

## LTM

* It can work with HTTP, SSH....ANY TCP protocol
* Node(configure server) > Pool(configure nodes + ports + health checks)
* Create virtual server and connect it with pool
* Configure profiles for Virtual server
* Virtual server can be L4-L7
* Virtual server can be Wild carded: All IPs, All ports...
* If there is no any Virtual server, traffic will be denied by default
* SNAT is not enabled by default, it is configured in virtual server
* iRules are in TCL and connected to Virtual server
* Local policies can manipulate and forward traffic
* Source NAT auto map is used to connect to web server from Big IP
* If server is very powerfull bigger ratio can be used to send more traffic to it - this and round robin are static load balance methods
* Ratio can be configured in Nodes and in Pools
* We can choose on which to balance nodes conf or pools member conf
* SSl client profile is used when client connects to F5 via SSL and then to the server there is naked HTTP
* SSL server profile is used when SSL on the server as well
* One arm configuration - when Virtual Server and servers are in one subnet, A common problem with one-armed configurations is that they can break load balancing when:
  * The web servers do not use the BIG-IP system as the default gateway
  * The client is in the same subnet as the virtual server and web servers.

### Packet processing

* Existing connection
* Packet filter
* Virtual server
* SNAT
* NAT
* Self-IP
* Drop

Virtual server selection priority

* IP addr:port
* IP addr: \*
* IP network: port
* IP network: \*
* \*: port
* \*: \*

`If a matching Virtual Server is down or disabled, any available lower priority Virtual Server is not selected. You can change this behavior by setting the BigDB TM.ContinueMatching variable to enabled`

**NAT**

* If the traffic is not matched to a Virtual Server, matching against SNATs and NATs occurs, as follow:
* The most specific origin (original source address or network) of multiple SNAT objects will be used.
* The most specific origin (original source address or network) of multiple NAT objects will be used.
* A specific (not wildcard or default) SNAT will take precedence over a specific NAT object.
* If traffic matches both a Destination (Virtual Server, SNAT or NAT) and a Source Listener (SNAT, NAT), the Destination Listener takes precedence.

### Object statuses

* Green circle - object is available
* Blue square - Uknown
* Yellow triangle - not availbale, but may become available
* Red diamond - unavailable
* Black circle - disabled available object
* Black diamond - disabled unavailable object
* Gray icons - parent object disabled the object
* Black square - availability is uknown + disabled

### Listeners

* These local traffic objects create listeners for new connection requests matching the destination host or network IP address:
  * Virtual servers (Destination address)
  * NATs (NAT address)
* When a new connection request matches both a virtual server and a NAT, the BIG-IP system places a higher precedence on the virtual server listener. Unless the NAT has a more specific address
* When a new connection request matches multiple virtual servers, the BIG-IP system places a higher precedence on the virtual server listener with a more specific IP address/netmask.
* These local traffic objects create listeners for new connection requests matching the source host or network IP address:
  * NATs (Origin address)
  * SNATs (Origin)
* It is important to understand the following regarding NATs and SNATs:
  * NATs can use only host IP addresses for the source address match.
  * SNATs can use both host and network IP addresses for the source address match.
  * NATs and SNATs cannot share the same origin host IP address.
* When a new connection request matches both a NAT and SNAT, the BIG-IP system places a higher precedence on the NAT listener.
* When a new connection request matches multiple SNATs, the BIG-IP system places a higher precedence the SNAT listener with a more specific IP address/netmask.
* Virtual Servers may listen both: source and destination
* When a new connection request matches multiple virtual servers, the BIG-IP system places a higher precedence on the virtual server listener with a more specific IP destination address/netmask.

### Virtual Servers

* K55185917: Overview of BIG-IP virtual server types (12.x - 15.x) - <https://support.f5.com/csp/article/K55185917>
* If we disable virtual server, everything under its src and dst will be dropped!!!
* Virtual servers reply to pings
* They reply from their own address, not from interface IP
* Wildcard, when destination IP is 0.0.0.0/0, can be used to load balance traffic between 2 firewalls, destination IP is not changed
* Default wildcard virtual server - all IPs, all ports, all VLANs - BIG IP is transformed into a router
* Port based wildcard - specific port configured for all IPs
* When you create VS in cluster, it listens only on active node. To change this, you need to go `LTM > Virtual servers > Virtual addresses` and change its address to local group
* VS maybe down because pool is down, but it may still work, because there are policies or iRules which redirect traffic to different pool, or different VS or different site

They can be

* Standard - listen on VLAN, can use L4 profiles(TCP, UDP, SCTP) and L7 profiles(HTTP, SSL, FTP)
* Internal - does not listen on network, accept traffic from Standard virtual servers. Used for ICAP for example.
* Forwarding IP type - destination of packet is not changed
* Performance L4 - simply forward packets, no full proxy - utilize PVA acceleration chip - Fast L4 profile
* Performance HTTP - optimize HTTP traffic: faster, less CPU, many restrictions - Fast HTTP profile
* Reject - send RST
* DHCP relay
* Stateless - perfect for load balance DNS traffic, Big IP does not track connections, DNS servers may reply via different path
* Message routing - for balancing sip traffic

Show info about VS, including stats, traffic, CPU usage, SYN cookies, status:

```
show ltm virtual Linux
bigtop
```

Troubleshooting

* Check connection to members
* Check monitor
* Check if traffic hits Virtual server - tcpdump + VS stats
* Check if traffic goes to member - tcpdump
* Check default gateway on member + SNAT

### Pools

* Check pool members flapping in /var/log/ltm
* Check monitors
* Show pools in all partitions: `cd /; list ltm pool recursive`
* Show pool members in partition: `cd /Common; list ltm pool`
* Show pool members: `ltm list pool testpool`
* Add pool member with name (Node should be created first) `modify ltm pool Mega_Pool members add { AJCP-EXMR09_webmail:443 }`

**Disable pool member for upgrade**

```
CLIENT → F5 → POOL MEMBER

Disable:
   Existing sessions → continue ✅
   New sessions     → blocked ❌

Forced Offline:
   Existing sessions → terminated 💥
   New sessions     → blocked ❌
```

### Connections

Show all connection to VIP `show /sys connection cs-server-addr 10.127.80.250`

```
       Client-Side                                         Server-Side
-----------------------------------------------         -----------------------------------------------
   [Source IP:Port] [Destination IP:Port]   [Source IP:Port] [Destination IP:Port]    [Protocol] [Age] [Slot/TMM] [PVA Acceleration] [Neuron Rules]
```

```
10.100.36.141:53570  10.127.80.250:443  10.127.80.20:53570  10.127.26.24:443  tcp  0  (slot/tmm: 6/2)  none  none
10.100.36.141:56986  10.127.80.250:443  10.127.80.20:56986  10.127.26.89:443  tcp  1  (slot/tmm: 6/4)  none  none
10.100.36.141:56938  10.127.80.250:443  10.127.80.20:56938  10.127.26.89:443  tcp  0  (slot/tmm: 6/3)  none  none
10.100.36.141:53728  10.127.80.250:443  10.127.80.20:53728  10.127.26.33:443  tcp  2  (slot/tmm: 6/3)  none  none
```

`tmsh show sys connection all-properties`

```
Sys::Connections
10.80.247.34:42508 - 10.80.247.38:80 - 10.80.247.1:42508 - 10.80.247.3:80
-------------------------------------------------------------------------
  TMM           0
  Type          any
  Acceleration  none
  Neuron Rules  none
  Protocol      tcp
  Idle Time     0
  Idle Timeout  300
  Unit ID       1
  Lasthop       /Common/External 00:50:56:xx:xx:xx
  Server Nexthop /Common/Internal 00:50:56:xx:xx:xx
  Ingress Dest  none
  Virtual Path  10.80.247.38:80
  Conn Id 0  
             
                       ClientSide         ServerSide
  Client Addr  10.80.247.34:42508  10.80.247.1:42508
  Server Addr     10.80.247.38:80     10.80.247.3:80
  Bits In                   30.7M              11.4G
  Bits Out                  11.4G              95.6M
  Packets In                73.9K             428.4K
  Packets Out              416.7K             229.8K

Total records returned: 1
```

### Local policy

* Draft policy, publish the policy, and then associate the published policy with a virtual server
* Match strategy, conditions, actions
* Matching strategies: a first-match, best-match, and all-match, user-defined
* In a best-match or first-match strategy, a rule without conditions becomes the default rule, when the rule is the last entry in the Rules list
* In an all-match strategy, when multiple rules match, but specify conflicting actions, only the action of the best-match rule is implemented. A best-match rule can be the lowest ordinal, the highest priority, or the first rule that matches in the Rules list: The lower rule the better during conflict!
* When you add a new rule, it is added to the end
* Many condition types: HTTP headers, SSL headers, TCP headers, Geo IP, CPU usage, URL category
* Different selectors: host, port, full strings, value, path...
* Different conditions: is, is not, in data group, any of
* Many actions:
  * Blocking traffic
  * Rewriting a URL
  * Logging traffic
  * Adding a specific header
  * Redirecting traffic to a different pool member
  * Selecting a specific Web Application policy

Disable Resp mode in SSLO for all traffic

* Create LTM policy Local traffic > Policies
* Create rule
* Condition: All traffic, Action: Disable response adapt at response time
* Apply policy to ICAP service in SSLO

Disable all methods except PUT and POST

* Condition: HTTP Method is not any of PUT POST at request time
* Action: Disable request adapt at request time

Disable Request Adapt, Response Adapt only for certain files

* Strategy: execute all rules
* 3 rules
* Rule 1: Disable request Adapt - HTTP Method exists at request time - Disable request adapt at request time
* Rule 2 - HTTP Status full string exists at response time - Disable Response Adapt at Response time
* Rule 3: HTTP Header full string named Content-Type is in datagroup "datagroup name" at response time - Enable response adapt at response time

Datagroup type string contents:

* application/octet-stream
* application/zip
* application/x-7z-compressed

Using TCL

* Condition: HTTP host is any of example.com
* Action for redirection with URI: `Redirect to Location https:///www.example.ca[HTTP::uri] at Request Time`

### Load balance

Static load balancing methods - 2

* Round Robin - every new connection goes to the next server in line, good when all servers are equal
* Ratio (member) Ratio (node) - based on ratios for every node or member. Ratio is configured in member and in node.

Dynamic methods - 9

* Fastest - The Fastest methods select a server based on the least number of current sessions. These methods require that you assign both a Layer 7 and a TCP type of profile to the virtual server.
* Least Connections (member) Least Connections (node) - based on least number of active connections
* Weighted Least Connections - For example, member\_a has 20 connections and its connection limit is 100, so it is at 20% of capacity. Similarly, member\_b has 20 connections and its connection limit is 200, so it is at 10% of capacity. In this case, the system select selects member\_b. This algorithm requires all pool members to have a non-zero connection limit specified
* Observed - With the Observed methods, nodes are ranked based on the number of connections. The Observed methods track the number of Layer 4 connections to each node over time and create a ratio for load balancing
* Predictive - The need for the Predictive methods is rare, and they are not recommend for large pools. with the Predictive methods, Local Traffic Manager analyzes the trend of the ranking over time, determining whether a node’s performance is currently improving or declining. The servers with performance rankings that are currently improving, rather than declining, receive a higher proportion of the connections.
* Least sessions - The Least Sessions method selects the server that currently has the least number of entries in the persistence table. Use of this load balancing method requires that the virtual server reference a type of profile that tracks persistence connections, such as the Source Address Affinity or Universal profile type. Note: The Least Sessions methods are incompatible with cookie persistence. The Least Sessions method works best in environments where the servers or other equipment that you are load balancing have similar capabilities
* Ratio least connections - The Ratio Least Connections methods cause the system to select the pool member according to the ratio of the number of connections that each pool member has active
* Ratio least sessions - least sessions method + ratio configured

Priority group activation

* One group of pool members is primary and other is redundant
* We configure minimum amount of active pool members in active group
* The group with highest number is primary
* Priority group is configured for member and policy group activation is configured for pool
* If one server from primary group fails, all servers from secondary group are activated
* When host is Up again, everything is switched back: only primary group serves

Fallback host

* Will redirect traffic to Appology server when all members are down, configured in HTTP profile

### Persistence

* LB methods define how to distribute initial packets of session, for example based on least connections
* Persistence profile then keeps this distributed session on one pool member, for example based on destination address
* Connection requests from the client that do not use persistence are load balanced according to the currently selected load balancing method
* Persistent profile is attached to virtual server as a profile
* Balancing method is attached to pool
* Most methods can work on node level and member level
* Ensure that client requests are directed to the same pool member throughout the life of a session or during subsequent sessions
* When you enable persistence, returning clients can bypass load balancing and instead connect to the server to which they last connected in order to access their saved information
* The BIG-IP system keeps session data for a period of time that you specify
* You can write an iRule, which enables a persistence type for particular requests (for example, for HTTP traffic that includes a certain cookie version only)
* Default persistence timeout is 180 or 300 s

Persistent profiles:

* Cookie persistence - from web server
* Destination address affinity persistence - based solely on the destination IP address of a packet
* Hash persistence - a hash value may be created based on Source IP, Destination IP, Destination Port
* Microsoft® Remote Desktop Protocol persistence
* SIP persistence
* Source address affinity persistence
* SSL persistence - SSL session ID
* Universal persistence - any piece of data

Show persistence data

```
show ltm persistence persist-records
```

Cookie persistence methods

* Cookie Hash
* HTTP Cookie Insert - default method - By default, the cookie is named BIGipServer\<pool\_name> is inserted into HTTP reply from server
* HTTP Cookie Passive - not recomended - the server provides the cookie, formatted with the correct server information and timeout
* HTTP Cookie Rewrite - recomended - cookie is intercepted and rewritten - BIG-IP system intercepts a Set-Cookie header, named BIGipCookie - The new cookie is named BIGipServer\<pool\_name> and it includes the address and port of the server handling the connection

Persistence mirroring

* Need to be enabled in a profile
* The BIG-IP system can mirror persistence information between peers for the following persistence profiles:
  * Destination address affinity
  * Hash
  * Host
  * Microsoft Remote Desktop
  * SIP
  * Source address affinity
  * SSL -Universal

Show mirriored persistence records

```
tmsh show /ltm persistence persist-records
```

### Profiles

* They are attached to Virtual Servers
* Services: HTTP, FTP, SIP, HTTPS, DNS, SIP, Diameter, Radius, RTSP, XML, SPDY
* Protocol: TCP, UDP, Fast L4
* Persistence: Cookie, RDP, Source address, SSL, Hash, Destination Address, SIP, Universal
* SSL: Client, Server
* Auth: Radius, LDAP, TACACS+, Radius, SSL OSCP, SSL/LDAP, CRLDP, Kerberos Delegation, XMP
* Analytics
* Web Acceleration profile provides settings to configure HTTP caching for the BIG-IP system. HTTP caching allows the BIG-IP system to store frequently requested web objects in memory for reuse by subsequent connections.
* Other: Oneconnect, Stream(change text in response), Request logging, NTLM, Statistics, DNS logging
* Profiles of higher levels depend on lower level profiles
* Profiles of the same level are exclusive
* All virtual servers have a protocol profile
* Default profiles: /config/profiles\_base.conf

Show cache for acceleration profile

```
tmsh show /ltm profile ramcache all
```

Clear the cache

```
tmsh delete /ltm profile ramcache acceleration_profile_name
```

## Routing

* The BIG-IP system maintains two kinds of routes:
  * Management routes: Management routes are routes that the BIG-IP system uses to forward traffic through the special management interface. The BIG-IP system stores management routes in the Linux (that is, kernel) routing table
  * TMM routes: TMM routes are routes that the BIG-IP system uses to forward traffic through the Traffic Management Microkernel (TMM) interfaces instead of through the management interface
  * The BIG-IP system stores TMM routes in both the TMM and kernel routing tables
  * TMM routes have lower metric and they are always preferred over management routes
* VIPs can be advertised to dynamic routing, based on the fact if they are available or not
* When we create VS, it creates VIP, VS can send its status to VIP, in VIP configuration we can configure ARP, ICMP echo, and advertisment to dynamic routing
* F5 may have only one physical interface and advertise many networks to other routers
* Physical interfaces are used only for connection with other routers
* F5 can advertise any amount of different networks
* Usually F5 only sends routes and receives nothing, blocking with filters, and using default GW
* Every VIP created is added to a routing table as Kernel: `K 10.255.255.15/32 [0/0] is directly connected, tmm`
* There are Kernel(VIPs, Static, Default gateway), Connected(Interfaces) and BGP routes

Add management route

```
create /sys management-route default gateway 192.168.5.1
save sys config
```

View the management route

```
tmsh list /sys management-route
```

Delete static management route

```
tmsh delete /sys management-route lognet
```

Show all routes

```
netstat -rn
```

Show routing table including kernel and BGP: `show /net route`

Show route for particular destination

```
show net route lookup
```

Del route

```
del net route Default
```

Create route

```
tmsh
create net route 10.10.22.0/24 gw 30.30.30.158
list net route
save /sys config
```

Non floating address is used for syslog and other services

### Route domains

* Network > Route Domains
* ID, VLANs, Ruting protocols, bandwidth, connections
* Route domain is specified inside virtual server configuration in destination address field: 192.168.1.10%10 - 10 is route domain ID
* Default route domain is 0
* Route domain is specified in static routes in destination field and gateway field

### BGP

```
imish

enable

router bgp 4294965110
 bgp router-id 10.127.131.5
 bgp graceful-restart restart-time 120
 network 10.126.73.0/24
 network 10.126.73.0/25
 network 10.126.73.128/25
 network 10.127.119.0/24
 network 10.127.119.0/25
 network 10.127.119.128/25
 
 redistribute kernel - redistribite to BGP all Kernel routes: static routes + default gateway + VIPs, no physical interfaces
 
 neighbor 10.127.131.2 remote-as 4294965114
 neighbor 10.127.131.2 next-hop-self
 neighbor 10.127.131.2 soft-reconfiguration inbound
 neighbor 10.127.131.2 prefix-list deny-all in
 neighbor 10.127.131.2 prefix-list allow-vips out

ip prefix-list deny-all description deny inbound routes 
ip prefix-list deny-all seq 10 deny any

ip prefix-list allow-vips description permit virtual server vips to be advertised
ip prefix-list allow-vips seq 5 permit 10.126.73.0/24 le 32
ip prefix-list allow-vips seq 10 permit 10.127.119.0/24 le 32
ip prefix-list allow-vips seq 15 permit 10.255.255.0/24 le 32
ip prefix-list allow-vips seq 20 permit 10.2.66.0/28

show ip bgp summary
show run
show ip bgp neighbors 10.127.131.2 advertised-routes
show ip route
```

## Traffic groups

* Several traffic groups may exist, Host A may be active for traffic group 1 and Host B for traffic group B
* We can control to which traffic group which floating IP or VIP is connected: Interfaces section and Virtual Addresses Section

## Monitors

* Address check - ICMP
* Application check - FTP
* Content check - send and receive string, special PHP file with DB check is cool
* Performance - SNMP
* Path check - gateway ICMP with transparent option, HTTP, TCP...are also supported
* Service check - regular port check
* Availability requirement setting for a pool member or node - how many monitors should be online to consider object available
* Test monitor with curl and tmsh run /ltm monitor before attaching new monitor or all members may become down, just create a copy of working monitor, change it and test
* In-TMM monitoring - capability to run ICMP, TCP, HTTP, and HTTPS monitors in the TMM process, which allows monitors to consume fewer system resources and scale more efficiently. Additionally, the feature uses SSL acceleration hardware and Server SSL profiles for HTTPS monitors
* Show errors for monitor `show /ltm monitor http site.com_HTTP_monitor`
* Show stats for monitor `show /ltm monitor http odp-mppe.digital.fglcorporate.net_HTTP_monitor stats`
* Run monitor test `run /ltm monitor http odp-mppe.digital.fglcorporate.net_HTTP_monitor destination 192.168.226.75:8090`
* Enable logging in monitor configuration
* Example of correct HTTP 1.1 monitor `GET /index.html HTTP/1.1\r\nHost: example.com\r\n`

Logs

* Logs are in /var/log/monitors, /var/log/ltm
* Logs can be enabled for node, pool member
* Logs for SNMP DCA are enabled separately and stored in /shared/tmp/snmpdca.log
* Globally enable monitor status logging

Hierarchy

* If a node is Down, all pool members connected to it are down.
* If at least one pool member is available, then pool is available
* If pool is offline, virtual server is offline

Test monitor

```
tmsh run util test-monitor 'monitor_name' 'ip_address' 'port'
```

Enable monitor status logging - shows which monitor exactly triggered status change

```
modify /sys db bigd.lognodestatuschange valuse enable
save /sys config
```

Test monitor

```
tmsh run util test-monitor 'monitor_name' 'ip_address' 'port'
```

Enable monitor status logging - shows which monitor exactly triggered status change

```
modify /sys db bigd.lognodestatuschange valuse enable
save /sys config
```

Check:

```
tail -f /var/log/ltm | grep -Ei "detected.mon|monitor.status"
```

Example:

```
local/bigip-1 notice bigd[3747]: 01060001:5: Service detected DOWN for ::ffff:10.10.100.25:80 monitor http.
local/bigip-1 notice mcpd[3741]: 01070638:5: Pool member 10.10.100.25:80 monitor status down.
local/bigip-1 notice bigd[3747]: 01060001:5: Service detected UP for ::ffff:10.10.100.25:80 monitor http.
local/bigip-1 notice mcpd[3741]: 01070727:5: Pool member 10.10.100.25:80 monitor status up.
```

Monitor Paloalto SSLO

* Create monitor with alias address
* Double NAT on Palo Alto
* TCP + ICMP to SSLO interface from PA
* 192.168.2.1 - to\_PA interface
* 192.168.2.2 - PA interface
* On SSLO add static route for 1.1.1.1 via PA(192.168.2.2)
* Ping 1.1.1.1, on PA change source to PA's interface IP which faces from\_PA subnet, and change destination IP to SSLO's from\_PA interface.
* Create virtual server with source of PA's interface(from\_PA subnet), and destination of from\_PA address and port 4444
* telnet 1.1.1.1 4444 will also work

HTTP monitors

HTTP 1.1 examples

```
GET /index.html HTTP/1.1\r\nHost: host.domain.com\r\nConnection: Close\r\n\r\n
POST /form.cgi HTTP/1.1\r\nHost: host.domain.com\r\nConnection: Close\r\n\r\nFirst=Joe&Last=Cool
```

Note: A double \r\n sequence must separate the last header from the request body No EOL after POST request data

**ICAP monitors**

To send text file to ICAP server

```
cat icap.txt | nc 100.104.51.10 1344
```

Text file, GET request, EOL should be CRLF, double enter after last row

```
REQMOD icap://100.104.51.10:1344/icap/full ICAP/1.0
Date: Tue, 15 Mar 2022 14:33:20 GMT
Host: 100.104.51.10:1344
Encapsulated: req-hdr=0, null-body=110
X-Client-IP: 100.67.130.47

GET / HTTP/1.1
Host: www.yandex.ru
Accept: text/html, text/plain
Accept-Encoding: compress

```

Send string GET

```
REQMOD icap://100.104.51.10:1344/icap/full ICAP/1.0\r\nDate: Tue, 15 Mar 2022 14:33:20 GMT\r\nHost: 100.104.51.10:1344\r\nEncapsulated: req-hdr=0, null-body=110\r\nX-Client-IP: 100.67.130.47\r\n\r\nGET / HTTP/1.1\r\nHost: www.yandex.ru\r\nAccept: text/html, text/plain\r\nAccept-Encoding: compress\r\n\r\n
```

Text file, POST request, EOL should be CRLF, double enter after last row

```
REQMOD icap://100.104.51.10:1344/icap/full ICAP/1.0
Date: Tue, 15 Mar 2022 14:33:20 GMT
Host: 100.104.51.10:1344
Encapsulated: req-hdr=0, null-body=110
X-Client-IP: 100.67.130.47

POST /http-post/ HTTP/1.1
Host: dlp-test.com
Accept: text/html, text/plain
Accept-Encoding: compress

Sending credit card number

```

The same but without connection to IP, Host header may be anything!

```
REQMOD /icap/full ICAP/1.0
Date: Tue, 15 Mar 2022 14:33:20 GMT
Host: 100.104.51.10:1344
Encapsulated: req-hdr=0, null-body=110
X-Client-IP: 100.67.130.47

POST /http-post/ HTTP/1.1
Host: dlp-test.com
Accept: text/html, text/plain
Accept-Encoding: compress

Sending credit card number
```

Send string POST

```
REQMOD icap://100.104.51.10:1344/icap/full ICAP/1.0\r\nHost: 100.104.51.10:1344\r\nEncapsulated: req-hdr=0, null-body=170\r\n\r\nPOST /http-post/ HTTP/1.1\r\nHost: dlp-test.com\r\n\r\nSending credit card number\r\n\r\n
```

Send string POST without connection to IP, Host header may be anything!

```
REQMOD /icap/full ICAP/1.0\r\nHost: 100.104.51.10:1344\r\nEncapsulated: req-hdr=0, null-body=170\r\n\r\nPOST /http-post/ HTTP/1.1\r\nHost: dlp-test.com\r\n\r\nSending credit card number\r\n\r\n
```

Receive string

```
ICAP/1.0 200 ok
```

Test ICAP availability via telnet and OPTIONS method

```
OPTIONS icap://127.0.0.1:1344/reqmod ICAP/1.0
```

## Email, alerts, SNMP

* `System > SNMP > Access V3`
* `Traps > Destination`
* All alerts are described in /etc/alertd/alert.conf
* Alerts are based on logs and on hardware, and which OID is used
* Alerts which sent to LEDs, are also configured here.
* All alerts are also logged to /var/log/ltm
* We can change their priority

After change:

```
bigstart restart alertd
```

Test log message

```
logger -p local0.warning "Initialization complete. The MCP is up and running."
```

Clear LCD panel

```
lcdwarn -c level slotid
```

* User based alerts, configure alert name, search string in Logs and email settings
* /config/user\_alert.conf

Example, email alert during auth failure:

```
alert BIGIP_GUI_AUTH_FAIL2 "[error](.*) AUTHCACHE PAM: user (.*) not authenticated: Authentication failure" {
        snmptrap OID=".1.3.6.1.4.1.3375.2.4.0.27";
        email toaddress="angara@waf2021.lab.bi.zone"
        fromaddress="root"
        body="Authentication failed"
}
```

Configure trigger for CPU:

```
tmsh
modify sys db cpu.logthreshold value 1
save sys config

list sys db cpu.logthreshold
```

Debug emails and SNMP traps:

```
tcpdump -nni 0.0 port 25 or port 162 –A
```

Send email script

```
#!/bin/bash

loglines=1 #how many of the last lines of /var/log/ltm to mail
ltm_log=$(tail -n "$loglines" /var/log/ltm)

function fappend {
    echo "$2">>$1;
}

# CHANGE THESE
TOEMAIL="test@ciscolab.comptek.ru";
SUBJECT="CPU too high.";
MSGBODY="$ltm_log";

# DON'T CHANGE ANYTHING BELOW
TMP=`mktemp`

rm -rf $TMP;
fappend $TMP "To: $TOEMAIL";
fappend $TMP "Subject: $SUBJECT";
fappend $TMP "";
fappend $TMP "$MSGBODY";
fappend $TMP "";
fappend $TMP "";
cat $TMP|sendmail -t;
rm $TMP;

exit 0
```

chmod 777 send\_mail.sh

Configure Relay

```
tmsh
modify sys outbound-smtp mailhub IP:port
save sys config
```

If we need to execute custom command

```
alert pool_member_forced_offline "Cpu utilization over 300 seconds is (.*), exceeded log level (.*)" {
        snmptrap OID=".1.3.6.1.4.1.3375.2.4.0.301";
        exec command="/home/root/send_mail.sh"
}
```

Change pool member priority group after failover

/var/log/ltm:

```
Change from active to passive: HA unit 1 state change: from 1 to 0
Change from passive to active: HA unit 1 state change: from 0 to 1
```

/config/user\_alert.conf:

```
alert HA_priority_group "HA unit 1 state change" {
exec command="/usr/bin/tmsh modify sys application service ssloS_Palto.app/ssloS_Palto strict-updates disabled; /usr/bin/tmsh modify ltm pool ssloS_Palto.app/ssloS_Palto members modify { ssloS_Palto.app/192.168.2.2:http { priority-group 10 } }"
}
```

## Bandwidth controllers

* You apply a bandwidth control policy to a virtual server, packet filter, or route domain, you can apply only one policy at a time, and that is a static policy
* Using iRules®, you can combine static and dynamic bandwidth control policies up to eight policies on a connection, but only one of the eight policies can be a dynamic policy. A packet is transmitted only when all the attached policies allow it. The system as a whole supports a maximum of 1024 policies
* Applying a bandwidth controller policy to a route domain affects all traffic transmitted by the BIG-IP system to VLANs in the route domain, including health monitors and DNS queries
* Only static bandwidth control policies support SNMP queries
* Bandwidth controller is the updated version of rate shaping on the BIG-IP® system. These features are mutually exclusive. You can configure and use either rate shaping or bandwidth controllers, but not both. Bandwidth controllers include distributed control, subscriber fairness, and support for a maximum rate of 320 Gbps. Rate shaping is hierarchical and supports minimum bandwidth (committed information rate), priority, and flow fairness
* Acceleration > Bandwidth Controllers
* Configure max rate 1 Mbps to 320 Gbps
* Add controller to virtual server

## SSL

SSL setups:

* SSL offloading - clients connect to F5, traffic to pools unencrypted, only clientSSL profile
* SSL bridging - clients connect to F5, new SSL session with pool member, both clientSSL and serverSSL
* SSL passthrough - F5 forwards SSL to pool member, no profiles

Two types of SSL cipher suites

* Native - optimized for F5
* Compat - OpenSSL library

Concepts

* If you enable ClientSSL cert then all SSL requests from client will be terminated on F5
* If you enable ServerSSL profile - then all requests to server will be sent via SSL - yes
* If we configure only ClientSSL profile, client terminates SSL on F5 via F5's cert, and then F5 sends pure HTTP to server, even if it is port 443
* If we configure only ServerSSL profile, then it will not work, in this case we have to connect to F5 using pure HTTP and then it will encrypt it with SSL before sending to server

### ClientSSL profile

* Certificate + key
* TLS versions
* Ciphers
* Client authentication
* Forward proxy
* Client Certificate Constrained Delegation
* Non-SSL Connections - Enables or disables acceptance of non-SSL connections. Disabled (cleared) by default.

### ServerSSL profile

* Used for authenticating F5 to the Server
* Used additional security and standards compliance
* Only F5 can connect to the server
* When renew ServerSide cert we need to do it together with server, to avoid distruption - allthough proper CA cert should be enough

### Proxy SSL

* Proxy SSL feature enables the BIG-IP system to optimize SSL traffic between the client and the destination server, without terminating the SSL connection on the BIG-IP system
  * The iRules read or write application data.
  * The BIG-IP ASM security policy inspects and protects web application traffic.
  * The BIG-IP AAM system optimizes application traffic.
  * The system passes client certificates to servers that require mutual authentication
  * Importing the certificate and key pair that the destination server uses to the BIG-IP system
  * Associating the certificate and key pair with the Server SSL profile configured for the BIG-IP virtual server used in the Proxy SSL connection

SSL Proxy sequence of events

* The client establishes a full TCP connection to the BIG-IP virtual server.
* The BIG-IP virtual server establishes a full TCP connection to the destination server.
* The client and destination server exchange SSL handshake messages.
* When the destination server sends its certificate in the SSL ServerHello packet, if the certificate matches the certificate that is configured in the Server SSL profile, the BIG-IP virtual server forwards the SSL ServerHello packet
* While the SSL handshake messages are being exchanged, the BIG-IP virtual server examines the SSL messaging data.
* The destination server authenticates and verifies the client and grants access to the client.
* When the SSL handshake completes, the BIG-IP virtual server has sufficient information to generate the appropriate tokens to decrypt the traffic.
* When the client starts sending traffic through the SSL connection established with the destination server, the BIG-IP system optimizes the traffic using the same SSL credentials that the client negotiated during the SSL handshake phase

### SSL forward proxy

* The system encrypts all traffic between a client and the BIG-IP system using a second unique server certificate dynamically generated by the BIG-IP system, and encrypts all traffic between the BIG-IP system and the server using the certificate provided by the server
* Instead of using ClientSSL profile certificate
* You must create both a Client SSL and a Server SSL profile, and enable the SSL Forward Proxy feature in both profiles
* The BIG-IP system uses the certificate provided by the server (including wildcard certificate) to create the second unique server certificate
* First prepare both profiles and them apply them simuteniously to virtual server
* Configure:
  * CA key + cert - to sign dynamic server certs - clientSSL cert
  * Certificate extensions - clientSSL cert
  * Bypass enabled or not + what is default - bypass or intercept - clientSSL cert + ServerSSL
  * Bypass or intercept based on source and dst IPs and hostnames - data groups - clientSSL cert + ServerSSL
  * Bypass on handshake alert - clientSSL cert + ServerSSL
  * Bypass on client cert failure - clientSSL cert + ServerSSL
  * Verified handshake - clientSSL cert + ServerSSL

## iRules

**Disable ICAP Respmode for reponses smaller then 1000 bytes. iRule is attached to ssloS\_Icap-t-4 in SSLO**

```
when HTTP_RESPONSE {

if { ( [HTTP::header exists Content-Length] ) and ( [expr { [HTTP::header Content-Length] <= 1000}] ) } {
            ADAPT::enable response false
      }
  }
```

**Log codes from DLP servers - connected to VS ssloS\_dlp\_req**

```
when RULE_INIT {
    set static::SyslogIP "10.1.1.228"
    set static::debug 0
}
when LB_FAILED {
    if { [active_members [LB::server pool]] > 0 } {
        if {$static::debug ne 0} {
            log local0. "LB to [IP::server_addr] is failed, reselect"
        }
        LB::reselect
    }
}
when ICAP_REQUEST {
    set http_host [HTTP::host]
    set client_addr [IP::client_addr]
}
when ICAP_RESPONSE {
    log $static::SyslogIP local0. "ICAP status code from DLP is [ICAP::status]"
    if {$static::debug ne 0} {
        log local0. "ICAP status code from DLP pool member [IP::server_addr] is [ICAP::status] for $client_addr is requesting $http_host"
    }
    if { [ICAP::status] == "503" } {
        if {$static::debug ne 0} {
            log local0. "Got 503 response from [IP::server_addr] and set it down"
        }
        LB::down
    }
}
```

## iApps

```
modify  sys application service sslo_sber_l3.app/sslo_sber_l3 strict-updates disabled
save sys config
```

## SSLO

## Docs

* All F5 SSLO documentation - <https://my.f5.com/manage/s/article/K71174564>
* Deployment guide - <https://clouddocs.f5.com/sslo-deployment-guide/#>
* Troubleshooting - <https://my.f5.com/manage/s/article/K26520133>
* Troubleshooting Guide - <https://clouddocs.f5.com/sslo-troubleshooting-guide/main/>
* Labs - <https://clouddocs.f5.com/training/community/sslviz/html/>
* iRules - <https://clouddocs.f5.com/api/irules/>
* API - <https://clouddocs.f5.com/api/>

\##Architecture

VM requirements min

* 80 GB - Thin Prov
* 4 CPUs
* 8 Gb RAM

It uses LTM + small piece of APM(authentication) It uses per-request auth policy (APM)

`Devices > Services > Service Chains`

The types of service devices are:

* Layer 2 Inline Devices
* Later 3 Inline Devices
* Inline HTTP Proxy (Transparent or Explicit)
* ICAP Device
* TAP Device

8 devices in a service max

Services:

* Inline (L2 or L3)
* ICAP
* Receive-only

Service is a pool in LTM terminology. Every device is a pool member\
For a pool you configure load balance method\
You also configure Health monitors for a pool\
Persistence profile(send all packets from the same IP to the same server) is used in Virtual server settings

Interception rule is a virtual server, one for TCP, one for UDP, one for Other

Security policy defines which traffic to allow or drop, which traffic to bypass or intercept and which service chain is used for traffic. And which traffic to decrypt\
Interception policy defines which traffic to intercept in general and on which interface. And then it goes to security policy

Service chain classifier rules determine which service chains receive traffic. It can be UDP or TCP.\
Each classifier has three filters that match the source IP address, the destination, and the application protocol. Filters can also overlap, so the best matching classifier determines the service chain for a specific connection. Finally, classifiers can reject a connection or allow it to bypass the service chain

First, accept a packet, then classification and only then decision: encrypt or not....\
Different types of traffic may flow through different chains...

SSL Orchestrator’s powerful classification engine applies different service chains based on context derived from:

* Source IP/subnet
* Destination IP/subnet
* An F5® IP Intelligence category subscription
* IP geolocation
* Host and domain name
* An F5 URL filtering category subscription
* Destination port
* Protocol

**SSL exemption**

* Guest VLANs
* Applications that use pinned certificates
* Trusted software update sources like those for Microsoft Windows updates
* Trusted backup solutions, such as a crash plan
* Any lateral encrypted traffic to internal services that should be exempted
* domain names
* URL categories

Note that SSL and TLS are used primarily with TCP-based protocols topologies. The TCP protocol selection creates the necessary architecture to perform decryption and re-encryption. UDP traffic is not decrypted but can be service chained. Other (non-TCP/non-UDP) is not decrypted and not service chained. This topology selection creates a routed outbound path for non-TCP/non-UDP traffic

### TIPS

<https://github.com/f5devcentral/sslo-script-tools/tree/main/internal-layered-architecture>

K33061373: Unable to open SSLO GUI with "Server Error" after loading UCS <https://support.f5.com/csp/article/K33061373>

K10053040: SSLO "peer HA verification response" Showing "Bad" Status

If you are running v14 and v15, try to restart restnoded and restjavad processes (workaround of BUG ID 835161)

```
bigstart restart restnoded restjavad
```

If it doesn't fix the issue, you may need to extract more memory. This memory is taken from TMM data plane and requires TMM restart

```
Add memory for mgmt
tmsh modify sys db provision.extramb value 2048

Increase Tomcat memory
tmsh modify sys db provision.tomcat.extramb value 512

restjavad extra memory
tmsh modify sys db restjavad.useextramb value true
bigstart restart restjavad

Show
tmsh list sys db provision.extramb all-properties
msh list sys db provision.tomcat.extramb
tmsh list sys db restjavad.useextramb
```

If the issue is still not resolved, try clicking "Reload Page" in `iApps >> Application Services >> Applications LX`

Disable read-only when device is connected to BIG-IQ

Once the RPM with a fix has been acquired, install it on the BIG-IP:

* Click iApps -> Package Management LX.
* Click on Import and select the RPM.
* Click Upload. This will install the selected RPM on the box.
* Verify the new SSLO package has been installed with expected version

To *disable* SSLO GUI's read-only mode, change the BIG-IQ monitor pool member value to 'Force Offline'

1. Browse to Pool Member location – Local Traffic > Pools > sslo\_bigiqMonitor > Members
2. Change the BIG-IQ monitor pool member value to 'Force Offline'

**Handshake errors**

If there are problems with protocol or ciphers then in logs we see `warning tmm[19484]: 01260013:4: SSL Handshake failed for TCP 141.101.182.254:443 -> 10.2.62.4:47642`

```
list /sys db log.ssl.level
modify /sys db log.ssl.level value debug
```

If option Bypass on handshake alert is enabled then we can see `warning tmm[19484]: 01260035:4: SSL Traffic bypassed due to handshake failure alert(40) for TCP 192.168.1.100:1617 -> 141.101.182.254:443`

**What to include in Bypass:**

* GOST cipher suite
* Rekaptcha - Google APIS
* Pinners
* Sites which require cert for auth

**Monitor amount of decrypted sessions**

We use stat for profile SSL server(or client, amount is the same) profile ssloT\_sber-sssl-vhf, `ltmClientSslStatCurNativeConns - OID`

**HA-sync script**

```
ha-sync -f -D F5_EKB_Cluster -H 100.108.19.35
```

where -D specifies device group name and IP address of peer device\
It is also possible to launch without -D option

**SSLO configuration freeze**

```
bigstart restart restnoded restjavad
```

**When SSLO drops connections from user to untrusted certificate site**

Disable strict updates

```
modify sys application service ssloT_sber_l3.app/ssloT_sber_l3 strict-updates disabled
```

* We go to Server Side SSL profile
* Untrusted Certificate Response Control set to Mask
* Another way is to add CA certificate to a list of trusted CAs
* It can be done in two ways

Add certificate in base64 format to the end of file /config/ssl/ssl.crt/ca-bundle.crt

```
touch /service/mcpd/forceload
```

Reboot - ?

**Create CA bundle**

* Add ca-bundle.crt to it
* Add new cert to it
* Check update now option in it, so it will appear in a list
* Choose new bundle in SSLO wizard or in SSL Server profile configuration

**Clear SSLO config**

Button in the GUI - deletes config on both devices

If does not work

```
clear-rest-storage -l
```

It should be done on both nodes

Also delete the following:

```
iapps > application services > Applications LX
```

Enable processing for ICMP

Send ICMP traffic to Palo Alto and then accept it back from PA

```
Create icmp-in virtual server:
	Source 0.0.0.0/0
	Destination 0.0.0.0/0
	Port - all
	Protocol - Other:1
	Type: performance Layer 4
	VLAN - internal
	Pool - Palo Alto
	Address Translation - disable
	
Create icmp-out virtual server
	Source 0.0.0.0/0
	Destination 0.0.0.0/0
	Port - all
	Protocol - Other:1
	Type: performance Layer 4
	VLAN - from_PA
	Pool - no
	Address Translation - disable
```

**Local API**

Through direct TMSH access to the BIG-IP, URLs can be added to a custom category. For example:

```
 tmsh create sys url-db url-category my-category default-action allow urls add { https://www.example.com/ { type exact-match } https://*.example.com/ { type glob-match } }

    tmsh modify sys url-db url-category my-category urls add { https://www.example.com/ { type exact-match } }

    tmsh modify sys url-db url-category my-category urls add { https://*.example.com/ { type glob-match} }
```

A custom category can also be enumerated:

```
 tmsh list sys url-db url-category my-category urls
```

**Mail and special protocols via SSLO**

SMTP via port 465 with SSL works without any additional virtual servers. Traffic is decrypted, but is seen in wireshark as pure TCP but contents is available. Gmail uses 465 with OAuth2 authentication

* IMAPs via port 993 work ok, decrypted. No special VS for it.
* POP3S - decrypted
* SMTPS over 465 port - works ok, decrypted, but Wireshark does not see SMTP headers

Special virtual servers(server speaks first protocols) are created for the following protocols:

* FTP - works ok
* FTPS - not tested
* IMAP - STARTTLS decrypted
* POP3 - not tested
* SMTP - 25 - used only between servers - works, starttls decryption not tested
* SMTP - 587 - never used - not tested

The SMTPS profile is introduced in BIG-IP 11.5.0 and provides support for the STARTTLS extension. To avoid a conflict between the SMTPS and Server SSL profiles, do not configure a Server SSL profile when an SMTPS profile is applied to the virtual server.

Также хочу обратить ваше внимание на то, что все клиентские программы начнут жаловаться на подмену сертификата, если в них предварительно не загрузить сертификат F5, которым подписываются все соединения. Например, Thunderbird автоматически импортирует СА сертификаты из системного хранилища, но с другими клиентами могут быть проблемы

**Verify gossip status and device status ( on both devices)**

```
restcurl /shared/gossip | jq '.status'
restcurl /shared/resolver/device-groups/tm-shared-all-big-ips/devices
```

## SSLO integration with Sandbox via ICAP

* This integration can and work fine
* Response ICAP mode is configured to send all HTTP replies to Sandbox
* ICAP virtual server TCP profile should be configured to increase idle timeout from 300 sec to 600 for heavy files
* File size limit can be configured via iRule, which is attached to ICAP virtual server
* What we send to Sandbox is configured using Content-Type field in HTTP and MIME types and local policy attached to ICAP Service in SSLO
* Be aware of a lot of garbage generated by Chrome and Windows updates - we can filter it in SSLO Security policy based on dst IPs and URLs via custom URL category
* Files which are downloaded via Javascript - can provide issues
* How to find out which request SSLO sends to Sandbox, more specifically Host, we need to launch on SSLO
* Sandbox in reply sends either block page and ICAP block code, or ICAP allow code plus HTTP reply(file) itself
* F5 sends to Sandbox the following:
  * RESPMOD icap\://10.2.55.113:1344/response ICAP/1.0\r
  * X-Client-IP: 192.168.1.20\r
  * HTTP request
  * HTTP response - file, html page, json...
  * In HTTP reply F5 looks at: http.content\_type: application/octet-stream

```
tcpdump -i 0.0 -A host 10.2.55.113 | grep Host

Host: 10.2.55.113:1344
Host: data-edge.smartscreen.microsoft.com
Host: 10.2.55.113:1344
Host: dl.google.com
```

10.2.55.113 - Sandbox IP\
This way we can know which domains to block to fight updates requests

List of domains which are used for updates:

* http\://\*.gvt1.com/
* <http://au.download.windowsupdate.com>
* <http://data-edge.smartscreen.microsoft.com/>
* <http://dl.google.com/>
* <http://edgedl.me.gvt1.com/>
* <http://r11---sn-n8v7znlr.gvt1.com>
* <http://www.google.com/> \*
  * The same for https

## SNI routing

Using SNI we can route traffic to a destination without having to terminate the SSL connection. This enables several benefits including:

* Reduced number of Public IPs
* Simplified configuration
* More intelligent routing of TLS traffic
* No SSL profile use

Using SNI Routing we can handle everything on a single virtual server / Public IP address. There are 3 methods for performing SNI Routing with BIG-IP

* iRule with binary scan
  * a. Article by Colin Walker code attribute to Joel Moses
  * b. Code Share by Stanislas Piron
* iRule with SSL::extensions
* Local Traffic Policy

Local policy:

* SSl extension - server name - is- any of - app1.example.com - at ssl client hello
* Forward traffic - to - pool - pool\_name - at SSL client hello time

## One connect

## Show commands

Show db variable

```
tmsh list sys db scheduler.splitplanes.ltm
```

`show sys version`

Show info about installed software

```
show /sys software status
```

Show model and hardware - Which SSL chips are installed?

```
show /sys hardware
```

List all processors with frequency

```
snmpwalk -v 2c -c public -On localhost | grep CPU
```

Show load of all CPU cores

```
tmctl cpu_info_stat -s 'cpu_id,five_sec_avg.ratio'
```

Show connections

```
show /sys connection type any
show sys conn cs-client-addr 10.1.10.6
```

When we delete all connections, BGP connections are included!!!!

Check if there is a PVA chip

```
tmsh show sys hardware  | grep -i pva.
```

We can disable PVA in Fast L4 profile

Performance

```
show sys performance system
show sys performance connection
show sys performance throughput
show sys performance all-stats
show /sys provision
```

Show default SSL ciphers

```
tmm --clientciphers DEFAULT
```

RST packets

Show reasons of RST packets

```
tmsh show /net rst-cause
reset-stats /net rst-cause
```

Enable logging of RST packets and reasons

```
modify /sys db tm.rstcause.log value enable
modify /sys db tm.rstcause.pkt value enable
```

## Active directory LDAP authentication

* The default admin account is always available regardless of what is configured for the Fallback to Local option

```
/var/log/secure 
```

when a fall back is invoked by the system:

```
notice httpd[1234]: pam_ldap: Auth server unavailable, trying fallback
```

Verify that server's certificate is trusted:

```
openssl s_client -connect ldapA.company.com:636 -CAfile /config/ssl/ssl.crt/My-Trusted-CA-Bundle.crt -debug -showcerts -verify 4
```

* Server configuration:
  * User directory - Active Directory
  * Port - 389
  * Directory Tree - DC=skynet,DC=ru
  * Scope - Sub
  * DN - CN=Philipp....
* Enable admin access only for certain user group
  * Create remote role group
  * Attribute string - memberOf=cn=F5,cn=Users,DC=skynet,DC=ru
  * Remote access - enabled
  * Assigned role - Administrator
* Disable access in LDAP server configuration
  * External users: Role - no access
  * Terminal access - disabled

## CLI

Export URLDB categories to file

```
tmsh list sys url-db url-category all-properties > urldb.txt
```

Import config to a system

```
load /sys config merge file /config/urldb.txt
```

Services

```
tmsh stop /sys service <service name>
tmsh start /sys service <service name>
tmsh restart /sys service <service name>
tmsh show /sys service <service name>
```

```
bigstart stop <service name>
bigstart start <service name>
bigstart restart <service name>
bigstart status <service name>
```

## EUD

* The End User Diagnostics (EUD) software is a set of diagnostic tests that provide reports about various components in the hardware unit
* It is recommended to install the latest version of EUD
* Install new EUD from im file

```
im <file_name>.im
```

EUD logs

```
/shared/log/eud.log
```

Show EUD version

```
eud_info
```

Command transactions - Opens batch mode within which you can submit a set of commands as a single transaction

```
create cli transaction
```

Insert many commands

```
submit cli transaction verify only
submit cli transaction
```

Verify config

```
load /sys config verify
```

Load config from terminal

```
load sys config from terminal merge 
```

## iRules

* The iRulesTM feature not only allows you to select pools based on header data, but also allows you to direct traffic by searching on any type of content data that you define
* Use them only when feature is unavaible in config
* They are complied into bytecode. So they are very fast
* It is a configuration object, like a pool
* They are applied to a virtual server
* Policies are preferable: iRules still provide greater flexibility, but as long as the needs are met in a policy, that should be the first choice
* If two iRules contain overlapping logic for the same event, the first iRule in the order wins, unless explicitly overridden by commands like event disable or return
* They are laucnched in position order but also event type influnces it, for example for event HTTP\_REUQEST first iRule is laumched then next one etc....
* If multiple iRules handle the same event (e.g., HTTP\_REQUEST), they are executed in the order in which they are attached to the virtual server
* If two iRules contain overlapping logic for the same event, the first iRule in the order wins, unless explicitly overridden by commands like event disable or return
* Priority: Lower numbered priority events are evaluated before higher numbered priority events - 500 is default
* Which CLIENT\_ACCEPTED will fire first?” If you have a virtual server with multiple iRules all making use of a particular event, there is no “first” or “last” occurrence of that event, it only happens once
* Regardless of how many iRules you have that call a given event, that event only ever fires once per connection/request, depending on the event
* The vast majority of iRules deployments that I’ve seen do not have specific priorities set. It can be useful, however, in cases where you want to ensure that a particular order of execution is achieved
* If you generate an HTTP response in either an iRule or LTM Policy, you must not query HTTP data after

Like in TCL:

* variabels
* conditions
* commands
* comments

Not like in TCL: Events

After you apply profiles, you get access to the events:

* TCP profile
* http profile
* ssl profile

Syntax:

```
when "event" {
}
```

iRules allow to:

* pass traffic to particular member of the pool (inclusding port and URI)
* logging
* rewrite payload

Example

```
when HTTP_REQUEST {
HTTP::redirect "https://[HTTP::host][HTTP::uri]"
}

#Basic variable creation in Tcl
set integer 5
set hostname [HTTP::host]

#Basic variable reference to retrieve and use the value stored in memory
if {$integer > 0) {
log local0. "Host: $hostname"
}
```

There are two main types of variables in iRules, local and global. Local are by default and in scope of session

```
#Standard variable reference
log local0. "My host is $host"

#Set variable to the output of a particular command using brackets []
set int [expr {5 + 8}]

#Directly manipulating a variable's value means no "$", most times
incr int

#Bracing can allow you to deliniate between variable name and adjacent characters
log local0. "Today's date is the ${int}th"
```

## Logging

Logging types:

* System > Logs > Configuration > Options - Log levels for different aspects of LTM, including SSL - everything goes to /var/log/ltm
* System > Logs > Configuration > Remote logging - Regular Syslog (via syslog- ng) - Everything from log files is sent - Logs to Syslog cannot be sent via Mgmt interface
* /var/log/apm - APM logs, SSLO logs - SSL Orchestrator > Logs > Settings + SSLO topology settings
* /var/log/audit - all admin actions + authentication
* Logs > Configuration > Audit logging > MCP Verbose
* System > Logs > Configuration > Log Publishers - High Speed Logging - if you enable this, add local syslog to publisher destination, or nothing will be saved locally

Show configured Syslog servers

```
tmsh list /sys syslog remote-servers
```

Modify levels

```
modify /sys syslog auth-priv-from warning
```

Show current syslog settings

```
tmsh list /sys syslog all-properties
```

Additional filtration via CLI:

```
modify /sys syslog remote-servers none
save sys config
edit /sys syslog all-properties
include "             
    filter f_remote_loghost {
        level(warning..emerg);
    };
    destination d_remote_loghost {
        udp(\"192.168.1.1\" port(514));
    };
    log {
        source(s_syslog_pipe);
        filter(f_remote_loghost);
        destination(d_remote_loghost);  
                  
    filter f_remote_loghost1 {
        match('/var/core/.*.bld');             
        level(notice..emerg);
    };
    log {
        source(s_syslog_pipe);
        filter(f_remote_loghost1);
        destination(d_remote_loghost);
    };
    "
```

K13333: Filtering log messages sent to remote syslog servers\
K40110244: How to send a specific log message to a remote syslog server

Enable debug for logging SSL errors

```
tmsh list /sys db log.ssl.level
modify /sys db log.ssl.level value debug

Set back
modify /sys db log.ssl.level value Warning
```

Reasons of handshake failure is available only in debug level

```
warning tmm3[17956]: 01260013:4: SSL Handshake failed for TCP 192.168.1.100:26034 -> 108.174.11.37:443
```

Enable Radius auth logging

```
tmsh modify /auth radius all debug enabled
tail -f /var/log/secure
tmsh modify /auth radius all debug disabled
```

### High speed logging

If you enable HSL, all logs sent to it, will not be sent to local logs, you have to create a separate HSL filter and send all required events to Local-syslog destination. Remote high speed logging sends logs directly from dataplane without using syslog-ng. It is faster.

1. Create a pool where we specify Syslog servers
2. Create Log destination with type Remote HSL and specify pool name
3. Create Log destination with type Remote Syslog and specify Remote HSL log destination and syslog format
4. Create Log publisher and add Remote Syslog destination there
5. Create Log filter, configure it and attach it to log publisher (Message ID is set without :)

### SSLO Per-topology log settings

* Per-Request Policy - logs events related to security policy processing. When set to Debug, this log facility produces an enormous amount of traffic, so it is recommended to only set this to Debug for troubleshooting. Otherwise the most appropriate setting is Error, which will only log error conditions.
* FTP - specifically logs error conditions for the built-in FTP listener when FTP is selected among the additional protocols in the Interception Rule configuration. The most appropriate setting is Error, which will only log error conditions.
* IMAP - specifically logs error conditions for the built-in IMAP listener when IMAP is selected among the additional protocols in the Interception Rule configuration. The most appropriate setting is Error, which will only log error conditions.
* POP3 - specifically logs error conditions for the built-in POP3 listener when POP3 is selected among the additional protocols in the Interception Rule configuration. The most appropriate setting is Error, which will only log error conditions.
* SMTP - specifically logs error conditions for the built-in SMTP listener when SMTP is selected among the additional protocols in the Interception Rule configuration. The most appropriate setting is Error, which will only log error conditions.
* SSL Orchestrator Generic - logs events related to generic SSLO processing, such as a summary of how a connection/flow was handled. If Per-Request Policy logging is set to Error, and SSL Orchestrator Generic is set to Information, only the connection/flow summary will be logged. If connection/flow summary logging is not required the most appropriate setting is Error, which will only log error conditions. The logs produced by the SSL Orchestrator Generic facility provide a summary of details during multiple stages of the client/server connection. The Information level of severity provides a single log message per-connection, summarizing connection properties, whether it was decrypted, and which Service Chain it was sent through. The Debug level of severity produces information at multiple stages while the connection is established and . An example of the logging that is produced by the SSL Orchestrator Generic facility can be seen below. In this example the severity was set to Debug, which includes log messages of all levels of severity, including Information:\
  May 5 12:11:49 sslo1 debug tmm\[11503]: 01c4ffff:7: /Common/sslo\_f5labs\_explicit.app /sslo\_f5labs\_explicit\_accessProfile:Common:2cd3ff97: /Common/sslo\_f5labs\_explicit.app /sslo\_f5labs\_explicit-in-t-4 CLIENT\_ACCEPTED TCP from 10.1.10.50\_64258 to 93.184.216.34\_443 L7 guess=https
* For the vast majority of troubleshooting cases the logging data from Per-Request Policy and SSL Orchestrator Generic (set to Debug and Information, respectively) are the most relevant. For ongoing connection summary logging to a system such as a SIEM, the SSL Orchestrator Generic log (set to Information) is usually the most relevant.

### SSLO errors in logs

All SSL/TLS handshake errors are in /var/log/ltm and are Warning and does not depend on SSLO configuration\
Most of them have SSL as a source in Log filter

GOST

* warning tmm2\[21553]: 01260009:4: 192.168.1.2:4387 -> 141.101.182.254:443: Connection error: ssl\_select\_suite:10065: alert(40) no shared ciphers
* warning tmm2\[21553]: 01260026:4: No shared ciphers between SSL peers 192.168.1.2.4387:141.101.182.254.443
* warning tmm2\[21553]: 01260013:4: SSL Handshake failed for TCP 192.168.1.2:4387 -> 141.101.182.254:443
* warning tmm5\[21553]: 01260035:4: SSL Traffic bypassed due to handshake failure alert(40) for TCP 192.168.1.2:4402 -> 141.101.182.254:443

Certificate

* warning tmm7\[21553]: 01260006:4: Peer cert verify error: certificate has expired (depth 0; cert /OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=\*.badssl.com)
* warning tmm7\[21553]: 01260009:4: 104.154.89.105:443 -> 10.2.62.2:61341: Connection error: ssl\_shim\_vfycerterr:4202: alert(45) certificate has expired
* warning tmm1\[21553]: 01260006:4: Peer cert verify error: self signed certificate (depth 0; cert /C=US/ST=California/L=San Francisco/O=BadSSL/CN=\*.badssl.com)
* warning tmm1\[21553]: 01260009:4: 104.154.89.105:443 -> 10.2.62.2:20580: Connection error: ssl\_shim\_vfycerterr:4202: alert(48) self signed certificate

Other

* warning tmm14\[26252]: 01260009:4: 100.64.45.21:58942 -> 17.57.146.136:5223: Connection error: ssl\_hs\_rxhello:10784: alert(70) unsupported version
* info tmm3\[26252]: 01220009:6: Pending rule /Common/sslo\_default.app/sslo\_default-in\_t \<CLIENT\_DATA> aborted for 100.64.35.0:60469 -> 17.57.146.133:443
* warning tmm11\[26252]: 01260035:4: SSL Traffic bypassed due to failed client certificate for TCP 100.64.38.230:57860 -> 194.186.207.152:443
* warning tmm12\[26252]: 01260009:4: 100.70.76.221:58746 -> 213.248.110.85:443: Connection error: ssl\_select\_suite:9984: alert(86) TLS\_FALLBACK\_SCSV with a lower protocol – клиент попытался понизить версию протокола
* warning tmm14\[26252]: 01260006:4: Peer cert verify error: unable to get local issuer certificate (depth 1; cert /C=RU/O=Kaspersky/CN=KSN Global Issuer CA) – не доверенный сертификат
* warning tmm11\[26252]: 01260009:4: 213.248.110.69:443 -> 100.70.76.221:58747: Connection error: ssl\_shim\_vfycerterr:4202: alert(48) unable to get local issuer certificate – не доверенный сертифика

### Connection summary for SSLO

/var/log/apm - For policy decisions. Most useful when troubleshooting problems with chains and services. If you want to get connection summary for each SSLO connection you need to configure SSL Orchestrator Generic to Information. All other is error. After this in /var/log/apm there will be logs.

They show app, IPs, ClientSSL options, ServerSSL options, URL, decryption status, service chain

```
Jun  8 15:06:16 sslo-1.sber.ru info tmm[19870]: 01c40000:6: /Common/sslo_Not_GOST.app/sslo_Not_GOST_accessProfile:Common:22daf270: /Common/sslo_Not_GOST.app/sslo_Not_GOST-in-t-4 Traffic summary - tcp 192.168.1.100:14515 -> 40.126.32.137:443 clientSSL: TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 serverSSL: TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 L7 unknown (login.live.com) decryption-status: decrypted duration: 180 msec service-path: ssloSC_Chain client-bytes-in: 421 client-bytes-out: 5298 server-bytes-in: 6574 server-bytes-out: 1127
```

For GOST traffic ServerSSL will be NA

```
Jun  8 15:03:35 sslo-1.sber.ru info tmm5[19870]: 01c40000:6: /Common/sslo_Not_GOST.app/sslo_Not_GOST_accessProfile:Common:018361e8: /Common/sslo_Not_GOST.app/sslo_Not_GOST-in-t-4 Traffic summary - tcp 192.168.1.100:14495 -> 141.101.182.254:443 clientSSL: TLSv1.3 TLS13-AES128-GCM-SHA256 serverSSL: NA NA L7 unknown (ssl.croinform.ru) decryption-status: decrypted duration: 12 msec service-path: ssloSC_Chain client-bytes-in: 649 client-bytes-out: 88 server-bytes-in: 179 server-bytes-out: 769
```

Unencrypted example:

```
Jun  8 15:16:53 sslo-1.sber.ru info tmm1[19870]: 01c40000:6: /Common/sslo_Not_GOST.app/sslo_Not_GOST_accessProfile:Common:f6c970f0: /Common/sslo_Not_GOST.app/sslo_Not_GOST-in-t-4 Traffic summary - tcp 192.168.1.100:14696 -> 217.69.139.200:443 clientSSL: NA NA serverSSL: NA NA L7 https (mail.ru) decryption-status: not-decrypted duration: 184986 msec service-path: ssloSC_Chain client-bytes-in: 85154 client-bytes-out: 219107 server-bytes-in: 216759 server-bytes-out: 83936
```

To send it to Syslog we need to add Log destination to Log publisher sys-sslo-publisher These logs appear in /var/log/apm because Log publisher sys-sslo-publisher is connected to access profile and local syslog is configured as destination for this log publisher! That is why they are not sent via regular Log Publisher, it should be connected to Access profile first

### Per-Request Policy logging

Per-Request Policy logging provides an in-depth view of the rule matching logic that is applied to each flow passing through SSL Orchestrator. The logging from this facility is very verbose, as can be seen from the example below, where a single HTTP GET request is sent to <https://www.example.com>. Per-Request Policy log data is sent to the APM log (/var/log/apm). As you look through the example log data, pay attention to the following:

* Each session has a unique identifier that you can filter on (ex. using grep), in this case it is: 3a9ebee8
* At the start of each session some basic client and server details are logged (ex. IPs and ports)
* Further into the session, additional flow details become available (look for Agent created variable name messages):
  * perflow\.category\_lookup.result.url, value: <https://www.example.com/>
  * perflow\.ssl.client\_cipher\_name, value: ECDHE-RSA-AES128-GCM-SHA256
  * perflow\.ssl.client\_cipher\_version, value: TLSv1.2
  * perflow\.ssl.server\_cipher\_name, value: ECDHE-RSA-AES128-GCM-SHA256
  * perflow\.ssl.server\_cipher\_version, value: TLSv1.2
  * perflow\.l7\_protocol\_lookup.result, value: https
  * perflow\.service\_path, value: ssloSC\_All\_Services
* Log messages indicate successful or unsuccessful evaluation of each rule, such as:
  * Following rule (Fail) from item (Pinners\_Rule) to item (Finance\_Bypass) indicates the Pinners Rule rule did not match
  * Following rule (Fail) from item (Finance\_Bypass) to item (ssloSC\_All\_Services) indicates the Finance Bypass rule did not match
  * This flow did not match the Pinners Rule or Finance Bypass so it was caught by the default "All Traffic" rule at the bottom of the Security Policy

Example Per-Request Policy log output:

```
May  4 13:53:03 sslo1 notice tmm2[11526]: 01490505:5: /Common/sslo_f5labs_explicit.app/sslo_f5labs_explicit_accessProfile:Common:3a9ebee8: SSLO Session
May  4 13:53:03 sslo1 info tmm2[11526]: 01870003:6: /Common/sslo_f5labs_explicit.app/sslo_f5labs_explicit_accessProfile:Common:3a9ebee8: Agent created variable name:perflow.client.ip.address, value: 10.1.10.50
```

## SSLO Troubleshooting

* Bypass rules with IPs should be on the top, because rules with categories provoke SSLO to connect to server to check the cert before bypassing
* Bypass based on URL category does not work for Anydesk, only via IP address, and no rules based on URL should be above

Site does not work via SSLO

* If site is bypassed, but server's CA is intrusted - it will not work
* Bypass on Handshake Alert - is enough for GOST traffic, it is not even required to add to bypass
* In browser identify which domains are used, besides main: Network in Developer Tools + 3rd party requests + Column Domain Name
* Via packet capture identify which IPs are used

```
tshark -T fields -e ip.dst -f "tcp and dst port 443 and src 10.10.10.1"
```

* Enable SSL debug logging
* Check /var/log/ltm for SSL errors
* Check if server certificate CA is in F5 bundle: check CAcert in browser without decryption and copy its CN:

```
cat /config/ssl/ssl.crt/ca-bundle.crt | grep "DigiCert Global Root CA"
```

* Check if server certificate is expired
* Check if certificate is pinned to client
* Enable Debug logs in SSLO and see /var/log/apm

### Check validity of server cert

```
openssl s_client -connect meetup.sberbank.ru:443
```

This command will show certificates, protocol and ciphers If F5 does not know this certificate, there will be a error:

```
verify error:num=20:unable to get local issuer certificate
verify error:num=21:unable to verify the first certificate
```

### SSL sequence during intercept

* CLient Hello from client to SSLO
* Client Hello from SSLO to server
* Server hello from Server to SSLO
* Server hello from SSLO to Client

### SSL sequence during bypass

* CLient Hello from client to SSLO
* Client Hello from SSLO to server
* Server hello from Server to SSLO
* Server hello from SSLO to Client - absolutely the same

## WAF

Source of knowledge:

* BIG-IP Application Security Manager: Implementations
* BIG-IP Application Security Manager: Getting Started
* BIG-IP ASM operations guide
* Succeeding with application security
* Creating a security policy automatically
* Working with BIG-IP ASM attack signatures
* Cloud docs labs
* Vulnerable apps: Juicy shop, Damn Vulnerable Web Application

AWAF:

* Bot protection
* API protection
* DoS protection
* Web scraping protection
* Brute force protection
* Data Safe (Fraud Protection Service) - saves login password on clients side - F5 adds javasrcipt to a form. Change password on user side in browser DOM model to random garbish. Change field names for password and user to garbish
* F5 recommends that most users create a security policy using the automatic method
* For some time it just monitors all requests, and adds them as legal, and then it is switched to enforce mode
* Manual mode is used in prod
* It supports positive model and negative model using signatures
* The logs in the GUI are stored in a local mysql database - Local Storage
* All logs: /var/log/asm

Configuration workflow

* Policy type: security or parent
* Policy template: includes all parameters, including signature set, server technologies, learning mode and all others
* Virtual server
* Application language - UTF8
* Enforcement mode: blocking or transparent
* Policy building learning mode - Automatic, Manual, Disabled

### Policies

* Policy best practise: <https://support.f5.com/csp/article/K07359270>
* Export asm attack signatures from CLI: <https://support.f5.com/csp/article/K99615376>

Policy types

* Security
* Parent

If app is under attack: `Rapid Deployment + disabled staging + Blocking mode`

Limits

* URL length - `Security > Options > Application Security > Advanced configurations > System Variables > ecard_max_http_req_uri_len` > 7168 > restart > `restart /sys service asm`
* Allow URLs - `Security > Application Security > URLs`
* White list IPs: `Policy > IP address exception` - do not forget routeing domain

Signatures

* Staging - all signatures in it, when policy is created. It is a primary defense mechanism against false positives. In staging request will never be blocked even when policy is in blocked mode
* Enforcement readiness period
* During this period signatures are in staging.

Templates - includes all policy options + signatures, we can make from one template to another

* Rapid deployment - what should not be in web app only
* Fundamental - what should not be in web app + elements of web app
* Comprehensive - very large and includes everything about app
* Passive - on mirrored traffic, signalling only, no blocking

Enforcement mode

* Transparent
* Blocking

Violations

* RFC vialotaions - Format of HTTP requests
* Access violations - blocked access to web application
* Length violations - too long URL
* Cookie violations
* Negative security violations - attack signatures

Integrating violations

* Accept - accept learning suggestion - update policy - Accept is available from Event log as well, it is just a shortcut to Traffic Learning page
* Delete - deletes logged violation - does not ipdate security policy - continues to generate learning suggestion
* Ignore - Deletes learning suggestion - Updates the ignored items list - does not continue to generate learning suggestions

What does it check?

* RFC compliance
* HTTP length limits
* Enforce valid types
* Enforce valid URLS
* Check for valid parametres
* Max length for parametres
* Attack signatures

Configuration

* Policy Name > Policy type(Standalone or parent) > Policy template
* Create a Virtual Server with HTTP and SSL profile
* Create Security Policy > Assign it to Virtual Server, Local traffic policy is created automatically
* Create a logging profile, assign it to Virtual server
* If learning mode is enabled for policy and attack is detected, then system makes a suggestion what to do with it. If learning mode is disabled, then no suggestions

### Used sections in GUI

We use only these sections

* Overview
  * Summary - attach logging profile, it is attached to VS, not to policy
  * Analytics
  * OWASP check
* Guided configuration - iapp to generate config
  * Dashboard, undeploy, export
* Application security
  * Policy building
    * Traffic learning- suggestions - accept or ignore - violation categories - 5 ratings of violations
    * Learning and blocking settings -
  * File types
  * URLs
  * Parametres
  * Sessions and logins - auth for particular URLS
  * Headers, cookies, methods
  * CSRF - add tokens to links
  * Audit > Log - we can see here last changes to policy
* DoS protection > Protection profiles
* Event logs - we can accept here - just a link to traffic learning
  * Logging profiles - blocked, illegal, all. Illigal is mostly used in prod.
  * DoS - DoS events
* Options - view all attack signatures, all policy templates, config sync

Any violation of policy is a violation

Possible request statuses:

* Unblocked - ?
* Blocked
* Illegal - ?
* Legal
* Legal, but triggered violation - ?

To be blocked all 3 should be enabled:

* Policy in blocking mode
* Violation is not in staging
* Block checkbox is enabled on violation

The following entities can be subject to staging:

* File types
* URLs
* Parameters
* Cookies
* Attack signatures
* Redirection domains

Enforcement readiness period - by default 7 days, reset to zero after configuration change or violation triggered

Learn, alarm, block

* Learn - learn suggest appears
* Alarm - request is logged
* Block - request is blocked, if not in staging and policy in blocking mode

### Learning process

* What is learning: policy building by whitelisting entities: File types, URLs, Parametres, Cookies, redirection domains
* What is learning: policy building by false positive elimination: attack signatures
* `Choose Learning mode > Choose enforcement mode > Choose Application language > Choose server technologies > Choose enforcement readiness period`

We study

* Files
* Parametres
* URLs

Learning mode

* Automatic - when suggestion reaches 100% it is automatically accepted
* Manual - we get a lot of suggestions and decide by our-self accept it or not
* Disabled - we receive no suggestions

Policy builder learning speed (number of samples required for decision) in percents for every suggestion

* Fast
* Medium
* Slow

Automatic learning mode

* All traffic is allowed
* Policy builder adds policy elements, we can inspect them
* System enables enforcement mode

Principles

* When we accept a suggestion to Ignore SQL injection, system add override for particular signature
* When using untrusted requests, there needs to be several requests from several unique sources over time to see an increase in the learning scores
* When score is 100% suggestion is accepted in Automatic mode, and just wait in manual mode
* Learning speed defines how many requests it needs to gather and in what period
* Staging allows us to collect stats about something
* Example: Paramter size 100 Kb arrives, learning suggestion arrives, if we choose accept only, than it will this parameter with 100 Kb. In the future it will block all parametres larger than 100 and show learning suggestion as well
* If we choose Accept and staging, than if we get larger than 100, it will not be blocked, and learning suggestions appears to add 102 for example
* Enforcement readiness period - 7 days nothing bigger than 100 Kb should arrive - only than staging is over
* If something arrives on a 3d day, counter starts from zero
* Policy building process - this is where speed of learning can be configured custom
* While the different file types and parameters are still in staging, the security policy is not yet stabilized

### Policy block

* Get support ID
* Determine partition
* Determine virtual server
* Determine security policy
* Analyze the logs
* Accept suggestion or reconfigure policy
* Consider source IP if you search based on URL or blocked state
* If manual URL testing does not show support ID, it does not mean anything, it can be blocked because of parametres - so search in logs based on URLs

### Data Guard

* Security > Application Security > Policy Name > Advanced Protection > Data Guard
* Choose a policy to enable it for
* Credit card numbers
* US social security numbers
* Ignore URLs in list
* Enforce URLs in list
* Data Guard - masks Credit card numbers and any custom patterns

## Velos

* System controllers (2)> Blades > Partitions > Tenants
* System controllers, partitions, tenants has its own mgmt IP, (the same subnet)backup
* In system controllers we upgrade controller OS, backup controllers, create partitions
* In partition we backup config, upload images, create vlans, configure interfaces and LAGs, create tenants, configuring VLANs, CPU, disk, memory and OS version for it
* Tenant type: BIG-IP and BIG-IP next
* We create a tenant inside a partition
  * Image
  * Slots
  * Vlans
  * CPU
  * Disk size
  * Memory
* Partitions are created on system controllers

## Monitoring

### Throghput

* Throughput historical data per VS is not available
* We can see only total Bits in and Bits out in VS stats
* Throughput historical data is avalable only for whole device
* `tmsh show sys performance throughput detail historical`
* bigtop tool can show throughput per VS
* It show total amount of bits IN/OUT + conenctions since last reset
* Plus it shows IN/OUT bits during last 4 seconds - controllable
* `bigtop -bytes -n -delay 1 -vips 10 | grep 172.22.48.36:8443 > test.log`
* Another option: `while [ 1==1 ]; do bigtop -bytes -nosort -n -vips 10 -nodes 0 -once |grep "10\.254\.254\.10"; sleep 2; done`
* After this, using text file we can build a graph
* Also historical throughput is available via SNMP polling and then calculating delta

## Logs

* `zcat /var/log/ltm.8.gz | grep "dom-prod-pdt" | less`

## GTM DNS

* Distribution across geographically distributed data centers
* GTM works by responding to DNS requests, making it possible to direct users to the closest or best-performing server
* GTM checks factors such as network latency, server availability, and geolocation to return the IP of the optimal data center

### Integration with DNS infrastructure

* Special zone is created: z2.example.com
* CNAME is created for the host in main zone: [www.example.com](http://www.example.com) > [www.z2.example.com](http://www.z2.example.com)
* NS servers for z2 zone are GTM servers
* Client asks GTM about cname and gets IP of one of the LTMs, which are in different data centers

### Architecture

`Virtual Server (IP, Service, monitor) > Server > Pool > Wide IP`

* Listener is a separate object: on what VLAN and IP accept DNS requests, this IP is specicifed as NS server for zone
* Listener accepts a DNS request and based on domain name sends it to proper Wide-IP
* Wide-IP sends it to one of the virtual server from the assosiated pool
* Several pools can be in one Wide IP, to provide redundancy betwewen data centers
*

Process:

* A client queries [www.example.com](http://www.example.com).
* GTM:
  * Evaluates the Wide IP ([www.example.com](http://www.example.com))
  * Looks at the associated pool (web\_pool)
  * Selects a healthy virtual server (192.168.1.10:80 or 192.168.1.11:80) based on the load-balancing method
  * Resolves the DNS query with the selected server's IP.

### Listener

* `Delivery > Listeners`
* Destination address
* VLANs
* UDP or TCP
* DNS profile - many DNS options + logging profile
* SSL profile

### Data centers

* `DNS > GSLB > Data Centers`
* Prober preference - inside or outside data center
* Prober fallback - which prober to use if main fails
* Inside Data Center:
  * Servers
  * Devices
  * Virtual Servers
  * Links - Used in Link Load Balancing scenarios to distribute traffic across multiple internet connections

### Servers

* Represents a logical grouping of virtual servers running on a device
* `DNS > GSLB > Data Centers > Servers`
* For every server we configure virutal servers and devices
* Product: BIG-IP, Generic Load balancer....
* `Data center`
* Prober preference
* Prober fallback
* BIG-IP system `devices`: Name + IP adddress - Represents a physical or virtual BIG-IP system or an external server. GTM tracks its overall health. GTM needs to monitor the device to track the status of all virtual servers running on it + automatically discover all virtual servers running on it + Health Monitoring at the Device Level
* Health monitors - system uses to determine whether it can use this server for load balancing
* iQuery options - ?
* Virtual server discovery - ?
* Virtual servers - Represents an individual service (IP + Port + Monitor) running on a server

### Wide IP

* Wide IP name - defines on which DNS request this Wide-IP will react
* Type of DNS record
* iRules
* Load balance method
  * Global Availability
  * Ratio
  * Round Robin
  * Topology - The system selects a pool based on topology information in the incoming LDNS request
* Persistence
* Pool list
* Step 1: Define Data Centers `GTM > Configuration > Data Centers` - name and location
* Step 2: Define Servers for Each Data Center - `GTM > Configuration > Servers` - IP address and resource type
* Step 3: Configure Virtual Servers (Web Servers) within Each Data Center - Virtual Servers are added inside Servers configuration
* Step 4: Create Pools for Load Balancing - `GTM > Configuration > Pools > New Pool`
* Step 5: Create Monitors for Health Checks - `GTM > Monitors > Create New Monitor`
* Step 6: Define a Wide IP for [www.globalsite.com](http://www.globalsite.com) - Assign the DNS pools (created in Step 4) for New York, London, and Tokyo to this Wide IP

## URL Categories

* Disable decryption based on URLS and categories
* Categorization input:
  * Use HTTP URI (cannot be used for SSL Bypass decisions) - For HTTP traffic, this option specifies performing a URL-based lookup
  * Use SNI in Client Hello (if SNI is not available, use Subject.CN) - For HTTPS traffic, this option specifies performing a host-based lookup
  * Use Subject.CN in Server Cert - For HTTPS traffic, this option specifies performing a host-based lookup. (This option is not for use in a reverse proxy configuration.)
  * Use HTTP Connect Hostname - For connections that are passing through an upstream proxy, this option uses information from the HTTP Connect header and matches only the hostname. The Category Lookup agent functions only on the transparent HTTP virtual servers and fails if the policy is attached to explicit HTTP virtual servers
* Browser adds SNIs to all requests
* URLs must be properly formatted. SSL Orchestrator expects URL entries in the “scheme://fully-qualified-domain-name/” format. For example:
  * <https://www.siterequest.com/>
  * <http://www.siterequest.com/>
* Wildcard URLs are also acceptable here using glob match patterns. For example:
  * https\://\*.siterequest.com/
  * https\://\*.gov/
* Slash at the end everywhere!!!!!
* The default action option in a custom category is not relevant to SSL Orchestrator
* URL filters are not relevant to SSL Orchestrator
* There are two options when provisioning the URL database:
  * Secure Web Gateway (SWG) – This option downloads the entire database and contains full URL paths for some sites. An encrypted session does not expose URL paths, just the intended host via Server Name Indication (SNI) value in the TLS handshake Client Hello message and certificate subject or SAN value. Therefore, to make TLS intercept or bypass decisions, SSL Orchestrator only needs the hostname value in the database. It is acceptable to enable this option, but it incurs additional memory and CPU overhead for the quantity of information that it does not use
  * URLDB Minimal (URLDB) – This option downloads only the host information and consumes a fraction of the CPU and memory of the full database. This is the recommended option
* Restart service `tmsh restart sys service urldbmgrd`
* Launch immediate update `tmsh modify sys url-db download-schedule urldb download-now true`
* URL updates - Can take up to 2 hours and a lot of resources
* If URL categories cannot be dowloaded from Websense: `/var/log/urldbmgr-trace.log`
* IP intelligence log file `/var/log/iprepd/iprepd.log`

## APM

* No undo, is good idea to copy policy before edit
* If we use Secure cookie, it will add word "Secure" to session cookie and this policy will only work with HTTPS virtual server
* Session cookies are randomly generated
* Fallback - exit
* Policy have to be applied
* Boxes are agents or items
  * OTP agent
  * email agent
  * Logon page agent
  * Authentication agent
  * Logging agent
* TCL syntax can be used in irules and branch rules for policy

### Per request policy

* AskF5 Home Knowledge Center BIG-IP Access Policy Manager: Visual Policy Editor Per-Request Policy Item Reference
* Access policy or per session policy
* The access policy runs when a client initiates a session. Depending on the actions you include in the access policy, it can authenticate the user and perform group or class queries to populate session variables with data for use throughout the session. It must also specify the SWG scheme to apply to the session
* After a session starts, a per-request policy runs each time the client makes an HTTP or HTTPS request
* A per-request policy must provide the logic for determining how to process web-bound traffic. It must determine whether to allow or reject a URL request and control whether or not to bypass SSL traffic
* An access policy and a per-request policy are both specified in a virtual server
* Per-request policy can be added only after per session
* Per request policy and per session policy have the same collection of agents
* When we create per session policy we choose its type, it regulates available agents
* Per session policy requires apply policy
* Per request policy changes immediately
* Per session policy is usually used for authentication
* Per request is usually used for checking URLS, for example
* About Session Check - This agent, used primarily by SSLO, is used to check whether a session exists. If no session exists, the agent creates a perflow variable with a redirect URL to the captive portal virtual server.
* About Service Connect - This agent, used primarily by SSLO, allows you to connect to SSLO services that were previously configured. Service Connect provides the option to attach a Connector profile to the virtual server to enable service chaining in a per-request policy. In connector profile we specify only virtual server
* About SSL Bypass Set - The SSL Bypass Set item provides a read-only element, Action, that specifies the Bypass option. For an SSL Bypass Set item to be effective, the client and server SSL profiles on the virtual server must enable SSL forward proxy and SSL forward proxy bypass; the client SSL profile must set the default bypass action to Intercept; and the SSL Bypass Set item must occur in the policy before any items that process HTTP traffic
* About SSL check - An SSL Check determines whether the protocol of the request is HTTP or HTTPS. It provides two default branches: HTTPS and fallback. Use the SSL Check early in a per-request policy to process HTTPS traffic before processing HTTP traffic
* Add log record after URL is blocked based on Category - `Access > Per Request Policy > Edit: add General Purpose Logging action:`

```
URL was blocked: %{perflow.category_lookup.result.url} Category: %{perflow.category_lookup.result.categories} Client IP: %{perflow.client.ip.address}
```

* We can use here Perflow and Subsession Variables

## Tshark

Show chosen cipher suites from particular server in ServerHello

`tshark -Y "ssl.handshake.type == 2" -V -i vlan1509 src 192.168.21.105 | grep 'Cipher Suite'`

* 192.168.21.105 - Server IP
* -Y "ssl.handshake.type == 2": Filters only ServerHello packets
* -V: Provides a detailed view of the packet's content. If you only need a summary, you can omit -V

## BIG IQ

* One BIG-IQ is Master
* One BIG-IQ is Standby
* Cluster of DCD
* Remote storage for DCD
* Managing: Upgrading, Disk, CPU, iHealth, Change management, Cert management
* Licensing
* Statistics - AVR on Big-IP is required
* Monitoring
* Role Base Access Control

Three types (choose on setup stage):

* BIG-IQ Centralized Management (CM)
* BIG-IQ Data Collection Devices (DCD)
* BIG-IQ License Manager

Logs are collected only for

* APM
* DoS protection
* Fraud Protection
* IPSec
* Network Security (AFM)
* Web Application Security (ASM)

When you add a device you choose services to configure centrally:

* LTM
* APM
* ASM
* FPS
* AFM
* SSM
* DNS
* SSLO

And you also choose which stats to monitor:

* Device
* LTM
* DNS
* AFM

What it allows to monitor(charts):

* CPU
* Memory
* Interface
* Disk
* Connections
* Throughput
* LTM(Virtual servers, HTTP, TCP, irules, pools)
* SSLO

HA

* Primary and secondary
* Promote to primary is manual, no automatic failover
* Config synchronization every 30 sec
* Keep latency between elements in a BIG-IQ HA configuration within 75ms
* You can set up BIG-IQ in an auto failover configuration or a manual failover configuration
* When you create a cluster, standby is completely deleted
* Sync config every 30 secs
* Restore only the active BIG-IQ in a high availability (HA) configuration
* To recover the standby BIG-IQ in an HA configuration, synchronize the configuration from the active BIG-IQ after you restore it. In the unlikely event that the active and standby BIG-IQ systems fail, use the backup to restore the active BIG-IQ and then synchronize with the standby BIG-IQ

License

* To use a BIG-IQ VE to manage BIG-IP devices, you need a license
* To use a BIG-IQ VE as a license manager, you do not need a license
* To use a BIG VE as a data collection device (DCD) you do not need a license
* If you are installing and configuring a BIG-IQ DCD on a BIG-IQ 7000 Platform, you need a license

### Network

For production use, F5 recommends a minimum of two interfaces.

1. Management - separate network
2. Discovery subnet to communicate with Big-IP and DCD, discovery address is configured during initial setup both on DCD and CM as a self-ip. Discovery address is also used to communicate between primary and secondary CMs. When we add Standby CM we should specify Discovery address of CM2 and all communications will go via Discovery address of CM1
3. Listener subnet - BIG-IP send logs to DCD - the same as discovery network, configured when we add DCD to CM
4. Cluster subnet - DCD communicate between each over - This is configured as self ip and then specified during adding DCD to CMFor production use, F5 recommends a minimum of two interfaces

Discovery адрес настраивается на CM во время начального Wizard, на BIG-IP и DCD настраивается просто в виде отдельного интерфейса (с соотвествующеми маршрутами), которые потом указываются при добавлении в CM. Listener адрес получается нигде отдельно не настраивается и совпадает с Discovery на DCD(это не стыкуется с документацией)? Cluster адрес для DCD задается во время добавления DCD в CM в виде Data Collection Address? При этом разделение L3 хопами возможно для Discovery и Listener, а Cluster сеть должна быть одной и тойже для всех DCD и CM? - Да

### Clean installation

Clear BIG-IQ to factory defaults - license is alive, mgmt is alive, masterkey

```
clear-rest-storage -d -l
```

-l - restjavad log files delete -d - system config delete

Full upgrade with cleaning everything, done via USB disk and console - settings and license is gone

<https://support.f5.com/csp/article/K33432934>

* To create a USB drive we mount ISO file in linux and then launch mkdisk script
* Script is on Perl and has many dependencies. Better to use Fedora or CentOS
* Script ends with errors
* Methods for BIG-IP are acceptable as well
* <https://support.f5.com/csp/article/K13117#local>

To perform clean installation without USB

```
image2disk --format=volumes --nosaveconfig /shared/images/BIGIP-13.0.1-0.0.3.iso
```

### CM

* Configuration snapshots back up the settings for configuration objects that reside on your managed BIG-IP devices. With them you can do:
  * Deploy the preserved configuration to a managed device
  * Restore the BIG-IQ Centralized Management device's current configuration to the preserved configuration
  * Compare the preserved configuration to the BIG-IQ device's current configuration to see what has changed
* Snapshots are available for the following modules: Access, DNS, Fraud, LTM, Network Security, Shared security, WAF
* If you are restoring a snapshot for Local Traffic & Network, Network Security, or Web Application Security, you can select specific objects to restore. This process is called partial restore
* If you do make changes locally directly on the BIG-IP device, you must re-import the BIG-IP device's configuration to resolve those changes with the BIG-IQ working configuration. If you do not re-import the configuration, a subsequent deployment of the configuration from the BIG-IQ will overwrite your local changes on the BIG-IP device
* If you made a change directly on BIG-IQ, you need to rediscover and reimport configuraton

### CLI

Add static route

```
tmsh
create net route 10.10.22.0/24 gw 30.30.30.158
list net route
save /sys config
```

Configure trunk

```
create /net trunk data interfaces add { 1.3 1.4 }
modify /net trunk data lacp enabled
modify /net vlan Discovery interfaces add { data }
list /net trunk data
show /net trunk
```

BIG-IQ does not see reactivated license on BIG-IP

```
bigstart restart restjavad
```

### DCD

* Logs are sent to DCD and then retrieved from CM
* DCDs are combined into a cluster
* On CM we add DCDs to a logging Group
* On DCD there are no options, only system settings, we do not configure on it anything
* Each DCD is in a zone, and Big-IP is in a zone, it allows to configure on which DCD to send logs
* The total number of DCDs should be an even number so that they can be split evenly between the data centers. This conformation makes it easier to configure zones
* For optimum performance, F5 recommends that the latency in the connection between any two objects in a DCD cluster be no more than 75 ms
* The DCD cluster logic that governs the distribution of data between your DCDs identifies one node in the cluster as the master node. The master node monitors the cluster health and manages the cluster operation. It is elected by the cluster, and can reside on any node. (The BIG-IQ system, however, does not store any data.) If a master node goes down, a new master is elected from among all the nodes in the cluster
* Because the underlying Elastic Search (ES) cluster already replicates both event logs and analytics data across the entire DCD cluster, you don't need snapshots to prevent loss of data, except in the case of catastrophic failure
* On the External Storage & Snapshots screen, you can restore from the last known good snapshot. However, you cannot restore from previous snapshots
* DCD snapshots (discussed here) back up the alert, event, and analytics data collected by your DCDs
* By default, the UCS file is saved to the /shared/ucs\_backups
* Files, uploaded to UCS folder are not shown in GUI, to restore them use command: `load /sys ucs /shared/ucs_backups/test_DCD-1.sber.ru_20210407142851.ucs no-license; restart /sys service restjavad`
* Data from the chosen snapshot overwrites the data on the DCD. Any data collected after the chosen snapshot was created is not retained
* If CM looses connection with DCD, Analytics is not available on CM any more
* BIG-IP device initiates a connection to the BIG-IQ DCD to send statistics data - port 443
* If the AVR process cannot connect to the first DCD, it tries a second one, if configured, and so on
* The BIG-IQ DCD still initiates a connection to the BIG-IP device to periodically retrieve event data

DCD UCS includes:

* System-specific configuration files
* License
* User account and password information
* SSL certificates and keys
* Master Key

Reset DCD configuration on CM and keep elastic search data

```
reset-data-collection-cluster -es
```

If you do it on CM cluster, first disassemble cluster on both devices

```
ha_reset <local discovery address>
```

Reset DCD configuration on CM and delete ellastic, system conf(except mgmt int), restjavad log files

```
reset-data-collection-cluster -ld
```

## GOST

Do not terminate SSL requests with GOST ciphers and forward them to Palo ALto without decryption

```
when CLIENT_ACCEPTED { 
    TCP::collect 
} 
when CLIENT_DATA { 
    binary scan [TCP::payload] cSS rtype sslver rlen 
    if { $rtype == 22 } { 
        #Collect rest of the record if necessary 
        if { [TCP::payload length] < $rlen } { 
            TCP::collect $rlen 
        } 
        #skip record header and random data 
        set field_offset 43 
        #set the offset 
        binary scan [TCP::payload] @${field_offset}c sessID_len 
        set field_offset [expr {$field_offset + 1 + $sessID_len}] 
        #Get cipherlist length 
        binary scan [TCP::payload] @${field_offset}S cipherList_len 
        #Get ciphers, separate into a list of elements 
        set field_offset [expr {$field_offset + 2}] 
        set cipherList_len [expr {$cipherList_len * 2}] 
        binary scan [TCP::payload] @${field_offset}H${cipherList_len} cipherlist 
        set clist [list] 
        for { set i 0 } { $i < [string length $cipherlist] } { incr i 4 } { 
            lappend clist [string range $cipherlist $i [expr {${i} + 3}]] 
        } 
        set cliststr [join $clist ","] 
        #log local0. "Client: [IP::client_addr] attempts SSL with ciphers: $cliststr" 
        if {($cliststr contains "ff85") || ($cliststr contains "0081")} { 
        #log local0. "ssl disabled" 
        #set disable_ssl 1 
        SSL::disable serverside 
        SSL::disable 
        HTTP::disable 
        #ASM::disable 
        #snat none 
        #Edit pool name 
        pool gost-gw-FCOD-pool_7443_via_gre 
        #disable processing of all subsequent irules
        event disable all
        } 
    } 
    TCP::release 
}
```

GOST suites in Wireshark

```
Cipher Suite: Unknown (0xff85)
Cipher Suite: TLS_GOSTR341001_WITH_28147_CNT_IMIT (0x0081)
```

## Steering iRule

```
## SSL Orchestrator Use Case: Internal Layered Architecture - Client-Facing Switching iRule
## Version: 2.2
## Date: 2021-07-19
## Author: Kevin Stewart, F5 Networks
## Configuration: see SSLOLIB iRule for build instructions

## Set a default topology assuming no other matches (d not edit)

when CLIENT_ACCEPTED  {
    call SSLOLIB::target $static::default_topology 
}

when FLOW_INIT {
    
    if { [call SSLOLIB::DSTPORT PORT:21] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-ftp-4" "FTP" ; return }
    if { [call SSLOLIB::DSTPORT PORT:990] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-ftps-4" "FTPS" ; return }
    if { [call SSLOLIB::DSTPORT PORT:143] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-imap-4" "IMAP" ; return }
    if { [call SSLOLIB::DSTPORT PORT:110] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-pop3-4" "POP3" ; return }
    if { [call SSLOLIB::DSTPORT PORT:25] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-smtp25-4" "SMTP" ; return }
    if { [call SSLOLIB::DSTPORT PORT:587] } { call SSLOLIB::target_ssf "/Common/sslo_default.app/sslo_default-smtp587-4" "SMTPS" ; return }
}


#####################################################
## EDIT BELOW THIS BLOCK ############################
#####################################################
when RULE_INIT {
    ## User-defined: DEBUG logging flag (1=on, 0=off)
    set static::SSLODEBUG 0

    ## User-defined: Default topology if no rules match (the topology name as defined in SSLO)
    set static::default_topology "default"

    ## User-defined: URL category list (create as many lists as required)
    set static::URLCAT_Finance_Health {
        /Common/Financial_Data_and_Services
        /Common/Health_and_Medicine
    }
    set static::URLCAT_bypass {
        /Common/Hard_Bypass
        }
}
when CLIENTSSL_CLIENTHELLO {
    ## Do not edit
    set cmd "catch { HTTP::disable }" ; eval ${cmd}
    
    ## Set local sni variable (for logging)
    set sni ""

    ## Standard certificate Pinners bypass rule (specify your bypass topology)
    #if { [call SSLOLIB::SNI CAT:/Common/sslo-urlCatPinners] } { call SSLOLIB::target "bypass" ${sni} "pinners" ; return}


    ################################
    #### SNI CONDITIONS GO HERE ####
    ################################
    #if { [call SSLOLIB::SRCIP IP:10.1.0.0/16] } { call SSLOLIB::target "bypass" ${sni} "SRCIP" ; return }
    #if { [call SSLOLIB::SRCIP DG:my-srcip-dg] } { call SSLOLIB::target "bypass" ${sni} "SRCIP" ; return }

    #if { [call SSLOLIB::SRCPORT PORT:5000] } { call SSLOLIB::target "bypass" ${sni} "SRCPORT" ; return }
    #if { [call SSLOLIB::SRCPORT PORT:1000-60000] } { call SSLOLIB::target "bypass" ${sni} "SRCPORT" ; return }
    
    #if { [call SSLOLIB::DSTIP IP:93.184.216.34] } { call SSLOLIB::target "bypass" ${sni} "DSTIP" ; return }
    if { ( [call SSLOLIB::DSTIP DG:Bypass_DG] ) or ( [call SSLOLIB::SNI CAT:$static::URLCAT_bypass] ) } { call SSLOLIB::target "bypass" ${sni} "SNIDGGLOB" ; return }
    
    #if { [call SSLOLIB::DSTPORT PORT:443] } { call SSLOLIB::target "bypass" ${sni} "DSTPORT" ; return }
    #if { [call SSLOLIB::DSTPORT PORT:443-9999] } { call SSLOLIB::target "bypass" ${sni} "DSTPORT" ; return }
    
    #if { [call SSLOLIB::SNI URL:www.example.com] } { call SSLOLIB::target "bypass" ${sni} "SNIURLGLOB" ; return }
    #if { [call SSLOLIB::SNI URLGLOB:.example.com] } { call SSLOLIB::target "bypass" ${sni} "SNIURLGLOB" ; return }
    
    #if { [call SSLOLIB::SNI CAT:$static::URLCAT_bypass] } { call SSLOLIB::target "Moscow" ${sni} "SNICAT" ; return }
    #if { [call SSLOLIB::SNI CAT:/Common/Bypass] } { call SSLOLIB::target "Moscow" ${sni} "SNICAT" ; return }
    
    #if { [call SSLOLIB::SNI DG:my-sni-dg] } { call SSLOLIB::target "bypass" ${sni} "SNIDGGLOB" ; return }
    #if { [call SSLOLIB::SNI DGGLOB:my-sniglob-dg] } { call SSLOLIB::target "bypass" ${sni} "SNIDGGLOB" ; return }

## To combine these, you can use smple AND|OR logic:
    #if { ( [call SSLOLIB::DSTIP DG:my-destip-dg] ) and ( [call SSLOLIB::SRCIP DG:my-srcip-dg] ) } { call SSLOLIB::target "bypass" ${sni} "SNIDGGLOB" ; return }
```

## Add/del/list URL for custom BIG-IP

* syncs cluster + checks if all commands are successful
* Скрипт завязан на основную ноду
* При удалении адреса нужно прописывать маску

```
!/bin/bash
## F5 Custom URL Category Update Script
## Description: provides options to add URLs, delete URLs, and list the URLs in an existing custom URL category
## Version: 1.0
## Requires: bash, curl, jq
## 
## Syntax:
##
##		Valid regions: MSK, SPB, SMR, EKB, NSK
##
##      To Add URLs:
##      Command:    url_custom.sh add <category> <URL> <[exact-match|glob-match]> <region>
##      Examples:   url_custom.sh add MY_CATEGORY https://www.example.com/ exact-match NSK
##                  url_custom.sh add MY_CATEGORY https://*.foo.com/ glob-match EKB
##
##      To List URLs:
##      Command:    url_custom.sh list <category> <region>
##      Example:    url_custom.sh list MY_CATEGORY SPB
##
##      To Delete URLs:
##      Command:    url_custom.sh del <category> <URL> <[exact-match|glob-match]> <region>
##      Examples:   url_custom.sh del MY_CATEGORY https://www.example.com/ exact-match SMR
##                  url_custom.sh del MY_CATEGORY https://*.foo.com/ glob-match NSK

##	IP addresses of all BIG-IPs
BIGIP_MSK="10.2.23.2"
BIGIP_SPB="10.2.23.2"
BIGIP_SMR="10.2.23.4"
BIGIP_EKB="10.2.23.4"
BIGIP_NSK="10.2.23.4"

##	Login
LOGIN='api:Bizon123!'


display_usage () {
    echo "   Custom URL Category Update Script"
    echo ""
	echo "   Valid regions: MSK, SPB, SMR, EKB, NSK"
	echo ""
    echo "   To add URLs to a custom category:"
    echo "   script.sh add <category> <URL> <[exact-match|glob-match]> <region>"
    echo ""
    echo "   To list URLs in a custom category:"
    echo "   script.sh list <category> <region>"
    echo ""
    echo "   To remove URLs from a custom category:"
    echo "   script del <category> <URL> <[exact-match|glob-match]> <region>"
    echo ""
    exit 1
}

## List URLs
list_urls () {
    if [[ -z "$1" || -z "$2" ]]
    then
        display_usage
    fi

	## Check IP address
	if [[ "$2" == "SPB" ]]
	then
		BIGIP=$BIGIP_SPB
    elif [[ "$2" == "SMR" ]]
	then
		BIGIP=$BIGIP_SMR
	elif [[ "$2" == "MSK" ]]
	then
		BIGIP=$BIGIP_MSK
	elif [[ "$2" == "EKB" ]]
	then
		BIGIP=$BIGIP_EKB
	elif [[ "$2" == "NSK" ]]
	then
		BIGIP=$BIGIP_NSK
	else
		echo "No such region! Valid regions: MSK, SPB, SMR, EKB, NSK"
	fi
	## Get current URLs
	curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP}/mgmt/tm/sys/url-db/url-category/$1" | jq .urls
    
}

add_urls () {
    if [[ -z "$1" || -z "$2" || -z "$3" || -z "$4" ]]
    then
        display_usage
    fi

	## Check IP address
	if [[ "$4" == "SPB" ]]
	then
		BIGIP=$BIGIP_SPB
    elif [[ "$4" == "SMR" ]]
	then
		BIGIP=$BIGIP_SMR
	elif [[ "$4" == "MSK" ]]
	then
		BIGIP=$BIGIP_MSK
	elif [[ "$4" == "EKB" ]]
	then
		BIGIP=$BIGIP_EKB
	elif [[ "$4" == "NSK" ]]
	then
		BIGIP=$BIGIP_NSK
	else
		echo "No such region! Valid regions: MSK, SPB, SMR, EKB, NSK"
	fi

    ## Get current URLs
    urls=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`
    if [ "$3" == "exact-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"exact-match\"}"
		elif [ "$3" == "glob-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"glob-match\"}"
    else
        display_usage
    fi

    ## Update category
	## Payload 
	payload="{\"urls\":[${urls},${newurl}]}"
	    
	## Update category
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "URL has been added successfully"
	else
    echo "URL has NOT been added!!!!"
	fi	
	## Sync cluster
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Cluster"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "Cluster has been synced successfully"
	else
    echo "Cluster has NOT been synced!!!!"
	fi	
	rm -f result.tmp
}

del_urls () {

    if [[ -z "$1" || -z "$2" || -z "$3" || -z "$4" ]]
    then
        display_usage
    fi

## Check IP address
	if [[ "$4" == "SPB" ]]
	then
		BIGIP=$BIGIP_SPB
    elif [[ "$4" == "SMR" ]]
	then
		BIGIP=$BIGIP_SMR
	elif [[ "$4" == "MSK" ]]
	then
		BIGIP=$BIGIP_MSK
	elif [[ "$4" == "EKB" ]]
	then
		BIGIP=$BIGIP_EKB
	elif [[ "$4" == "NSK" ]]
	then
		BIGIP=$BIGIP_NSK
	else
		echo "No such region! Valid regions: MSK, SPB, SMR, EKB, NSK"
	fi
    ## Form URL for deletion
    if [ "$3" == "exact-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"exact-match\"}"
    elif [ "$3" == "glob-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"glob-match\"}"
    else
        display_usage
    fi

	## Get current URLs
    urls=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`
    ## Update category
    modurls=`printf '%s\n' "${urls//$newurl/}"`
    payload="{\"urls\":[${modurls}]}"
    payload=`echo ${payload} |sed "s/\[,/\[/;s/,\]/\]/;s/,,/,/"`    
    curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "URL has been deleted successfully"
	else
    echo "URL has NOT been deleted!!!!"
	fi	
	## Sync cluster
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Cluster"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "Cluster has been synced successfully"
	else
    echo "Cluster has NOT been synced!!!!"
	fi	

	rm -f result.tmp
}


## Test for command inputs
if [[ "$1" == "add" ]]
then
    add_urls $2 $3 $4 $5
elif [[ "$1" == "list" ]]
then
    list_urls $2 $3
elif [[ "$1" == "del" ]]
then
    del_urls $2 $3 $4 $5
else
    display_usage
fi
exit 1
```

## Add/del URL to many BIG-IPs

* syncs cluster + checks if all commands are successfull
* Скрипт завязан на основную ноду
* При удалении адреса нужно прописывать маску

```
#!/bin/bash
## F5 Custom URL Category Update Script
## Description: provides options to add URLs and delete URLs in an existing custom URL category
## Version: 1.0
## Requires: bash, curl, jq
##
## Syntax:
##      To Add URLs:
##      Command:    url_all.sh add <category> <URL> <[exact-match|glob-match]>
##      Examples:   url_all.sh add MY_CATEGORY https://www.example.com/ exact-match
##                  url_all.sh add MY_CATEGORY https://*.foo.com/ glob-match
##
##      To Delete URLs:
##      Command:    url_all.sh del <category> <URL> <[exact-match|glob-match]>
##      Examples:   url_all.sh del MY_CATEGORY https://www.example.com/ exact-match
##                  url_all.sh del MY_CATEGORY https://*.foo.com/ glob-match
##

##	IP addresses of all BIG-IPs
BIGIP_MSK="10.2.23.2"
BIGIP_SPB="10.2.23.2"
BIGIP_SMR="10.2.23.4"
BIGIP_EKB="10.2.23.4"
BIGIP_NSK="10.2.23.4"

##	Login
LOGIN='api:Bizon123!'

## Display command usage
display_usage () {
    echo "Custom URL Category Update Script"
    echo ""
    echo "   To add URLs to a custom category:"
    echo "   url_all.sh add <category> <URL> <[exact-match|glob-match]>"
    echo ""
    echo "   To remove URLs from a custom category:"
    echo "   url_all.sh del <category> <URL> <[exact-match|glob-match]>"
    echo ""
    exit 1
}

## Add URLs
add_urls () {
    if [[ -z "$1" || -z "$2" || -z "$3" ]]
    then
        display_usage
    fi

    ## Get current URLs for SPB BIG-IP
    urls_spb=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP_SPB}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`
	## Get current URLs for SMR BIG-IP
	urls_smr=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP_SMR}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`

    if [ "$3" == "exact-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"exact-match\"}"
		elif [ "$3" == "glob-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"glob-match\"}"
    else
        display_usage
    fi

    ## Update category
	## Payload for SPB BIG-IP
	payload_spb="{\"urls\":[${urls_spb},${newurl}]}"
	## Payload for SMR BIG-IP
	payload_smr="{\"urls\":[${urls_smr},${newurl}]}"
    
	## Update category on SPB BIG-IP
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP_SPB}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload_spb} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SPB: URL has been added successfully"
	else
    echo "SPB: URL has NOT been added!!!!"
	fi	
	## Sync cluster in SPB
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP_SPB}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Cluster"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SPB: Сluster has been synced successfully"
	else
    echo "SPB: Cluster has NOT been synced!!!!"
	fi	
	## Update category on SMR BIG-IP
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP_SMR}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload_smr} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SMR: URL has been added successfully"
	else
    echo "SMR: URL has NOT been added!!!!"
	fi	
	## Sync cluster in SMR
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP_SMR}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Novosibirsk"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SMR: Сluster has been synced successfully"
	else
    echo "SMR: Cluster has NOT been synced!!!!"
	fi
	rm -f result.tmp
}

## Delete URLs
del_urls () {

    if [[ -z "$1" || -z "$2" || -z "$3" ]]
    then
        display_usage
    fi

    ## Form URL for deletion
    if [ "$3" == "exact-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"exact-match\"}"
    elif [ "$3" == "glob-match" ]
    then
        newurl="{\"name\":\"$2\",\"type\":\"glob-match\"}"
    else
        display_usage
    fi

	## Get current URLs in SPB
    urls_spb=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP_SPB}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`
    ## Update category in SPB
    modurls_spb=`printf '%s\n' "${urls_spb//$newurl/}"`
    payload_spb="{\"urls\":[${modurls_spb}]}"
    payload_spb=`echo ${payload_spb} |sed "s/\[,/\[/;s/,\]/\]/;s/,,/,/"`    
    curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP_SPB}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload_spb} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SPB: URL has been deleted successfully"
	else
    echo "SPB: URL has NOT been deleted!!!!"
	fi	
	## Sync cluster in SPB
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP_SPB}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Cluster"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SPB: Сluster has been synced successfully"
	else
    echo "SPB: Cluster has NOT been synced!!!!"
	fi	

	## Samara
	## Get current URLs in SMR
    urls_smr=`curl -sku ${LOGIN} -H 'Content-Type: application/json' -X GET "https://${BIGIP_SMR}/mgmt/tm/sys/url-db/url-category/$1" |jq .urls --compact-output |sed 's/\[//g' |sed 's/\]//g'`
	## Update category in SMR
    modurls_smr=`printf '%s\n' "${urls_smr//$newurl/}"`
    payload_smr="{\"urls\":[${modurls_smr}]}"
    payload_smr=`echo ${payload_smr} |sed "s/\[,/\[/;s/,\]/\]/;s/,,/,/"`    
    curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X PATCH "https://${BIGIP_SMR}/mgmt/tm/sys/url-db/url-category/$1" -d ${payload_smr} > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SMR: URL has been deleted successfully"
	else
    echo "SMR: URL has NOT been deleted!!!!"
	fi	
	## Sync cluster in SMR
	curl -i -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP_SMR}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Novosibirsk"}' > result.tmp
	if grep -q "HTTP/1.1 200 OK" result.tmp; then
		echo "SMR: Сluster has been synced successfully"
	else
    echo "SMR: Cluster has NOT been synced!!!!"
	fi	
}

## Test for command inputs
if [[ "$1" == "add" ]]
then
    add_urls $2 $3 $4
elif [[ "$1" == "del" ]]
then
    del_urls $2 $3 $4
else
    display_usage
fi
exit 1
```

## API

<https://clouddocs.f5.com/api>

Basic and token auth are supported

Добавление нового пула с пул мембером

```
curl -kv "https://<BIG-IP_mgmt_IP_address>//mgmt/tm/ltm/pool" -u admin:admin -X POST -H "Content-Type: application/json" -d '{"name":"api_pool","members":[{"name":"api_pm:80","address":"8.8.4.4"}]}'
```

-k: insecure, ignore self-signed certs -v: verbose

Удаление ранее созданного пула

```
curl -kv "https://<BIG-IP_mgmt_IP_address>//mgmt/tm/ltm/pool/api_pool" -u admin:admin -X DELETE
```

```
To add URLs to a custom category, enter the following (it will rewrite all URLs):
```

```
curl -sku 'admin:Bizon123!' -H 'Content-Type: application/json' -X PATCH 'https://10.2.23.2/mgmt/tm/sys/url-db/url-category/Bypass' -d '{"urls":[{"name":"http://www.a.com/"},{"name":"http://www.b.com/"}]}'
```

where <https://bigip/> is the address (IP or hostname) of the F5 BIG-IP. To directly enumerate a customer category by using a remote API call, enter the following:

```
curl -sku 'admin:admin' -H 'Content-Type: application/json' -X GET 'https://bigip/mgmt/tm/sys/url-db/url-category/my-category' | jq
```

Show data group Bypass

```
curl -sku 'admin:Bizon123!' -H 'Content-Type: application/json' -X GET 'https://10.2.23.2/mgmt/tm/ltm/data-group/internal/dg-bypass' | jq
```

Add IP addresses to data group - it will overwrite whole data group

```
curl -sku 'admin:Bizon123!' -H 'Content-Type: application/json' -X PATCH 'https://10.2.23.2/mgmt/tm/ltm/data-group/internal/dg-bypass' -d '{"records":[{"name":"1.1.1.1"},{"name":"2.2.2.2"}]}'
```

Sync cluster (send local config to group)

```
curl -sku ${LOGIN} -H 'Content-Type: application/json' -X POST "https://${BIGIP_SPB}/mgmt/tm/cm" -d '{"command":"run","utilCmdArgs":"config-sync to-group Cluster"}'
```

Check failover status

```
curl -sku 'admin:Bizon123!' -H 'Content-Type: application/json' -X GET 'https://10.2.23.3/mgmt/tm/cm/failover-status' | jq
```

Get API token

```
POST https://10.2.23.110/mgmt/shared/authn/login
{
"username":"admin",
"password":"Bizon123!",
"loginProviderName": "tmos"
}
```

Than use it in X-F5-Auth-Token Header

## ICAP

`Traffic > Standard Virtual server > Request Adapt profile > Internal Virtual server > ICAP profile > ICAP servers pool`

Configure internal ICAP virtual server

* Create standard virtual server
* Create internal virtual server: apply ICAP irules here
* Configure Request Adapt profile to the standard virtual server, in this profile we configure Internal Vitual server name
* Configure an HTTP profile to the standard virtual server - why?
* Configure ICAP profile for internal virtual server, here we specify ICAP server address, port for instance `icap://${SERVER_IP}:${SERVER_PORT}/reqmod`

How ICAP works in SSLO

* Per request policy > ssloS\_ICAP-t-4-connector connector profile (service down action: Ignore here) > ssloS\_ICAP-t-4 Virtual server: Request Adapt and Response Adapt profiles are here: Local traffic > Profiles > Services > Request Adapt and Response Adapt > link to internal Virtual servers ssloS\_ICAP-req and ssloS\_ICAP\_resp respectively > In these virtual servers links to ICAP profiles ssloS\_ICAP-req and ssloS\_ICAP-resp (URI here)

### Add custom ICAP header with destination IP, applied on Internal ICAP virtual server

```
when ICAP_REQUEST {
ICAP::header add X-Server-IP [IP::local_addr]
}
```

```
when ICAP_REQUEST {
ICAP::header add Allow 204
}
```

### Disable ICAP requests for HTTP requests smaller then 1Kb

* In Local policy: `HTTP header Content Length is in data group Test at request time`
* Data group: ICAP text file with Unix end format and UTF-8 encoding. The datagroup file contains integers from 1 to 1000. Type is string
* Disable request adapt at request time, disable request adapt during response time

```
1,LF
2,LF
3,LF
...
```

**Generate POST request 1001 bytes exactly! Smaller then this request will not trigger ICAP request**

```
curl -k -X POST -F 'item_meta[6]=testtttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt' https://dlptest.com/http-post/
```

**Test with tcpdump**

```
tcpdump -A -s0 -nni 0.0 host 1.1.1.1 and port 1344 | grep "Host: dlptest.com"
```

**Show Content-Length of the request**

```
tcpdump -A -s0 -nni to_pa port 443 and src 192.168.1.100 | grep -B 4 "Content-Length"
```

**Monitor ICAP pool**

.1.3.6.1.4.1.3375.2.2.5.2.3.1.3 F5-BIGIP-LOCAL-MIB::ltmPoolStatServerBytesIn - it should be increasing

.1.3.6.1.4.1.3375.2.2.5.2.3.1.8 F5-BIGIP-LOCAL-MIB::ltmPoolStatServerCurConns

## Orchestrating VS

Default is bypass, add one network to decrypt, first check exceptions in URL and DST

```
 if { ( [call SSLOLIB::DSTIP DG:dg-bypass] ) or ( [call SSLOLIB::SNI CAT:$static::URLCAT_bypass] ) } { call SSLOLIB::target "bypass" ${sni} "SNIDGGLOB" ; return }
 if { [call SSLOLIB::SRCIP DG:DG-decrypt] } { call SSLOLIB::target "default" ${sni} "SRCIP" ; return }

```
