-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinux.txt
1665 lines (1486 loc) · 69.7 KB
/
linux.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Network Time Protocol 101 [[{configuration.clock,troubleshooting]]
REF:<https://www.server-world.info/en/note?os=Fedora_25&p=ntp&f=2>
```
| $ sudo dnf -y install ntp # <- STEP 1) Install ntp client on RedHat flavours
| # sudo apt install ntp on Debian/Ubuntu flavours
| $ edit /etc/ntp.conf # <- STEP 2) Create/Modify config. file
|
| ...
| + restrict 10.0.0.0 mask 255.255.255.0 nomodify notrap
| + server 0.fedora.pool.ntp.org iburst
| # server 1.fedora.pool.ntp.org iburst
| # server 2.fedora.pool.ntp.org iburst
| # server 3.fedora.pool.ntp.org iburst
| # server ntp.nict.jp iburst
| # server ntp1.jst.mfeed.ad.jp iburst
| # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| # Enable/disable NTP servers "at will"
| $ sudo systemctl start ntpd # <- STEP 3) Start daemon as (SystemD) service
| $ ntpq -p # <- STEP 4) check
| $ sudo systemctl enable ntpd # <- STEP 5) Enable at boot time.
| $ sudo timedatectl set-timezone Europe/London # <- STEP 5) Set timezone
```
[[}]]
## Linux ACLs [[{security.aaa,PM.TODO]]
<https://wiki.archlinux.org/index.php/Access_Control_Lists>
[[}]]
[[{configuration.sysctl,kernel.tunning,configuration.network,storage.fs,troubleshooting.performance]]
# sysctl: Kernel Tunning
* Cli app to view/modify kernel parameters affecting the runtime behavior
of network, file-systems, kernel logging, ...
* Not to be confused with (SystemD) 'systemctl' used to add/remove/modify/...
services (applications running in background), centralized app logging,...
* TIP: *read comments in /etc/sysctl.conf for most widely tunned params.*
```
| $ sysctl -a ← View all configured kernel params
| Output can be filtered out easily with
| 'grep'.
|
| $ sysctl vm.min_free_kbytes ← View a given param
| -n: opt. Show only value (vs param name)
|
|
| $ sudo sysctl -w net....=0 ← Set new value for kernel param.
|
|
| $ sudo edit /etc/sysctl.conf ← make changes permanent after reboot
| edit /etc/sysctl.d/99-custom.conf for custom
| changes.
|
|
| $ sudo sysctl -p ← apply any change in /etc/sysctl.conf
| Use -p /etc/sysctl.d/99-custom.conf for
| alternative (non default) path
|
| /proc/sys/ OVERVIEW:
| ├ abi/vsyscall32
| ├ debug
| │ ├ exception-trace
| │ └ kprobes-optimization
| ├ dev
| │ ├ parport
| │ │ ├ default/...
| │ │ └ parport0/...
| │ │ ├ devices
| │ │ ...
| │ ├ raid/speed_limit_max(min)
| │ ├ scsi/logging_level
| │ ├ tty/ldisc_autoload
| │ ...
| ├ kernel REF: https://www.kernel.org/doc/html/v5.7/admin-guide/sysctl/kernel.html
| │ ├ acct
| │ ├ sched_*
| │ ├ sem
| │ ├ watchdog*
| │ ...
| ├ net
| │ ├ core/... (40 tunnable params)
| │ ├ ipv4/* (devices, conf, route, tcp, udp,...)
| │ ├ ipv6/...
| │ ├ netfilter ... (65 tunnable params)
| │ ├ nf_conntrack_max
| │ ├ unix
| │ │ └ max_dgram_qlen
| │ ...
| ├ fs
| │ ├ inotify/...
| │ ├ nfs/...
| │ ├ ext4/...
| │ ├ xfs/...
| │ ...
| ├ sunrpc ... (11 tunnable params)
| ├ user/... (9 tunnable params)
| └ vm/... (48 tunnable params)
```
$ sysctl -a ← View all configured kernel params
[[configuration.sysctl}]]
[[{kernel.tunning.tuned,kernel.tunning.101,PM.TODO,qa.UX]]
## Kernel Tunning with 'tuned'
* `/proc/sys/vm/`: Kernel FS "control pannel"
<https://tuned-project.org/>
* About tuned:
* OS Tunning is done in practice through:
* long-profiling
* continuous-monitoring
* Tunning becomes harder if system load changes frequently.<br/>
Ex.: A system with a peak of load certain hours a day
```
can be tuned for performance those known hours
and tuned for power-efficency the rest of day
```
* man 8 tuned: Dynamic Adaptive system tuning daemon
<https://linux.die.net/man/8/tuned>
* cron-friendly system service that lets to select a tuning profile
(pre-build or custom).
* Tuning include:
* sysctl settings (/proc/sys/)
* settings for disk-elevators
* power management options
* transparent hugepages
* custom-scripts
* Install):
```
| $ sudo dnf -y install tuned # <· RedHat/Fedora/CentOS package install
| $ sudo systemctl enable tuned # <· enable tuned service at boot
| ...
| $ sudo systemctl start tuned # <· Start tuned service now
| $ sudo systemctl status tuned # <· Check tuned service status
| $ sudo systemctl status tuned
| * tuned.service - Dynamic System Tuning Daemon
| Loaded: loaded (/usr/lib/systemd/system/tuned.service; disabled; vendor preset: disabled)
| Active: *active (running)* since Sun 2019-01-20 16:29:05 EST; 15s ago
| Docs: man:tuned(8)
| man:tuned.conf(5)
| man:tuned-adm(8)
| Main PID: 10552 (tuned)
| Tasks: 4 (limit: 4915)
| Memory: 15.7M
| CGroup: /system.slice/tuned.service
| └─10552 /usr/bin/python3 -Es /usr/sbin/tuned -l -P
```
* Ussage:
```
| $ *tuned-adm list* # ← List existing tunning profiles
| → Available profiles:
| → - balanced - General non-specialized
| → - desktop - Optimize for the desktop
| → - latency-performance - deterministic performance (increased power consumption)
| → - network-latency - deterministic performance low-latency (increased power consumption)
| → - network-throughput - Optimize for streaming network throughput
| generally only necessary on older CPUs or
| 40G+ networks
| → - powersave - Optimize for low power consumption
| → - throughput-performance - provides excellent performance across a
| variety of common server workloads
| → - virtual-guest - Optimize for running inside a virtual guest
| → - virtual-host - Optimize for running KVM guests
| → Current active profile: balanced
|
| $ *sudo tuned-adm active* # ← query status
| Current active profile: balanced
|
| $ *sudo tuned-adm profile powersave* # ← select profile
```
[[kernel.tunning.tuned}]]
## Job control++
* nice : run a process with modified scheduling priority.
* STOP/CONT : kill -STOP $pid "freezes" a process.
* kill -CONT $pid un-freezes it.
* chroot : (Ch)ange Root, runs a process withing a modified view of [[{security.101]]
the OS File System, where the root seen by the process is
just a subdirectory of the real root path seen by the OS.
Basically containerization extends the idea of chroot to
let processes view only a subset of the FS and network
through (kernel supported) namespaces. [[}]]
* cgroups : linux kernel (C)ontrol groups allow processes to be organized
into hierarchical groups whose usage of various types of
resourcescan then be limited and monitored.
`/sys/fs/cgroup` pseudo-FS is used to control them.
* cgroup subsystem: kernel component modifying the behavior of processes.
(CPU time, available memory, ...).
also known as resource controllers (or simply, controllers).
...
## GNU Parallel [[{job_control,performance.distributed]]
* <https://linux.die.net/man/1/parallel>
* <https://www.gnu.org/software/parallel/parallel_cheat.pdf>
* <https://www.reddit.com/r/programming/comments/ayew9r/never_got_around_to_learning_gnu_parallel_here_is/>
* Replacement for xargs and for-loops.
* It can also split a file or a stream into blocks and pass those to commands running in parallel.
Ex:
```
|$ parallel --jobs 200% gzip ::: *.html # ← Compress all *.html files in parallel
| 200% → 2 per CPU thread
|
|$ parallel lame {} -o {.}.mp3 ::: *.wav # ← Convert all *.wav to *.mp3 using lame
|
|$ cat bigfile | \ # ← Chop bigfile into 1MB blocks and grep
| parallel --pipe grep foobar for the string foobar
```
* INPUT SOURCES:
```
| $ parallel echo ::: cmd line input source
| $ cat input_from_stdin | parallel echo
| $ parallel echo ::: multiple input sources ::: with values
| $ parallel -a input_from_file echo
| $ parallel echo :::: input_from_file
| $ parallel echo :::: input_from_file ::: and command line
```
* Replacement string:
```
| {} ← mydir/mysubdir/myfile.myext
| {.} ← mydir/mysubdir/myfile
| {/}, {//}, {/.} ← myfile.myext, mydir/mysubdir, myfile
| {#} ← The sequence number of the job
| {%} ← The job slot number
| {2} ← Value from the second input source
| {2.} {2/} {2//} {2/.} ← Combination of {2} and {.} {/} {//} {/.}
| {= perl expression =} ← Change $_ with perl expression
|
| $ parallel --keep-order "sleep {}; echo {}" ::: 5 4 3 2 1 # ← *Keep input order in output*
```
* Control the execution:
```
| $ parallel --jobs 2 "sleep {}; echo {}" ::: 5 4 3 2 1 # ← Run 2 jobs in parallel
|
| $ parallel --dryrun echo ::: Red Green Blue ::: S M L # ← Dry-run. See will be executed
| without real execution
```
* Remote execution:
```
| $ parallel -S server1 -S server2 "hostname; echo {}" ::: foo bar
```
* Pipe mode:
```
| $ cat bigfile | parallel --pipe wc -l
|
| $ parallel -a bigfile \ <·· Chop bigfile into one block per CPU
| --pipepart --block -1 \ thread and grep for foobar
| grep foobar
```
[[}]]
[[{monitoring.101,monitoring.memory,monitoring.I/O,]]
[[monitoring.network,monitoring.cpu,troubleshooting,PM.TODO]]
## Dstat (vmstat + iostat+ ifstat + mpstat)
* NOTE: There is a conflict between Red Hat Dstat and the original dstat-real.
C&P from <https://github.com/dstat-real/dstat>:
> Due to actions taken by RedHat to hijack the DSTAT name, further
> development of this project has ceased. Development of this project
> is taking place on the Dool fork.
Next refers to Red-Hat? version.
* TODO: Compare with [dool](https://github.com/scottchiefbaker/dool)
<https://linux.die.net/man/1/dstat>
* Dstat: moderm replacement joining the info from [[{doc_has.comparative]]
vmstat, iostat, ifstat an mpstat. [[}]]
* Dstat overcomes some of the limitations and adds some extra features.
* Dstat allows you to view all of your system resources instantly,
you can eg.:
* compare disk usage in combination with interrupts from disk controller.
* compare network bandwidth numbers directly with the disk throughput (in the same interval).
[[}]]
[[{monitoring.jobs,job_control,monitoring.i/o]]
[[profiling.jobs.IO.block,profiling.storage,storage.profiling]]
## pidstat: process stats
* By Sebastien Godard (http://pagesperso-orange.fr/sebastien.godard/)
```
| -d Report I/O statistics
| kB_rd/s
| kB_wr/s
| kB_ccwr/s: Cancelled-writes eg. task truncates some dirty pagecache.
| (IO which another task has been accounted for).
| iodelay : Block-I/O delay of task-monitored, measured in clock ticks. [[{profiling.jobs.]]
| including delays waiting for sync-block-I/O and swaping-block-I/O completion. [[}]]
|
| --dec= 0|1|2* number of decimal-places to use.
| -e 'program' arg1 arg2 ... Exec. program + args to be monitored.
| -G cmd_name_regex Filter by processes mathching regex for its command-name .
| -H Display timestamp-in-seconds since epoch. (1970-01-01)
| -h Display activities horizontally in a single line, without statistics (for batch tasks)
| --human
| -I In SMP archs, indicate to divide task CPU ussage should be divided by total num.or proccessors.
| -l Display command-name + all its arguments.
| -p $PID Filter by process $PID Select tasks (processes)
| Use SELF for the pidstat process itself.
| Use ALL for all tasks.
| -R Report realtime-priority and scheduling-policy info, including:
| -r Report pagefaults and memory utilization. [[profiling.jobs.pagefaults]]
| minflt/s : Total number of minor-faults per sec, (not loading from disk).
| minflt-nr: Total number of minor-faults for task-and-children for time-interval.
| majflt/s : Total number of major-faults per secd,
| majflt-nr: Total number of major-faults for task-and-children for time-interval.
| VSZ : virtual memory usage of entire task in kilobytes.
| RSS : Resident Set Size: (non-swapped physical memory used in kilobytes).
| %MEM : Resident Set Size %
| -nr : Total number of major-faults by task-and-children for time-interval.
| -s Report stack utilization. [[profiling.jobs.memory.stack]]
| StkSize : memory in kilobytes reserved for the task as stack, (not necessarily used)
| StkRef : memory in kilobytes used as stack, referenced by the task.
| -T {TASK*|CHILD|ALL}
| -t display statistics per-thread.
| -U [ username ] Display real-user-name or filter by user-name.
| -u Report CPU utilization. [[{profiling.jobs.cpu]]
| %usr : CPU used by task at user-level NOT include time spent running a Virt.CPU.
| usr-ms : Total millisecs spent by task+children at user level.
| %system : CPU used by task while executing at the system level (kernel).
| system-ms: Total millisecs spent by task+children at systeml level (kernel).
| %guest : Percentage of CPU spent by the task in virt. machine. (KVM/Qemu/...?)
| guest-ms : Total millisecs spent by task+children in virt. machine. (KVM/Qemu/...?)
| %wait : Percentage of CPU spent by the task while waiting to run.
| %CPU : Total percentage of CPU time used by the task. [[}]]
| Total number of milliseconds spent by the task and all its children in virtual
| machine (running a virtual processor).
| -v Report some kernel tables. [[monitoring.jobs.kernel]]
| -w Report task switching activity: [[profiling.jobs.kernel]] [[{profiling.jobs.kernel]]
| cswch/s : Total number of voluntary context-switches per sec.
| voluntary == task blocks waiting for a resource.
| nvcswch/s: Total number of non-voluntary context switches per sec.
| non voluntary == task executes for the duration of its time slice and then
| is forced to relinquish the processor. [[}]]
|
| ENV.VARS:
| S_COLORS := never|always|auto (display statistics in color)
```
* EXAMPLES
```
| $ pidstat 2 5 # Dump 5-reports of CPU-statistics
| # for every active task at 2-secs intervals.
|
| $ pidstat -r -p 1643 2 5 # Display five reports of page faults
| # and mem. stats for PID 1643 at 2 secs interval.
|
| $ pidstat -C "fox|bird" -r -p ALL # Display global page faults and mem.
| # stats for all processes whose command name
| # includes the string "fox" or "bird".
|
| $ pidstat -T CHILD -r 2 5 # Display 5 reports of page faults stats at 2 secs
| # intervals for child processes of all tasks in
| # the system. Only child processes with non-zero statistics
| # values are displayed.
```
[[monitoring.jobs}]]
## blktrace (block I/O traffic) [[{monitoring.storage.blocks]] (man 8 blktrace)
* generate traces of the i/o traffic on (low-level) block devices vs (high-level) File Systems.
```
| $ sudo blktrace -d /dev/sda -o - | blkparse -i - <··· trace i/o for /dev/sda
| Alt. using btrace script:
| $ btrace /dev/sda
| $ blktrace /dev/sda /dev/sdb <··· trace /dev/sda+/dev/sdb to current dir.
| $ blkparse sda sdb <··· View saved trace
```
```
| SYNOPSIS
| blktrace -d dev [ -r debugfs_path ] [ -o output ] [ -w time ] [ -a action ] [ -A action_mask ] [ -v ]
|
| DESCRIPTION
| OPTIONS
| -a/--set-mask=hex-mask : Set filter mask to hex-mask (see below for masks)
| barrier : barrier attribute
| complete: completed by driver
| discard : discard / trim traces
| fs : requests
| issue : issued to driver
| pc : packet command events
| queue : queue operations
| read : read traces
| requeue : requeue operations
| sync : synchronous attribute
| write : write traces
| notify : trace messages
| drv_data: additional driver specific trace
|
| --act-mask=mask : Add mask to current filter (see below for masks)
| --buffer-size=size : Specifies (1024) buffer size for event extraction. Def 512KiB.
| --dev=dev : Adds dev as a device to trace
| --input-devs=file : Adds the devices found in file as devices to trace
| --num-sub-buffers=X : number of buffers to use. Def: 4 sub buffers.
| --listen : Run in network listen/server mode.
| --host=hostname : Run in network client mode
| --port=number : Network port to use (default 8462)
| --no-sendfile : Make the network client NOT use sendfile() to transfer data
| --output=basename : Specifies base name for input files. Default is device.blktrace.cpu.
| Specifying -o - runs in live mode with blkparse (writing data to standard out).
| --output-dir=dir : Prepend file to output file name(s)
| --relay=rel-path : Specifies debugfs mount point
| --version
| -w seconds
| --stopwatch=seconds
```
### REQUEST TYPES:
* file system : normal read/write op from a specific disk location at a given size.
typically originating from a user process
* SCSI commands: blktrace sends the command data block as a payload so that blkparse can decode it.
[[}]]
## SystemTap (stap) [[{monitoring.jobs,troubleshooting,PM.TODO]]
* C&P from https://lwn.net/Articles/852112/: [[{doc_has.comparative]]
SystemTap has been available since 2005, while bpftrace is a more
recent contender that, to some, may appear to have made SystemTap
obsolete. However, SystemTap is still the preferred tool for some
real-world use cases. [[}]]
* <https://en.wikipedia.org/wiki/SystemTap>
* tool to perform live analysis of running program (dynamic instrumentation).
* It can interrupt normal control flow and execute code specified by a SystemTap script,
temporarily modifying the program at runtime.
* Use-cases:
- extract, filter, summarize complex performance|functional diagnosys data.
* Contributed by:
- Red Hat/IBM, Intel, Hitachi, Oracle, community.
* See real example: <https://developers.redhat.com/blog/2019/07/24/probing-golang-runtime-using-systemtap/>
[[}]]
## latrace LD audit [[{monitoring.jobs,monitoring.libc,troubleshooting,PM.TODO]]
* man 1 latrace
* LD_AUDIT 2.4+ libc frontend
```
$ latrace [-ltfsbcCpADaoyIiBdvTFELVh] command [arg ... ]
```
Run command and display its dynamic library calls using
a LD_AUDIT libc feature (available from libc version 2.4 onward - see the
section called "DISCUSSION" ). It is also capable to measure and display
various statistics of dynamic calls.
If the config file is provided, latrace will display symbol's arguments with
detailed output for structures. The config file syntax is similar to the C
language, with several exceptions.
The `latrace` by default fully operates inside of the traced program. However
another pipe mode is available, to move the main work to the latrace binary
(see the section called "PIPE mode").
[[}]]
[[{monitoring.network,troubleshooting]]
# Network audit/control
## ss: socket Statistics ss
* replaces 'netstat'
```
| ┌──── -n : Do not resolve IP to DNS (much) faster.
| ·┌─── -t : Show tcp (filter out UNIX, UDP, ...)
| ··┌── -l : Show socket waiting for (client) connetions
| ···┌─ -p : Show process PID that controls the socket.
| $ sudo ss -ntlp
| example Output:
| State Recv-Q Send-Q Local Peer
| Addr:Port Addr:Port
| LISTEN 0 128 *:80 *:* users:(("lighttpd",pid=23515,fd=4))
| LISTEN 0 128 *:22 *:* users:(("sshd",pid=571,fd=3))
|
| ┌─······ TCP connection only (vs UDP, ...)
| · ┌─··· all (listening and connected) processes (vs ─l: listening)
| · · ┌─ display socket and processes
| $ sudo ss -t -a -p
| STATE ... ADDRESS:PORT PEER ADDRESS:PORT
| ESTABLISHED ... 127.0.0.1:postgres 127.0.0.1:46404 users:(("postgres",pid=64032,fd=11))
| ESTABLISHED ... 127.0.0.1:37200 127.0.0.1:50004 users:(("sshd",pid=61411,fd=10))
| ESTABLISHED ... 127.0.0.1:postgres 127.0.0.1:45086 users:(("postgres",pid=43553,fd=11))
| TIME_WAIT ...
|
| # ── Display all established ssh connections. ────────────
| $ SS='( dport = :ssh or sport = :ssh )'
| $ ss -o state established ${SS }
|
| $ ss -x src /tmp/.X11-unix/* # <·· Find all local processes connected to X server
|
|
| # Advanced example: List tcp sockets in state FIN-WAIT-1
| # for http/https@193.233.7/24 and look at their timers.
| $ ss -o state fin-wait-2
| '( sport = :http or sport = :https )' \
| dst 193.233.7/24*
```
[[{]]
## ip (route, link, ...)
* Monitor debug IP routing.
```
$ ip route list <····· DISPLAY IP ROUTING TABLE
*default via 10.0.0.1 dev eth0*
10.0.0.0/24 dev eth0 proto kernel scope link src 10.0.0.5
169.254.0.0/16 dev eth0 scope link metric 1002
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1
168.63.129.16 via 10.0.0.1 dev eth0 proto static
169.254.169.254 via 10.0.0.1 dev eth0 proto static
...
$ ip link <···· DISPLAY IP DEVICE STATUS
1: lo: <LOOPBACK, UP,LOWER_UP> ... state UNKNOWN mode DEFAULT ...
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> ... state UP mode DEFAULT ...
link/ether 00:0d:3a:26:bb:2b brd ff:ff:ff:ff:ff:ff
...
```
## tcpdump "capture" network traffic
```
┌─················ -i eth0 \ <─ in network interface eth0
· ┌─······ filter in packets to/from port 8090
· · ┌─··· -n: Do not convert IPs to
· · · host-names (Avoiding slow
· · · dns reverse lookups)
· · · ┌─ -A: Show in text/ASCII format
$ sudo tcpdump -i eth0 port 8090 -n -A
Alternatively write to a file with flag:
-w output.tcpdump
This output.tcpdump file can then be replay again tcpdump
or with the more advanced Wireshark.
```
```
$ sudo traceroute "destination_host" # <· (attempts to) show IP ("hop" path) route from
source to destination for an IP packet.
```
## nmap: Remote IP port scanner
* Examine open ports in remote machine (vs local machine).
```
$ sudo nmap -nt remote_machine # ← (try to) query remote machine for open ports
```
* Release Changelog: <https://nmap.org/changelog.html>
* 5 scripts for getting started with the Nmap Scripting Engine
<https://www.redhat.com/sysadmin/nmap-scripting-engine>
[[monitoring.network}]]
[[{monitoring.network,troubleshooting.network]]
## Wondershaper: basic network traffic shaping
* <https://github.com/magnific0/wondershaper/>
```
| $ sudo ./wondershaper -a eth0 -u 4096 -d 8192 # <· limit: upload: 4Mbps, download:8Mbs
```
## Firejail: Network shaping
* <https://www.pcsuggest.com/bandwidth-traffic-shaping-in-linux-with-firejail/>
```
| $ firejail --net=enp2s0 firefox [/bash]
| $ firejail --list | grep 'firefox' | awk -F: '{print$1}'
| $ firejail --bandwidth=PID set interface-name down-speed up-speed
```
[[}]]
[[}]]
[[monitoring.network.nethogs}]]
* TODO:
<https://www.binarytides.com/linux-commands-monitor-network/>
[[network}]]
[[{security.101,security.remote_access]]
## Knockd ("Invisible Linux")
* <https://www.maketecheasier.com/make-linux-server-invisible-knockd/>
Knockd allows to listen to traffic on an network interface/port
waiting first for special sequences of port-hits.
clients (telnet, socat, ...) initiate port-hits by sending a TCP
or packet to a port/s on the server in order (sort of password
using port "pings")
### PRE-SETUP:
1. Install and Configure Iptables
```
| $ sudo apt-get install iptables iptables-persistent
| └────────┬────────┘
| takes over automatic
| loading of saved tables
```
2. Install Knockd:
```
| $ sudo apt-get install knockd # apt like
| $ sudo dnf install knockd # rpm like
```
### Ussage example: hide ssh service until "Knocked"
```
|
| $ iptables -A INPUT \ STEP 1
| -m conntrack \
| --ctstate ESTABLISHED, RELATED \ ← Allow established/current
| -j ACCEPT ← Allow
|
| $ iptables -A INPUT \ STEP 2
| -p tcp --dport 22 \ ← block incomming con. to 22 (SSH)
| -j REJECT
|
| STEP 3
| $ netfilter-persistent save ← s save the firewall rules
| $ netfilter-persistent reload
|
| STEP 4. Configure Knockd
| $ sudo "vim" /etc/knockd.conf
| [options]
| UseSyslog
|
| [openSSH]
| sequence = 7000,8000,9000
| seq_timeout = 5
| command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
| tcpflags = syn
|
| [closeSSH]
| sequence = 8000,9000,7000
| seq_timeout = 5
| command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
| tcpflags = syn
|
| command will be executed once the client-sequence is recognised.
| tcpflags must be set on the client "knocks"
|
| NOTE: Adding iptables "-A" flag (appned) causes the rule to be appended
| to the end of th INPUT chain, causing all remaining connections to drop.
| Replace by:
| command = /sbin/iptables -I INPUT 1 -s %IP% -p tcp --dport 22 -j ACCEPT
| "-I" flag (insert) ensures that the new rule is added to the top of the
| input chain to accept ssh connections.
|
| Modify /etc/default/knock lo look like: <· STEP 5. Enable Knockd Service
| + START_KNOCKD=1
| $ sudo systemctl enable knockd
| $ sudo systemctl start knockd
```
### Testing Setup:
```
| $ knock -v my-server-ip 7000 8000 9000
| $ ssh my-server-ip
| ...
| $ knock -v my-server-ip 9000 8000 7000
```
[[security.remote_access}]]
[[{monitoring.101,monitoring.vmstat]]
# Monitoring
## vmstat RT stats for CPU/procs/mem/paging/block IO/traps
```
| $ vmstat [options] [delay [count]] (global stats) [[{monitoring.101,monitoring.memory,monitoring.i/o]] (man 8 vmstat)
|
| The first report produced gives averages since the last reboot.
| Additional reports give information on a sampling period of length delay.
| The process and memory reports are instantaneous in either case.
|
| -a --active: Display active and inactive memory
| FROM: https://unix.stackexchange.com/questions/305606/linux-inactive-memory
| * active memory are pages which have been accessed "recently"
| * inactive memory are pages which have not been accessed "recently"
| """A high ratio of active to innactive memory can indicate
| memory pressure, but that condition is usually accompanied by
| pagin/swapping which is easier to understand"""
| -f --forks : display number of forks (fork,vfork,clone) since boot. This
| -m --slabs : Display slabinfo (memory assigned to kernel objects)
| https://en.wikipedia.org/wiki/Slab_allocation
| -s --stats : Displays a table of various event counters and memory statis‐
| tics. (without repeating)
| -d --disk : Report disk statistics
| -D --disk-sum: Report some summary statistics about disk activity.
| -p --partition device: Detailed statistics about partition
| -S --unit := 1000 (k), 1024 (K), 1000000 (m), 1048576 (M) bytes.
| swap (si/so) and block (bi/bo) not affected
| -t --timestamp: Append timestamp to each line
| *-w --wide : Wide output mode* (Recomended)
|
| OUTPUT FIELD DESCRIPTION
| *VM MODE* | *DISK MODE(--disk)*
| Procs | Reads
| r: # of runnable procs(running|waiting for) | total : Total reads completed successfully
| b: # of processes *in uninterruptible sleep* | merged : grouped reads(resulting in 1 I/O)
| | sectors: Sectors read successfully
| Memory ¹ | ms: milliseconds spent reading
| (inacti,cache,buff can be freed if needed) |
| swpd : virtual memory used |
| free : idle (ready to use) memory | Writes
| buff : memory used as disk buffers | total: Total writes completed successfully
| cache : memory used as cache | merged: grouped writes (resulting in 1 I/O)
| inact : inactive memory (-a option) | sectors: Sectors written successfully
| (still cached for possible reuse) | ms: milliseconds spent writing
| active: memory Used by processes |
| | IO
| Swap | cur: I/O in progress
| si: Amount of memory swapped in from disk(/s)| s: seconds spent for I/O
| so: Amount of memory swapped to disk(/s) +--------------------------------------------------------
|
| IO | *DISK PARTITION MODE (--partition)*
| bi: Blocks received from block device | reads: Total # of reads issued to part.
| bo: Blocks sent to block device | read sectors: Total read sectors for partition
| | writes: Total # of writes issued to part.
| System |requested writes: Total # of write requests made for part
| in: interrupts per second, including the clock+---------------------------------------------------------
| cs: *context switches per second*
| | *SLAB MODE (--slabs)*
| CPU (percentages of total CPU time) | cache: Cache name
| us: Time spent running non-kernel code(user )| num: # of currently active objects
| sy: Time spent running kernel code(system)| total: Total # of available objects
| id: Time spent idle | size: Size of each object
| wa: *Time spent waiting for IO* | pages: # of pages with at least one active object
| st: Time stolen from a virtual machine +---------------------------------------------------------
|
| ¹ buffers vs cache
| <https://stackoverflow.com/questions/6345020/what-is-the-difference-between-buffer-vs-cache-memory-in-linux>
|
| - buffers are associated with a specific block device,
| caching filesystem metadata(dir contents, file permissions),
| as tracking in-flight pages (what's being written
| from or read to for a particular block device).
| The Kernel tries to cache just enough buffers for predicted
| "next-reads" to block devices.
|
| - cache contains real application file data (file content).
| The Kernel tries to cache as much as possible until there is
| no more free memory for apps.
|
| *All linux blocks are currently 1024 bytes.*
```
[[monitoring.101}]]
[[{monitoring.memory.ps_mem,troubleshooting.memory]]
## ps_mem: Accurate mem.use
* <https://github.com/pixelb/ps_mem/>
```
| $ sudo pip install ps_mem <··· PIP (P)ackage (I)nstaler for (P)ython
| USSAGE:
| ps_mem [-h|--help] [-p PID,...] [-s|--split-args] [-t|--total] [-w N]
| [-d|--discriminate-by-pid] [-S|--swap]
|
| $ sudo ps_mem <··· Simple ussage:
| Private + Shared = RAM used Program
|
| 34.6 MiB + 1.0 MiB = 35.7 MiB gnome-terminal
| 139.8 MiB + 2.3 MiB = 142.1 MiB firefox
| 291.8 MiB + 2.5 MiB = 294.3 MiB gnome-shell
| 272.2 MiB + 43.9 MiB = 316.1 MiB chrome (12)
| 913.9 MiB + 3.2 MiB = 917.1 MiB thunderbird
| ---------------------------------
| 1.9 GiB
|
|
| $ sudo ps_mem -p $(pgrep -d, -u $USER) <··· Show only ps_mem for current $USER
| → ...
```
[[monitoring.memory.ps_mem}]]
[[{linux.101.shared_memory,configuration.memory,monitoring.memory,]]
## SysV shared memory
* SysV shared memory segments are accounted as a cache,
though they do not represent any data on the disks.
```
| $ sudo ipcs -m # <· check size of shared-memory-segments
```
[[linux.101.shared_memory}]]
[[monitoring.101}]]
# Audit [[{security.audit]]
[[{security.audit.user,101,security.aaa]]
## basic user audit
```
| $ sudo last -f /var/run/utmp # <· audit of present users logins at which terminals, logouts
| system events and current status of the system,
| system boot time (used by uptime) etc.
| $ who
| $ w
| $ sudo last -f /var/log/wtmp # <· historical data of utmp.
| $ sudo last -f /var/log/btmp # <· failed login attempts
| $ sudo lastb
| └─────┬─────┘
| binary compact format.
| Use `utmpdump` to dump to
| text friendly format.
|
| $ who <· Displays current users logged in + logged-in time
| $ w <· Displays who is logged into the system and WHAT THEY ARE DOING
| (procs. they are running).
| $ users <· Displays only user names who are currently logged in
| $ last <· Displays records of users-logged-in time, remote IP or PTTY, reboot time,
| $ lastlog <· Displays list of users and what day/time they logged into the system.
| $ whoami <· Tells the user who they are currently logged in as
| $ ac <· Tell how much time users are logged in.
| (sudo apt install acct, sudo dnf install psacct, ...)
| It pulls its data from the current wtmp file.
| Ex:
| $ ac
| → total 1261.72
| $ ac - <··· total hours by user
| → shark 5.24
| → nemo 5.52
| → shs 1251.00
| → total 1261.76
| $ ac -d | tail -10 <··· daily counts of how many hours users were logged in
| → Jan 11 total 0.05
| → Jan 12 total 1.36
| → ...
| → Today total 9.83
```
[[security.audit.user}]]
[[{qa.UX,use_case.documentation,]]
## Asciinema: TTY recordings
<https://asciinema.org/>
* Includes a command line tool to record the terminal plus
a Javascript player to replay the session in a browser.
<https://asciinema.org/docs/how-it-works>
* Lightweight, purely text-based approach to terminal recording.
* See demos at:
- https://asciinema.org/
- Example asciinema recording "embedded" in github markdown:
https://github.com/mvndaemon/mvnd
[[}]]
[[{monitoring.audit_framework,doc_has.diagram]]
## Linux Audit framework
* REF: <https://www.youtube.com/watch?v=x2u_prS2HmM>
```
| *ARCHITECTURE:* *LOG "TOPICS":*
| ┌───────────────────
| audit.rules auditd.conf │user
| + + │group
| │ │ │Audit ID
| │ │ │Remote Hostname
| │ │ │Remote Host Address
| │ │ ┌─> audispd │System call
| v v │ │System call args.
| auditctl ───> *auditd* ┌─> *aureport* │File
| │ ^ │ │ │File Operations
| │ ║ └─> /var/log/audit/audit.log │Session
| │ ║ │ │Success│Failure
| │ ║ └─> *ausearch* └───────────────────
| └──────┐ ║
| Running │ ║ autrace
| process │ ║ │
| + ┌───│──────────┐ │
| │ │ └─> *audit*│ │
| └──→+ ^ +←─┘
| │ ║ │ Lecture:
| │ KERNEL════╝ │ ═══ : control
| └──────────────┘ ─── : data-flow
|
| * *auditd daemon* centralize log writing to disk/network
|
| * *audit module@KERNEL* handles the audit rules
| (audtictl gets in charge of passing audit.rules to audit@KERNEL
| It also intercepts system calls.
```
* CLI UTILITIES:
```
|- *aureport* creates human-readable reports. Useful options:
| --summary
| --failed
| --start, --end (aureport understands 'today', 'yesterday', 'now',
| 'recent', 'this-week', 'this-month', 'this-year')
| --auth, --avc, --login, --user, --executable, --syscall
|
|- *ausearch* "drills deeper" into the details of a
| particular event. Ex.
| $*# ausearch -sv no --comm httpd *
| └──────────────────────────┘
| Search audit log for recently denied events triggered by
| httpd ("Apache", lighthttpd). Useful also for debugging
| SELinux related problems.
```
* autrace is the "ptrace" or "strace" for audit events
(audit the audit)
* Audispd (dispatcher) provides a plugin system to dispath
to other places (remote machines, Prometheus,...)
In RHEL 8+ it has been integrated into auditd.
(REF <https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8-beta/html/8.0_beta_release_notes/new-features>)
## Audit Daemon "Full Journey"
* INITIAL SETUP
1. Audit Daemon Configuration ·> `/etc/audit/auditd.conf`.<br/>
Defines how the audit system works once the daemon is running.
Default settings ussually are right-enough
2. Audit Rules:
*WARN: No default rules are set*
*WARN: First match wins!
- Used to define *what we are interested in auditing*
- three basic types of audit rules:
- Basic audit system parameters
- File and directory watches
- System call audits
Ex. Audit rules
```
| # basic audit system parameters
| -D ← Delete all previous rules (recommended)
| -b ← How many buffer do we want to have
| -f 1 ← 0: ignore failures
| 1: syslog
| 2: panic
| -e 1 ← 0: disable logging
| 1: enable
| 2: inmutable (not even root can change without reboot)
| # some file and dirs. watches
| -w /home/myUser/MySecrets -p rxwa
| -w /sbin/auditctl -p x
| # Example system call rule
| -a entry,always -S umask
```
3. audispd Daemon Configuration (now part of auditd)
* Daily use:
Normally you find an event class of interest with aureport and then
drill down into the nitty-gritty with ausearch
```
| $ sudo aureport --summary
| Summary Report
| ======================
| Range of time in logs: 12/31/1969 19:00:00.000 - 04/20/2019 07:42:51.715
| Selected time for report: 12/31/1969 19:00:00 - 04/20/2019 07:42:51.715
| Number of changes in configuration : 971
| Number of changes to accounts, groups, or roles: 36
| Number of logins : 2992
| Number of failed logins : 497
| Number of authentications : 3161
| Number of failed authentications : 438
| Number of users : 8
| Number of terminals : 30
| Number of host names : 16
| Number of executables : 24
| Number of commands : 14
| Number of files : 2
| Number of AVC's : 3
| Number of MAC events : 3052
| Number of failed syscalls : 0
| Number of anomaly events : 92
| Number of responses to anomaly events : 0